PetScan::extract_array: rename "dim" variable to "space"
[pet.git] / scan.cc
blobc1a15f1dae07fb9dc99c577b36be34636eb0bd17
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2015 Ecole Normale Superieure. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
32 * Leiden University.
33 */
35 #include "config.h"
37 #include <string.h>
38 #include <set>
39 #include <map>
40 #include <iostream>
41 #include <llvm/Support/raw_ostream.h>
42 #include <clang/AST/ASTContext.h>
43 #include <clang/AST/ASTDiagnostic.h>
44 #include <clang/AST/Attr.h>
45 #include <clang/AST/Expr.h>
46 #include <clang/AST/RecursiveASTVisitor.h>
48 #include <isl/id.h>
49 #include <isl/space.h>
50 #include <isl/aff.h>
51 #include <isl/set.h>
52 #include <isl/union_set.h>
54 #include "aff.h"
55 #include "array.h"
56 #include "clang.h"
57 #include "context.h"
58 #include "expr.h"
59 #include "nest.h"
60 #include "options.h"
61 #include "scan.h"
62 #include "scop.h"
63 #include "scop_plus.h"
64 #include "tree.h"
65 #include "tree2scop.h"
67 using namespace std;
68 using namespace clang;
70 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
72 switch (kind) {
73 case UO_Minus:
74 return pet_op_minus;
75 case UO_Not:
76 return pet_op_not;
77 case UO_LNot:
78 return pet_op_lnot;
79 case UO_PostInc:
80 return pet_op_post_inc;
81 case UO_PostDec:
82 return pet_op_post_dec;
83 case UO_PreInc:
84 return pet_op_pre_inc;
85 case UO_PreDec:
86 return pet_op_pre_dec;
87 default:
88 return pet_op_last;
92 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
94 switch (kind) {
95 case BO_AddAssign:
96 return pet_op_add_assign;
97 case BO_SubAssign:
98 return pet_op_sub_assign;
99 case BO_MulAssign:
100 return pet_op_mul_assign;
101 case BO_DivAssign:
102 return pet_op_div_assign;
103 case BO_Assign:
104 return pet_op_assign;
105 case BO_Add:
106 return pet_op_add;
107 case BO_Sub:
108 return pet_op_sub;
109 case BO_Mul:
110 return pet_op_mul;
111 case BO_Div:
112 return pet_op_div;
113 case BO_Rem:
114 return pet_op_mod;
115 case BO_Shl:
116 return pet_op_shl;
117 case BO_Shr:
118 return pet_op_shr;
119 case BO_EQ:
120 return pet_op_eq;
121 case BO_NE:
122 return pet_op_ne;
123 case BO_LE:
124 return pet_op_le;
125 case BO_GE:
126 return pet_op_ge;
127 case BO_LT:
128 return pet_op_lt;
129 case BO_GT:
130 return pet_op_gt;
131 case BO_And:
132 return pet_op_and;
133 case BO_Xor:
134 return pet_op_xor;
135 case BO_Or:
136 return pet_op_or;
137 case BO_LAnd:
138 return pet_op_land;
139 case BO_LOr:
140 return pet_op_lor;
141 default:
142 return pet_op_last;
146 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
147 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
149 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
150 SourceLocation(), var, false, var->getInnerLocStart(),
151 var->getType(), VK_LValue);
153 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
154 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
156 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
157 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
158 VK_LValue);
160 #else
161 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
163 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
164 var, var->getInnerLocStart(), var->getType(), VK_LValue);
166 #endif
168 #ifdef GETTYPEINFORETURNSTYPEINFO
170 static int size_in_bytes(ASTContext &context, QualType type)
172 return context.getTypeInfo(type).Width / 8;
175 #else
177 static int size_in_bytes(ASTContext &context, QualType type)
179 return context.getTypeInfo(type).first / 8;
182 #endif
184 /* Check if the element type corresponding to the given array type
185 * has a const qualifier.
187 static bool const_base(QualType qt)
189 const Type *type = qt.getTypePtr();
191 if (type->isPointerType())
192 return const_base(type->getPointeeType());
193 if (type->isArrayType()) {
194 const ArrayType *atype;
195 type = type->getCanonicalTypeInternal().getTypePtr();
196 atype = cast<ArrayType>(type);
197 return const_base(atype->getElementType());
200 return qt.isConstQualified();
203 /* Create an isl_id that refers to the named declarator "decl".
205 static __isl_give isl_id *create_decl_id(isl_ctx *ctx, NamedDecl *decl)
207 return isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
210 PetScan::~PetScan()
212 std::map<const Type *, pet_expr *>::iterator it;
213 std::map<FunctionDecl *, pet_function_summary *>::iterator it_s;
215 for (it = type_size.begin(); it != type_size.end(); ++it)
216 pet_expr_free(it->second);
217 for (it_s = summary_cache.begin(); it_s != summary_cache.end(); ++it_s)
218 pet_function_summary_free(it_s->second);
220 isl_union_map_free(value_bounds);
223 /* Report a diagnostic, unless autodetect is set.
225 void PetScan::report(Stmt *stmt, unsigned id)
227 if (options->autodetect)
228 return;
230 SourceLocation loc = stmt->getLocStart();
231 DiagnosticsEngine &diag = PP.getDiagnostics();
232 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
235 /* Called if we found something we (currently) cannot handle.
236 * We'll provide more informative warnings later.
238 * We only actually complain if autodetect is false.
240 void PetScan::unsupported(Stmt *stmt)
242 DiagnosticsEngine &diag = PP.getDiagnostics();
243 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
244 "unsupported");
245 report(stmt, id);
248 /* Report an unsupported unary operator, unless autodetect is set.
250 void PetScan::report_unsupported_unary_operator(Stmt *stmt)
252 DiagnosticsEngine &diag = PP.getDiagnostics();
253 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
254 "this type of unary operator is not supported");
255 report(stmt, id);
258 /* Report an unsupported statement type, unless autodetect is set.
260 void PetScan::report_unsupported_statement_type(Stmt *stmt)
262 DiagnosticsEngine &diag = PP.getDiagnostics();
263 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
264 "this type of statement is not supported");
265 report(stmt, id);
268 /* Report a missing prototype, unless autodetect is set.
270 void PetScan::report_prototype_required(Stmt *stmt)
272 DiagnosticsEngine &diag = PP.getDiagnostics();
273 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
274 "prototype required");
275 report(stmt, id);
278 /* Report a missing increment, unless autodetect is set.
280 void PetScan::report_missing_increment(Stmt *stmt)
282 DiagnosticsEngine &diag = PP.getDiagnostics();
283 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
284 "missing increment");
285 report(stmt, id);
288 /* Report a missing summary function, unless autodetect is set.
290 void PetScan::report_missing_summary_function(Stmt *stmt)
292 DiagnosticsEngine &diag = PP.getDiagnostics();
293 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
294 "missing summary function");
295 report(stmt, id);
298 /* Report a missing summary function body, unless autodetect is set.
300 void PetScan::report_missing_summary_function_body(Stmt *stmt)
302 DiagnosticsEngine &diag = PP.getDiagnostics();
303 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
304 "missing summary function body");
305 report(stmt, id);
308 /* Extract an integer from "val", which is assumed to be non-negative.
310 static __isl_give isl_val *extract_unsigned(isl_ctx *ctx,
311 const llvm::APInt &val)
313 unsigned n;
314 const uint64_t *data;
316 data = val.getRawData();
317 n = val.getNumWords();
318 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
321 /* Extract an integer from "val". If "is_signed" is set, then "val"
322 * is signed. Otherwise it it unsigned.
324 static __isl_give isl_val *extract_int(isl_ctx *ctx, bool is_signed,
325 llvm::APInt val)
327 int is_negative = is_signed && val.isNegative();
328 isl_val *v;
330 if (is_negative)
331 val = -val;
333 v = extract_unsigned(ctx, val);
335 if (is_negative)
336 v = isl_val_neg(v);
337 return v;
340 /* Extract an integer from "expr".
342 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
344 const Type *type = expr->getType().getTypePtr();
345 bool is_signed = type->hasSignedIntegerRepresentation();
347 return ::extract_int(ctx, is_signed, expr->getValue());
350 /* Extract an integer from "expr".
351 * Return NULL if "expr" does not (obviously) represent an integer.
353 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
355 return extract_int(expr->getSubExpr());
358 /* Extract an integer from "expr".
359 * Return NULL if "expr" does not (obviously) represent an integer.
361 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
363 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
364 return extract_int(ctx, cast<IntegerLiteral>(expr));
365 if (expr->getStmtClass() == Stmt::ParenExprClass)
366 return extract_int(cast<ParenExpr>(expr));
368 unsupported(expr);
369 return NULL;
372 /* Extract a pet_expr from the APInt "val", which is assumed
373 * to be non-negative.
375 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
377 return pet_expr_new_int(extract_unsigned(ctx, val));
380 /* Return the number of bits needed to represent the type "qt",
381 * if it is an integer type. Otherwise return 0.
382 * If qt is signed then return the opposite of the number of bits.
384 static int get_type_size(QualType qt, ASTContext &ast_context)
386 int size;
388 if (!qt->isIntegerType())
389 return 0;
391 size = ast_context.getIntWidth(qt);
392 if (!qt->isUnsignedIntegerType())
393 size = -size;
395 return size;
398 /* Return the number of bits needed to represent the type of "decl",
399 * if it is an integer type. Otherwise return 0.
400 * If qt is signed then return the opposite of the number of bits.
402 static int get_type_size(ValueDecl *decl)
404 return get_type_size(decl->getType(), decl->getASTContext());
407 /* Bound parameter "pos" of "set" to the possible values of "decl".
409 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
410 unsigned pos, ValueDecl *decl)
412 int type_size;
413 isl_ctx *ctx;
414 isl_val *bound;
416 ctx = isl_set_get_ctx(set);
417 type_size = get_type_size(decl);
418 if (type_size == 0)
419 isl_die(ctx, isl_error_invalid, "not an integer type",
420 return isl_set_free(set));
421 if (type_size > 0) {
422 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
423 bound = isl_val_int_from_ui(ctx, type_size);
424 bound = isl_val_2exp(bound);
425 bound = isl_val_sub_ui(bound, 1);
426 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
427 } else {
428 bound = isl_val_int_from_ui(ctx, -type_size - 1);
429 bound = isl_val_2exp(bound);
430 bound = isl_val_sub_ui(bound, 1);
431 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
432 isl_val_copy(bound));
433 bound = isl_val_neg(bound);
434 bound = isl_val_sub_ui(bound, 1);
435 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
438 return set;
441 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
443 return extract_index_expr(expr->getSubExpr());
446 /* Return the depth of an array of the given type.
448 static int array_depth(const Type *type)
450 if (type->isPointerType())
451 return 1 + array_depth(type->getPointeeType().getTypePtr());
452 if (type->isArrayType()) {
453 const ArrayType *atype;
454 type = type->getCanonicalTypeInternal().getTypePtr();
455 atype = cast<ArrayType>(type);
456 return 1 + array_depth(atype->getElementType().getTypePtr());
458 return 0;
461 /* Return the depth of the array accessed by the index expression "index".
462 * If "index" is an affine expression, i.e., if it does not access
463 * any array, then return 1.
464 * If "index" represent a member access, i.e., if its range is a wrapped
465 * relation, then return the sum of the depth of the array of structures
466 * and that of the member inside the structure.
468 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
470 isl_id *id;
471 ValueDecl *decl;
473 if (!index)
474 return -1;
476 if (isl_multi_pw_aff_range_is_wrapping(index)) {
477 int domain_depth, range_depth;
478 isl_multi_pw_aff *domain, *range;
480 domain = isl_multi_pw_aff_copy(index);
481 domain = isl_multi_pw_aff_range_factor_domain(domain);
482 domain_depth = extract_depth(domain);
483 isl_multi_pw_aff_free(domain);
484 range = isl_multi_pw_aff_copy(index);
485 range = isl_multi_pw_aff_range_factor_range(range);
486 range_depth = extract_depth(range);
487 isl_multi_pw_aff_free(range);
489 return domain_depth + range_depth;
492 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
493 return 1;
495 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
496 if (!id)
497 return -1;
498 decl = (ValueDecl *) isl_id_get_user(id);
499 isl_id_free(id);
501 return array_depth(decl->getType().getTypePtr());
504 /* Return the depth of the array accessed by the access expression "expr".
506 static int extract_depth(__isl_keep pet_expr *expr)
508 isl_multi_pw_aff *index;
509 int depth;
511 index = pet_expr_access_get_index(expr);
512 depth = extract_depth(index);
513 isl_multi_pw_aff_free(index);
515 return depth;
518 /* Construct a pet_expr representing an index expression for an access
519 * to the variable referenced by "expr".
521 * If "expr" references an enum constant, then return an integer expression
522 * instead, representing the value of the enum constant.
524 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
526 return extract_index_expr(expr->getDecl());
529 /* Construct a pet_expr representing an index expression for an access
530 * to the variable "decl".
532 * If "decl" is an enum constant, then we return an integer expression
533 * instead, representing the value of the enum constant.
535 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
537 isl_id *id;
538 isl_space *space;
540 if (isa<EnumConstantDecl>(decl))
541 return extract_expr(cast<EnumConstantDecl>(decl));
543 id = create_decl_id(ctx, decl);
544 space = isl_space_alloc(ctx, 0, 0, 0);
545 space = isl_space_set_tuple_id(space, isl_dim_out, id);
547 return pet_expr_from_index(isl_multi_pw_aff_zero(space));
550 /* Construct a pet_expr representing the index expression "expr"
551 * Return NULL on error.
553 * If "expr" is a reference to an enum constant, then return
554 * an integer expression instead, representing the value of the enum constant.
556 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
558 switch (expr->getStmtClass()) {
559 case Stmt::ImplicitCastExprClass:
560 return extract_index_expr(cast<ImplicitCastExpr>(expr));
561 case Stmt::DeclRefExprClass:
562 return extract_index_expr(cast<DeclRefExpr>(expr));
563 case Stmt::ArraySubscriptExprClass:
564 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
565 case Stmt::IntegerLiteralClass:
566 return extract_expr(cast<IntegerLiteral>(expr));
567 case Stmt::MemberExprClass:
568 return extract_index_expr(cast<MemberExpr>(expr));
569 default:
570 unsupported(expr);
572 return NULL;
575 /* Extract an index expression from the given array subscript expression.
577 * We first extract an index expression from the base.
578 * This will result in an index expression with a range that corresponds
579 * to the earlier indices.
580 * We then extract the current index and let
581 * pet_expr_access_subscript combine the two.
583 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
585 Expr *base = expr->getBase();
586 Expr *idx = expr->getIdx();
587 pet_expr *index;
588 pet_expr *base_expr;
590 base_expr = extract_index_expr(base);
591 index = extract_expr(idx);
593 base_expr = pet_expr_access_subscript(base_expr, index);
595 return base_expr;
598 /* Extract an index expression from a member expression.
600 * If the base access (to the structure containing the member)
601 * is of the form
603 * A[..]
605 * and the member is called "f", then the member access is of
606 * the form
608 * A_f[A[..] -> f[]]
610 * If the member access is to an anonymous struct, then simply return
612 * A[..]
614 * If the member access in the source code is of the form
616 * A->f
618 * then it is treated as
620 * A[0].f
622 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
624 Expr *base = expr->getBase();
625 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
626 pet_expr *base_index;
627 isl_id *id;
629 base_index = extract_index_expr(base);
631 if (expr->isArrow()) {
632 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
633 base_index = pet_expr_access_subscript(base_index, index);
636 if (field->isAnonymousStructOrUnion())
637 return base_index;
639 id = create_decl_id(ctx, field);
641 return pet_expr_access_member(base_index, id);
644 /* Mark the given access pet_expr as a write.
646 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
648 access = pet_expr_access_set_write(access, 1);
649 access = pet_expr_access_set_read(access, 0);
651 return access;
654 /* Mark the given (read) access pet_expr as also possibly being written.
655 * That is, initialize the may write access relation from the may read relation
656 * and initialize the must write access relation to the empty relation.
658 static __isl_give pet_expr *mark_may_write(__isl_take pet_expr *expr)
660 isl_union_map *access;
661 isl_union_map *empty;
663 access = pet_expr_access_get_dependent_access(expr,
664 pet_expr_access_may_read);
665 empty = isl_union_map_empty(isl_union_map_get_space(access));
666 expr = pet_expr_access_set_access(expr, pet_expr_access_may_write,
667 access);
668 expr = pet_expr_access_set_access(expr, pet_expr_access_must_write,
669 empty);
671 return expr;
674 /* Construct a pet_expr representing a unary operator expression.
676 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
678 int type_size;
679 pet_expr *arg;
680 enum pet_op_type op;
682 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
683 if (op == pet_op_last) {
684 report_unsupported_unary_operator(expr);
685 return NULL;
688 arg = extract_expr(expr->getSubExpr());
690 if (expr->isIncrementDecrementOp() &&
691 pet_expr_get_type(arg) == pet_expr_access) {
692 arg = mark_write(arg);
693 arg = pet_expr_access_set_read(arg, 1);
696 type_size = get_type_size(expr->getType(), ast_context);
697 return pet_expr_new_unary(type_size, op, arg);
700 /* Construct a pet_expr representing a binary operator expression.
702 * If the top level operator is an assignment and the LHS is an access,
703 * then we mark that access as a write. If the operator is a compound
704 * assignment, the access is marked as both a read and a write.
706 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
708 int type_size;
709 pet_expr *lhs, *rhs;
710 enum pet_op_type op;
712 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
713 if (op == pet_op_last) {
714 unsupported(expr);
715 return NULL;
718 lhs = extract_expr(expr->getLHS());
719 rhs = extract_expr(expr->getRHS());
721 if (expr->isAssignmentOp() &&
722 pet_expr_get_type(lhs) == pet_expr_access) {
723 lhs = mark_write(lhs);
724 if (expr->isCompoundAssignmentOp())
725 lhs = pet_expr_access_set_read(lhs, 1);
728 type_size = get_type_size(expr->getType(), ast_context);
729 return pet_expr_new_binary(type_size, op, lhs, rhs);
732 /* Construct a pet_tree for a variable declaration.
734 __isl_give pet_tree *PetScan::extract(Decl *decl)
736 VarDecl *vd;
737 pet_expr *lhs, *rhs;
738 pet_tree *tree;
740 vd = cast<VarDecl>(decl);
742 lhs = extract_access_expr(vd);
743 lhs = mark_write(lhs);
744 if (!vd->getInit())
745 tree = pet_tree_new_decl(lhs);
746 else {
747 rhs = extract_expr(vd->getInit());
748 tree = pet_tree_new_decl_init(lhs, rhs);
751 return tree;
754 /* Construct a pet_tree for a variable declaration statement.
755 * If the declaration statement declares multiple variables,
756 * then return a group of pet_trees, one for each declared variable.
758 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
760 pet_tree *tree;
761 unsigned n;
763 if (!stmt->isSingleDecl()) {
764 const DeclGroup &group = stmt->getDeclGroup().getDeclGroup();
765 n = group.size();
766 tree = pet_tree_new_block(ctx, 0, n);
768 for (int i = 0; i < n; ++i) {
769 pet_tree *tree_i;
770 pet_loc *loc;
772 tree_i = extract(group[i]);
773 loc = construct_pet_loc(group[i]->getSourceRange(),
774 false);
775 tree_i = pet_tree_set_loc(tree_i, loc);
776 tree = pet_tree_block_add_child(tree, tree_i);
779 return tree;
782 return extract(stmt->getSingleDecl());
785 /* Construct a pet_expr representing a conditional operation.
787 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
789 pet_expr *cond, *lhs, *rhs;
790 isl_pw_aff *pa;
792 cond = extract_expr(expr->getCond());
793 lhs = extract_expr(expr->getTrueExpr());
794 rhs = extract_expr(expr->getFalseExpr());
796 return pet_expr_new_ternary(cond, lhs, rhs);
799 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
801 return extract_expr(expr->getSubExpr());
804 /* Construct a pet_expr representing a floating point value.
806 * If the floating point literal does not appear in a macro,
807 * then we use the original representation in the source code
808 * as the string representation. Otherwise, we use the pretty
809 * printer to produce a string representation.
811 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
813 double d;
814 string s;
815 const LangOptions &LO = PP.getLangOpts();
816 SourceLocation loc = expr->getLocation();
818 if (!loc.isMacroID()) {
819 SourceManager &SM = PP.getSourceManager();
820 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
821 s = string(SM.getCharacterData(loc), len);
822 } else {
823 llvm::raw_string_ostream S(s);
824 expr->printPretty(S, 0, PrintingPolicy(LO));
825 S.str();
827 d = expr->getValueAsApproximateDouble();
828 return pet_expr_new_double(ctx, d, s.c_str());
831 /* Convert the index expression "index" into an access pet_expr of type "qt".
833 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
834 __isl_take pet_expr *index)
836 int depth;
837 int type_size;
839 depth = extract_depth(index);
840 type_size = get_type_size(qt, ast_context);
842 index = pet_expr_set_type_size(index, type_size);
843 index = pet_expr_access_set_depth(index, depth);
845 return index;
848 /* Extract an index expression from "expr" and then convert it into
849 * an access pet_expr.
851 * If "expr" is a reference to an enum constant, then return
852 * an integer expression instead, representing the value of the enum constant.
854 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
856 pet_expr *index;
858 index = extract_index_expr(expr);
860 if (pet_expr_get_type(index) == pet_expr_int)
861 return index;
863 return extract_access_expr(expr->getType(), index);
866 /* Extract an index expression from "decl" and then convert it into
867 * an access pet_expr.
869 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
871 return extract_access_expr(decl->getType(), extract_index_expr(decl));
874 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
876 return extract_expr(expr->getSubExpr());
879 /* Extract an assume statement from the argument "expr"
880 * of a __pencil_assume statement.
882 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
884 return pet_expr_new_unary(0, pet_op_assume, extract_expr(expr));
887 /* Construct a pet_expr corresponding to the function call argument "expr".
888 * The argument appears in position "pos" of a call to function "fd".
890 * If we are passing along a pointer to an array element
891 * or an entire row or even higher dimensional slice of an array,
892 * then the function being called may write into the array.
894 * We assume here that if the function is declared to take a pointer
895 * to a const type, then the function may only perform a read
896 * and that otherwise, it may either perform a read or a write (or both).
897 * We only perform this check if "detect_writes" is set.
899 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
900 Expr *expr, bool detect_writes)
902 pet_expr *res;
903 int is_addr = 0, is_partial = 0;
905 expr = pet_clang_strip_casts(expr);
906 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
907 UnaryOperator *op = cast<UnaryOperator>(expr);
908 if (op->getOpcode() == UO_AddrOf) {
909 is_addr = 1;
910 expr = op->getSubExpr();
913 res = extract_expr(expr);
914 if (!res)
915 return NULL;
916 if (array_depth(expr->getType().getTypePtr()) > 0)
917 is_partial = 1;
918 if (detect_writes && (is_addr || is_partial) &&
919 pet_expr_get_type(res) == pet_expr_access) {
920 ParmVarDecl *parm;
921 if (!fd->hasPrototype()) {
922 report_prototype_required(expr);
923 return pet_expr_free(res);
925 parm = fd->getParamDecl(pos);
926 if (!const_base(parm->getType()))
927 res = mark_may_write(res);
930 if (is_addr)
931 res = pet_expr_new_unary(0, pet_op_address_of, res);
932 return res;
935 /* Find the first FunctionDecl with the given name.
936 * "call" is the corresponding call expression and is only used
937 * for reporting errors.
939 * Return NULL on error.
941 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
943 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
944 DeclContext::decl_iterator begin = tu->decls_begin();
945 DeclContext::decl_iterator end = tu->decls_end();
946 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
947 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
948 if (!fd)
949 continue;
950 if (fd->getName().str().compare(name) != 0)
951 continue;
952 if (fd->hasBody())
953 return fd;
954 report_missing_summary_function_body(call);
955 return NULL;
957 report_missing_summary_function(call);
958 return NULL;
961 /* Return the FunctionDecl for the summary function associated to the
962 * function called by "call".
964 * In particular, if the pencil option is set, then
965 * search for an annotate attribute formatted as
966 * "pencil_access(name)", where "name" is the name of the summary function.
968 * If no summary function was specified, then return the FunctionDecl
969 * that is actually being called.
971 * Return NULL on error.
973 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
975 FunctionDecl *decl = call->getDirectCallee();
976 if (!decl)
977 return NULL;
979 if (!options->pencil)
980 return decl;
982 specific_attr_iterator<AnnotateAttr> begin, end, i;
983 begin = decl->specific_attr_begin<AnnotateAttr>();
984 end = decl->specific_attr_end<AnnotateAttr>();
985 for (i = begin; i != end; ++i) {
986 string attr = (*i)->getAnnotation().str();
988 const char prefix[] = "pencil_access(";
989 size_t start = attr.find(prefix);
990 if (start == string::npos)
991 continue;
992 start += strlen(prefix);
993 string name = attr.substr(start, attr.find(')') - start);
995 return find_decl_from_name(call, name);
998 return decl;
1001 /* Construct a pet_expr representing a function call.
1003 * In the special case of a "call" to __pencil_assume,
1004 * construct an assume expression instead.
1006 * In the case of a "call" to __pencil_kill, the arguments
1007 * are neither read nor written (only killed), so there
1008 * is no need to check for writes to these arguments.
1010 * __pencil_assume and __pencil_kill are only recognized
1011 * when the pencil option is set.
1013 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1015 pet_expr *res = NULL;
1016 FunctionDecl *fd;
1017 string name;
1018 unsigned n_arg;
1019 bool is_kill;
1021 fd = expr->getDirectCallee();
1022 if (!fd) {
1023 unsupported(expr);
1024 return NULL;
1027 name = fd->getDeclName().getAsString();
1028 n_arg = expr->getNumArgs();
1030 if (options->pencil && n_arg == 1 && name == "__pencil_assume")
1031 return extract_assume(expr->getArg(0));
1032 is_kill = options->pencil && name == "__pencil_kill";
1034 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1035 if (!res)
1036 return NULL;
1038 for (int i = 0; i < n_arg; ++i) {
1039 Expr *arg = expr->getArg(i);
1040 res = pet_expr_set_arg(res, i,
1041 PetScan::extract_argument(fd, i, arg, !is_kill));
1044 fd = get_summary_function(expr);
1045 if (!fd)
1046 return pet_expr_free(res);
1048 res = set_summary(res, fd);
1050 return res;
1053 /* Construct a pet_expr representing a (C style) cast.
1055 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1057 pet_expr *arg;
1058 QualType type;
1060 arg = extract_expr(expr->getSubExpr());
1061 if (!arg)
1062 return NULL;
1064 type = expr->getTypeAsWritten();
1065 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1068 /* Construct a pet_expr representing an integer.
1070 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1072 return pet_expr_new_int(extract_int(expr));
1075 /* Construct a pet_expr representing the integer enum constant "ecd".
1077 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
1079 isl_val *v;
1080 const llvm::APSInt &init = ecd->getInitVal();
1081 v = ::extract_int(ctx, init.isSigned(), init);
1082 return pet_expr_new_int(v);
1085 /* Try and construct a pet_expr representing "expr".
1087 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1089 switch (expr->getStmtClass()) {
1090 case Stmt::UnaryOperatorClass:
1091 return extract_expr(cast<UnaryOperator>(expr));
1092 case Stmt::CompoundAssignOperatorClass:
1093 case Stmt::BinaryOperatorClass:
1094 return extract_expr(cast<BinaryOperator>(expr));
1095 case Stmt::ImplicitCastExprClass:
1096 return extract_expr(cast<ImplicitCastExpr>(expr));
1097 case Stmt::ArraySubscriptExprClass:
1098 case Stmt::DeclRefExprClass:
1099 case Stmt::MemberExprClass:
1100 return extract_access_expr(expr);
1101 case Stmt::IntegerLiteralClass:
1102 return extract_expr(cast<IntegerLiteral>(expr));
1103 case Stmt::FloatingLiteralClass:
1104 return extract_expr(cast<FloatingLiteral>(expr));
1105 case Stmt::ParenExprClass:
1106 return extract_expr(cast<ParenExpr>(expr));
1107 case Stmt::ConditionalOperatorClass:
1108 return extract_expr(cast<ConditionalOperator>(expr));
1109 case Stmt::CallExprClass:
1110 return extract_expr(cast<CallExpr>(expr));
1111 case Stmt::CStyleCastExprClass:
1112 return extract_expr(cast<CStyleCastExpr>(expr));
1113 default:
1114 unsupported(expr);
1116 return NULL;
1119 /* Check if the given initialization statement is an assignment.
1120 * If so, return that assignment. Otherwise return NULL.
1122 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1124 BinaryOperator *ass;
1126 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1127 return NULL;
1129 ass = cast<BinaryOperator>(init);
1130 if (ass->getOpcode() != BO_Assign)
1131 return NULL;
1133 return ass;
1136 /* Check if the given initialization statement is a declaration
1137 * of a single variable.
1138 * If so, return that declaration. Otherwise return NULL.
1140 Decl *PetScan::initialization_declaration(Stmt *init)
1142 DeclStmt *decl;
1144 if (init->getStmtClass() != Stmt::DeclStmtClass)
1145 return NULL;
1147 decl = cast<DeclStmt>(init);
1149 if (!decl->isSingleDecl())
1150 return NULL;
1152 return decl->getSingleDecl();
1155 /* Given the assignment operator in the initialization of a for loop,
1156 * extract the induction variable, i.e., the (integer)variable being
1157 * assigned.
1159 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1161 Expr *lhs;
1162 DeclRefExpr *ref;
1163 ValueDecl *decl;
1164 const Type *type;
1166 lhs = init->getLHS();
1167 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1168 unsupported(init);
1169 return NULL;
1172 ref = cast<DeclRefExpr>(lhs);
1173 decl = ref->getDecl();
1174 type = decl->getType().getTypePtr();
1176 if (!type->isIntegerType()) {
1177 unsupported(lhs);
1178 return NULL;
1181 return decl;
1184 /* Given the initialization statement of a for loop and the single
1185 * declaration in this initialization statement,
1186 * extract the induction variable, i.e., the (integer) variable being
1187 * declared.
1189 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1191 VarDecl *vd;
1193 vd = cast<VarDecl>(decl);
1195 const QualType type = vd->getType();
1196 if (!type->isIntegerType()) {
1197 unsupported(init);
1198 return NULL;
1201 if (!vd->getInit()) {
1202 unsupported(init);
1203 return NULL;
1206 return vd;
1209 /* Check that op is of the form iv++ or iv--.
1210 * Return a pet_expr representing "1" or "-1" accordingly.
1212 __isl_give pet_expr *PetScan::extract_unary_increment(
1213 clang::UnaryOperator *op, clang::ValueDecl *iv)
1215 Expr *sub;
1216 DeclRefExpr *ref;
1217 isl_val *v;
1219 if (!op->isIncrementDecrementOp()) {
1220 unsupported(op);
1221 return NULL;
1224 sub = op->getSubExpr();
1225 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1226 unsupported(op);
1227 return NULL;
1230 ref = cast<DeclRefExpr>(sub);
1231 if (ref->getDecl() != iv) {
1232 unsupported(op);
1233 return NULL;
1236 if (op->isIncrementOp())
1237 v = isl_val_one(ctx);
1238 else
1239 v = isl_val_negone(ctx);
1241 return pet_expr_new_int(v);
1244 /* Check if op is of the form
1246 * iv = expr
1248 * and return the increment "expr - iv" as a pet_expr.
1250 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1251 clang::ValueDecl *iv)
1253 int type_size;
1254 Expr *lhs;
1255 DeclRefExpr *ref;
1256 pet_expr *expr, *expr_iv;
1258 if (op->getOpcode() != BO_Assign) {
1259 unsupported(op);
1260 return NULL;
1263 lhs = op->getLHS();
1264 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1265 unsupported(op);
1266 return NULL;
1269 ref = cast<DeclRefExpr>(lhs);
1270 if (ref->getDecl() != iv) {
1271 unsupported(op);
1272 return NULL;
1275 expr = extract_expr(op->getRHS());
1276 expr_iv = extract_expr(lhs);
1278 type_size = get_type_size(iv->getType(), ast_context);
1279 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1282 /* Check that op is of the form iv += cst or iv -= cst
1283 * and return a pet_expr corresponding to cst or -cst accordingly.
1285 __isl_give pet_expr *PetScan::extract_compound_increment(
1286 CompoundAssignOperator *op, clang::ValueDecl *iv)
1288 Expr *lhs;
1289 DeclRefExpr *ref;
1290 bool neg = false;
1291 pet_expr *expr;
1292 BinaryOperatorKind opcode;
1294 opcode = op->getOpcode();
1295 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1296 unsupported(op);
1297 return NULL;
1299 if (opcode == BO_SubAssign)
1300 neg = true;
1302 lhs = op->getLHS();
1303 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1304 unsupported(op);
1305 return NULL;
1308 ref = cast<DeclRefExpr>(lhs);
1309 if (ref->getDecl() != iv) {
1310 unsupported(op);
1311 return NULL;
1314 expr = extract_expr(op->getRHS());
1315 if (neg) {
1316 int type_size;
1317 type_size = get_type_size(op->getType(), ast_context);
1318 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1321 return expr;
1324 /* Check that the increment of the given for loop increments
1325 * (or decrements) the induction variable "iv" and return
1326 * the increment as a pet_expr if successful.
1328 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1329 ValueDecl *iv)
1331 Stmt *inc = stmt->getInc();
1333 if (!inc) {
1334 report_missing_increment(stmt);
1335 return NULL;
1338 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1339 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1340 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1341 return extract_compound_increment(
1342 cast<CompoundAssignOperator>(inc), iv);
1343 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1344 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1346 unsupported(inc);
1347 return NULL;
1350 /* Construct a pet_tree for a while loop.
1352 * If we were only able to extract part of the body, then simply
1353 * return that part.
1355 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1357 pet_expr *pe_cond;
1358 pet_tree *tree;
1360 tree = extract(stmt->getBody());
1361 if (partial)
1362 return tree;
1363 pe_cond = extract_expr(stmt->getCond());
1364 tree = pet_tree_new_while(pe_cond, tree);
1366 return tree;
1369 /* Construct a pet_tree for a for statement.
1370 * The for loop is required to be of one of the following forms
1372 * for (i = init; condition; ++i)
1373 * for (i = init; condition; --i)
1374 * for (i = init; condition; i += constant)
1375 * for (i = init; condition; i -= constant)
1377 * We extract a pet_tree for the body and then include it in a pet_tree
1378 * of type pet_tree_for.
1380 * As a special case, we also allow a for loop of the form
1382 * for (;;)
1384 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1386 * If we were only able to extract part of the body, then simply
1387 * return that part.
1389 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1391 BinaryOperator *ass;
1392 Decl *decl;
1393 Stmt *init;
1394 Expr *lhs, *rhs;
1395 ValueDecl *iv;
1396 pet_tree *tree;
1397 struct pet_scop *scop;
1398 int independent;
1399 int declared;
1400 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1402 independent = is_current_stmt_marked_independent();
1404 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1405 tree = extract(stmt->getBody());
1406 if (partial)
1407 return tree;
1408 tree = pet_tree_new_infinite_loop(tree);
1409 return tree;
1412 init = stmt->getInit();
1413 if (!init) {
1414 unsupported(stmt);
1415 return NULL;
1417 if ((ass = initialization_assignment(init)) != NULL) {
1418 iv = extract_induction_variable(ass);
1419 if (!iv)
1420 return NULL;
1421 lhs = ass->getLHS();
1422 rhs = ass->getRHS();
1423 } else if ((decl = initialization_declaration(init)) != NULL) {
1424 VarDecl *var = extract_induction_variable(init, decl);
1425 if (!var)
1426 return NULL;
1427 iv = var;
1428 rhs = var->getInit();
1429 lhs = create_DeclRefExpr(var);
1430 } else {
1431 unsupported(stmt->getInit());
1432 return NULL;
1435 declared = !initialization_assignment(stmt->getInit());
1436 tree = extract(stmt->getBody());
1437 if (partial)
1438 return tree;
1439 pe_iv = extract_access_expr(iv);
1440 pe_iv = mark_write(pe_iv);
1441 pe_init = extract_expr(rhs);
1442 if (!stmt->getCond())
1443 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1444 else
1445 pe_cond = extract_expr(stmt->getCond());
1446 pe_inc = extract_increment(stmt, iv);
1447 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1448 pe_inc, tree);
1449 return tree;
1452 /* Try and construct a pet_tree corresponding to a compound statement.
1454 * "skip_declarations" is set if we should skip initial declarations
1455 * in the children of the compound statements.
1457 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1458 bool skip_declarations)
1460 return extract(stmt->children(), true, skip_declarations);
1463 /* Return the file offset of the expansion location of "Loc".
1465 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1467 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1470 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1472 /* Return a SourceLocation for the location after the first semicolon
1473 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1474 * call it and also skip trailing spaces and newline.
1476 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1477 const LangOptions &LO)
1479 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1482 #else
1484 /* Return a SourceLocation for the location after the first semicolon
1485 * after "loc". If Lexer::findLocationAfterToken is not available,
1486 * we look in the underlying character data for the first semicolon.
1488 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1489 const LangOptions &LO)
1491 const char *semi;
1492 const char *s = SM.getCharacterData(loc);
1494 semi = strchr(s, ';');
1495 if (!semi)
1496 return SourceLocation();
1497 return loc.getFileLocWithOffset(semi + 1 - s);
1500 #endif
1502 /* If the token at "loc" is the first token on the line, then return
1503 * a location referring to the start of the line and set *indent
1504 * to the indentation of "loc"
1505 * Otherwise, return "loc" and set *indent to "".
1507 * This function is used to extend a scop to the start of the line
1508 * if the first token of the scop is also the first token on the line.
1510 * We look for the first token on the line. If its location is equal to "loc",
1511 * then the latter is the location of the first token on the line.
1513 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1514 SourceManager &SM, const LangOptions &LO, char **indent)
1516 std::pair<FileID, unsigned> file_offset_pair;
1517 llvm::StringRef file;
1518 const char *pos;
1519 Token tok;
1520 SourceLocation token_loc, line_loc;
1521 int col;
1522 const char *s;
1524 loc = SM.getExpansionLoc(loc);
1525 col = SM.getExpansionColumnNumber(loc);
1526 line_loc = loc.getLocWithOffset(1 - col);
1527 file_offset_pair = SM.getDecomposedLoc(line_loc);
1528 file = SM.getBufferData(file_offset_pair.first, NULL);
1529 pos = file.data() + file_offset_pair.second;
1531 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1532 file.begin(), pos, file.end());
1533 lexer.LexFromRawLexer(tok);
1534 token_loc = tok.getLocation();
1536 s = SM.getCharacterData(line_loc);
1537 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1539 if (token_loc == loc)
1540 return line_loc;
1541 else
1542 return loc;
1545 /* Construct a pet_loc corresponding to the region covered by "range".
1546 * If "skip_semi" is set, then we assume "range" is followed by
1547 * a semicolon and also include this semicolon.
1549 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1550 bool skip_semi)
1552 SourceLocation loc = range.getBegin();
1553 SourceManager &SM = PP.getSourceManager();
1554 const LangOptions &LO = PP.getLangOpts();
1555 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1556 unsigned start, end;
1557 char *indent;
1559 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1560 start = getExpansionOffset(SM, loc);
1561 loc = range.getEnd();
1562 if (skip_semi)
1563 loc = location_after_semi(loc, SM, LO);
1564 else
1565 loc = PP.getLocForEndOfToken(loc);
1566 end = getExpansionOffset(SM, loc);
1568 return pet_loc_alloc(ctx, start, end, line, indent);
1571 /* Convert a top-level pet_expr to an expression pet_tree.
1573 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1574 SourceRange range, bool skip_semi)
1576 pet_loc *loc;
1577 pet_tree *tree;
1579 tree = pet_tree_new_expr(expr);
1580 loc = construct_pet_loc(range, skip_semi);
1581 tree = pet_tree_set_loc(tree, loc);
1583 return tree;
1586 /* Construct a pet_tree for an if statement.
1588 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1590 pet_expr *pe_cond;
1591 pet_tree *tree, *tree_else;
1592 struct pet_scop *scop;
1593 int int_size;
1595 pe_cond = extract_expr(stmt->getCond());
1596 tree = extract(stmt->getThen());
1597 if (stmt->getElse()) {
1598 tree_else = extract(stmt->getElse());
1599 if (options->autodetect) {
1600 if (tree && !tree_else) {
1601 partial = true;
1602 pet_expr_free(pe_cond);
1603 return tree;
1605 if (!tree && tree_else) {
1606 partial = true;
1607 pet_expr_free(pe_cond);
1608 return tree_else;
1611 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1612 } else
1613 tree = pet_tree_new_if(pe_cond, tree);
1614 return tree;
1617 /* Try and construct a pet_tree for a label statement.
1619 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1621 isl_id *label;
1622 pet_tree *tree;
1624 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1626 tree = extract(stmt->getSubStmt());
1627 tree = pet_tree_set_label(tree, label);
1628 return tree;
1631 /* Update the location of "tree" to include the source range of "stmt".
1633 * Actually, we create a new location based on the source range of "stmt" and
1634 * then extend this new location to include the region of the original location.
1635 * This ensures that the line number of the final location refers to "stmt".
1637 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1639 pet_loc *loc, *tree_loc;
1641 tree_loc = pet_tree_get_loc(tree);
1642 loc = construct_pet_loc(stmt->getSourceRange(), false);
1643 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1644 pet_loc_free(tree_loc);
1646 tree = pet_tree_set_loc(tree, loc);
1647 return tree;
1650 /* Try and construct a pet_tree corresponding to "stmt".
1652 * If "stmt" is a compound statement, then "skip_declarations"
1653 * indicates whether we should skip initial declarations in the
1654 * compound statement.
1656 * If the constructed pet_tree is not a (possibly) partial representation
1657 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1658 * In particular, if skip_declarations is set, then we may have skipped
1659 * declarations inside "stmt" and so the pet_scop may not represent
1660 * the entire "stmt".
1661 * Note that this function may be called with "stmt" referring to the entire
1662 * body of the function, including the outer braces. In such cases,
1663 * skip_declarations will be set and the braces will not be taken into
1664 * account in tree->loc.
1666 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
1668 pet_tree *tree;
1670 set_current_stmt(stmt);
1672 if (isa<Expr>(stmt))
1673 return extract(extract_expr(cast<Expr>(stmt)),
1674 stmt->getSourceRange(), true);
1676 switch (stmt->getStmtClass()) {
1677 case Stmt::WhileStmtClass:
1678 tree = extract(cast<WhileStmt>(stmt));
1679 break;
1680 case Stmt::ForStmtClass:
1681 tree = extract_for(cast<ForStmt>(stmt));
1682 break;
1683 case Stmt::IfStmtClass:
1684 tree = extract(cast<IfStmt>(stmt));
1685 break;
1686 case Stmt::CompoundStmtClass:
1687 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
1688 break;
1689 case Stmt::LabelStmtClass:
1690 tree = extract(cast<LabelStmt>(stmt));
1691 break;
1692 case Stmt::ContinueStmtClass:
1693 tree = pet_tree_new_continue(ctx);
1694 break;
1695 case Stmt::BreakStmtClass:
1696 tree = pet_tree_new_break(ctx);
1697 break;
1698 case Stmt::DeclStmtClass:
1699 tree = extract(cast<DeclStmt>(stmt));
1700 break;
1701 default:
1702 report_unsupported_statement_type(stmt);
1703 return NULL;
1706 if (partial || skip_declarations)
1707 return tree;
1709 return update_loc(tree, stmt);
1712 /* Given a sequence of statements "stmt_range" of which the first "n_decl"
1713 * are declarations and of which the remaining statements are represented
1714 * by "tree", try and extend "tree" to include the last sequence of
1715 * the initial declarations that can be completely extracted.
1717 * We start collecting the initial declarations and start over
1718 * whenever we come across a declaration that we cannot extract.
1719 * If we have been able to extract any declarations, then we
1720 * copy over the contents of "tree" at the end of the declarations.
1721 * Otherwise, we simply return the original "tree".
1723 __isl_give pet_tree *PetScan::insert_initial_declarations(
1724 __isl_take pet_tree *tree, int n_decl, StmtRange stmt_range)
1726 StmtIterator i;
1727 pet_tree *res;
1728 int n_stmt;
1729 int is_block;
1730 int j;
1732 n_stmt = pet_tree_block_n_child(tree);
1733 is_block = pet_tree_block_get_block(tree);
1734 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
1736 for (i = stmt_range.first; n_decl; ++i, --n_decl) {
1737 Stmt *child = *i;
1738 pet_tree *tree_i;
1740 tree_i = extract(child);
1741 if (tree_i && !partial) {
1742 res = pet_tree_block_add_child(res, tree_i);
1743 continue;
1745 pet_tree_free(tree_i);
1746 partial = false;
1747 if (pet_tree_block_n_child(res) == 0)
1748 continue;
1749 pet_tree_free(res);
1750 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
1753 if (pet_tree_block_n_child(res) == 0) {
1754 pet_tree_free(res);
1755 return tree;
1758 for (j = 0; j < n_stmt; ++j) {
1759 pet_tree *tree_i;
1761 tree_i = pet_tree_block_get_child(tree, j);
1762 res = pet_tree_block_add_child(res, tree_i);
1764 pet_tree_free(tree);
1766 return res;
1769 /* Try and construct a pet_tree corresponding to (part of)
1770 * a sequence of statements.
1772 * "block" is set if the sequence represents the children of
1773 * a compound statement.
1774 * "skip_declarations" is set if we should skip initial declarations
1775 * in the sequence of statements.
1777 * If autodetect is set, then we allow the extraction of only a subrange
1778 * of the sequence of statements. However, if there is at least one
1779 * kill and there is some subsequent statement for which we could not
1780 * construct a tree, then turn off the "block" property of the tree
1781 * such that no extra kill will be introduced at the end of the (partial)
1782 * block. If, on the other hand, the final range contains
1783 * no statements, then we discard the entire range.
1785 * If the entire range was extracted, apart from some initial declarations,
1786 * then we try and extend the range with the latest of those initial
1787 * declarations.
1789 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
1790 bool skip_declarations)
1792 StmtIterator i;
1793 int j, skip;
1794 bool has_kills = false;
1795 bool partial_range = false;
1796 pet_tree *tree;
1798 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
1801 tree = pet_tree_new_block(ctx, block, j);
1803 skip = 0;
1804 i = stmt_range.first;
1805 if (skip_declarations)
1806 for (; i != stmt_range.second; ++i) {
1807 if ((*i)->getStmtClass() != Stmt::DeclStmtClass)
1808 break;
1809 ++skip;
1812 for (; i != stmt_range.second; ++i) {
1813 Stmt *child = *i;
1814 pet_tree *tree_i;
1816 tree_i = extract(child);
1817 if (pet_tree_block_n_child(tree) != 0 && partial) {
1818 pet_tree_free(tree_i);
1819 break;
1821 if (tree_i && child->getStmtClass() == Stmt::DeclStmtClass &&
1822 block)
1823 has_kills = true;
1824 if (options->autodetect) {
1825 if (tree_i)
1826 tree = pet_tree_block_add_child(tree, tree_i);
1827 else
1828 partial_range = true;
1829 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
1830 partial = true;
1831 } else {
1832 tree = pet_tree_block_add_child(tree, tree_i);
1835 if (partial || !tree)
1836 break;
1839 if (!tree)
1840 return NULL;
1842 if (partial) {
1843 if (has_kills)
1844 tree = pet_tree_block_set_block(tree, 0);
1845 } else if (partial_range) {
1846 if (pet_tree_block_n_child(tree) == 0) {
1847 pet_tree_free(tree);
1848 return NULL;
1850 partial = true;
1851 } else if (skip > 0)
1852 tree = insert_initial_declarations(tree, skip, stmt_range);
1854 return tree;
1857 /* Is "T" the type of a variable length array with static size?
1859 static bool is_vla_with_static_size(QualType T)
1861 const VariableArrayType *vlatype;
1863 if (!T->isVariableArrayType())
1864 return false;
1865 vlatype = cast<VariableArrayType>(T);
1866 return vlatype->getSizeModifier() == VariableArrayType::Static;
1869 /* Return the type of "decl" as an array.
1871 * In particular, if "decl" is a parameter declaration that
1872 * is a variable length array with a static size, then
1873 * return the original type (i.e., the variable length array).
1874 * Otherwise, return the type of decl.
1876 static QualType get_array_type(ValueDecl *decl)
1878 ParmVarDecl *parm;
1879 QualType T;
1881 parm = dyn_cast<ParmVarDecl>(decl);
1882 if (!parm)
1883 return decl->getType();
1885 T = parm->getOriginalType();
1886 if (!is_vla_with_static_size(T))
1887 return decl->getType();
1888 return T;
1891 extern "C" {
1892 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1893 void *user);
1894 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1895 __isl_keep pet_context *pc, void *user);
1898 /* Construct a pet_expr that holds the sizes of the array accessed
1899 * by "access".
1900 * This function is used as a callback to pet_context_add_parameters,
1901 * which is also passed a pointer to the PetScan object.
1903 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1904 void *user)
1906 PetScan *ps = (PetScan *) user;
1907 isl_id *id;
1908 ValueDecl *decl;
1909 const Type *type;
1911 id = pet_expr_access_get_id(access);
1912 decl = (ValueDecl *) isl_id_get_user(id);
1913 isl_id_free(id);
1914 type = get_array_type(decl).getTypePtr();
1915 return ps->get_array_size(type);
1918 /* Construct and return a pet_array corresponding to the variable
1919 * accessed by "access".
1920 * This function is used as a callback to pet_scop_from_pet_tree,
1921 * which is also passed a pointer to the PetScan object.
1923 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1924 __isl_keep pet_context *pc, void *user)
1926 PetScan *ps = (PetScan *) user;
1927 isl_ctx *ctx;
1928 isl_id *id;
1929 ValueDecl *iv;
1931 ctx = pet_expr_get_ctx(access);
1932 id = pet_expr_access_get_id(access);
1933 iv = (ValueDecl *) isl_id_get_user(id);
1934 isl_id_free(id);
1935 return ps->extract_array(ctx, iv, NULL, pc);
1938 /* Extract a function summary from the body of "fd".
1940 * We extract a scop from the function body in a context with as
1941 * parameters the integer arguments of the function.
1942 * We turn off autodetection (in case it was set) to ensure that
1943 * the entire function body is considered.
1944 * We then collect the accessed array elements and attach them
1945 * to the corresponding array arguments, taking into account
1946 * that the function body may access members of array elements.
1948 * The reason for representing the integer arguments as parameters in
1949 * the context is that if we were to instead start with a context
1950 * with the function arguments as initial dimensions, then we would not
1951 * be able to refer to them from the array extents, without turning
1952 * array extents into maps.
1954 * The result is stored in the summary_cache cache so that we can reuse
1955 * it if this method gets called on the same function again later on.
1957 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
1959 isl_space *space;
1960 isl_set *domain;
1961 pet_context *pc;
1962 pet_tree *tree;
1963 pet_function_summary *summary;
1964 unsigned n;
1965 ScopLoc loc;
1966 int save_autodetect;
1967 struct pet_scop *scop;
1968 int int_size;
1969 isl_union_set *may_read, *may_write, *must_write;
1970 isl_union_map *to_inner;
1972 if (summary_cache.find(fd) != summary_cache.end())
1973 return pet_function_summary_copy(summary_cache[fd]);
1975 space = isl_space_set_alloc(ctx, 0, 0);
1977 n = fd->getNumParams();
1978 summary = pet_function_summary_alloc(ctx, n);
1979 for (int i = 0; i < n; ++i) {
1980 ParmVarDecl *parm = fd->getParamDecl(i);
1981 QualType type = parm->getType();
1982 isl_id *id;
1984 if (!type->isIntegerType())
1985 continue;
1986 id = create_decl_id(ctx, parm);
1987 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
1988 space = isl_space_set_dim_id(space, isl_dim_param, 0,
1989 isl_id_copy(id));
1990 summary = pet_function_summary_set_int(summary, i, id);
1993 save_autodetect = options->autodetect;
1994 options->autodetect = 0;
1995 PetScan body_scan(PP, ast_context, loc, options,
1996 isl_union_map_copy(value_bounds), independent);
1998 tree = body_scan.extract(fd->getBody(), false);
2000 domain = isl_set_universe(space);
2001 pc = pet_context_alloc(domain);
2002 pc = pet_context_add_parameters(pc, tree,
2003 &::get_array_size, &body_scan);
2004 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2005 scop = pet_scop_from_pet_tree(tree, int_size,
2006 &::extract_array, &body_scan, pc);
2007 scop = scan_arrays(scop, pc);
2008 may_read = isl_union_map_range(pet_scop_collect_may_reads(scop));
2009 may_write = isl_union_map_range(pet_scop_collect_may_writes(scop));
2010 must_write = isl_union_map_range(pet_scop_collect_must_writes(scop));
2011 to_inner = pet_scop_compute_outer_to_inner(scop);
2012 pet_scop_free(scop);
2014 for (int i = 0; i < n; ++i) {
2015 ParmVarDecl *parm = fd->getParamDecl(i);
2016 QualType type = parm->getType();
2017 struct pet_array *array;
2018 isl_space *space;
2019 isl_union_set *data_set;
2020 isl_union_set *may_read_i, *may_write_i, *must_write_i;
2022 if (array_depth(type.getTypePtr()) == 0)
2023 continue;
2025 array = body_scan.extract_array(ctx, parm, NULL, pc);
2026 space = array ? isl_set_get_space(array->extent) : NULL;
2027 pet_array_free(array);
2028 data_set = isl_union_set_from_set(isl_set_universe(space));
2029 data_set = isl_union_set_apply(data_set,
2030 isl_union_map_copy(to_inner));
2031 may_read_i = isl_union_set_intersect(
2032 isl_union_set_copy(may_read),
2033 isl_union_set_copy(data_set));
2034 may_write_i = isl_union_set_intersect(
2035 isl_union_set_copy(may_write),
2036 isl_union_set_copy(data_set));
2037 must_write_i = isl_union_set_intersect(
2038 isl_union_set_copy(must_write), data_set);
2039 summary = pet_function_summary_set_array(summary, i,
2040 may_read_i, may_write_i, must_write_i);
2043 isl_union_set_free(may_read);
2044 isl_union_set_free(may_write);
2045 isl_union_set_free(must_write);
2046 isl_union_map_free(to_inner);
2048 options->autodetect = save_autodetect;
2049 pet_context_free(pc);
2051 summary_cache[fd] = pet_function_summary_copy(summary);
2053 return summary;
2056 /* If "fd" has a function body, then extract a function summary from
2057 * this body and attach it to the call expression "expr".
2059 * Even if a function body is available, "fd" itself may point
2060 * to a declaration without function body. We therefore first
2061 * replace it by the declaration that comes with a body (if any).
2063 * It is not clear why hasBody takes a reference to a const FunctionDecl *.
2064 * It seems that it is possible to directly use the iterators to obtain
2065 * a non-const pointer.
2066 * Since we are not going to use the pointer to modify anything anyway,
2067 * it seems safe to drop the constness. The alternative would be to
2068 * modify a lot of other functions to include const qualifiers.
2070 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
2071 FunctionDecl *fd)
2073 pet_function_summary *summary;
2074 const FunctionDecl *def;
2076 if (!expr)
2077 return NULL;
2078 if (!fd->hasBody(def))
2079 return expr;
2081 fd = const_cast<FunctionDecl *>(def);
2083 summary = get_summary(fd);
2085 expr = pet_expr_call_set_summary(expr, summary);
2087 return expr;
2090 /* Extract a pet_scop from "tree".
2092 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
2093 * then add pet_arrays for all accessed arrays.
2094 * We populate the pet_context with assignments for all parameters used
2095 * inside "tree" or any of the size expressions for the arrays accessed
2096 * by "tree" so that they can be used in affine expressions.
2098 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
2100 int int_size;
2101 isl_set *domain;
2102 pet_context *pc;
2103 pet_scop *scop;
2105 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2107 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2108 pc = pet_context_alloc(domain);
2109 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
2110 scop = pet_scop_from_pet_tree(tree, int_size,
2111 &::extract_array, this, pc);
2112 scop = scan_arrays(scop, pc);
2113 pet_context_free(pc);
2115 return scop;
2118 /* Check if the scop marked by the user is exactly this Stmt
2119 * or part of this Stmt.
2120 * If so, return a pet_scop corresponding to the marked region.
2121 * Otherwise, return NULL.
2123 struct pet_scop *PetScan::scan(Stmt *stmt)
2125 SourceManager &SM = PP.getSourceManager();
2126 unsigned start_off, end_off;
2128 start_off = getExpansionOffset(SM, stmt->getLocStart());
2129 end_off = getExpansionOffset(SM, stmt->getLocEnd());
2131 if (start_off > loc.end)
2132 return NULL;
2133 if (end_off < loc.start)
2134 return NULL;
2136 if (start_off >= loc.start && end_off <= loc.end)
2137 return extract_scop(extract(stmt));
2139 StmtIterator start;
2140 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
2141 Stmt *child = *start;
2142 if (!child)
2143 continue;
2144 start_off = getExpansionOffset(SM, child->getLocStart());
2145 end_off = getExpansionOffset(SM, child->getLocEnd());
2146 if (start_off < loc.start && end_off >= loc.end)
2147 return scan(child);
2148 if (start_off >= loc.start)
2149 break;
2152 StmtIterator end;
2153 for (end = start; end != stmt->child_end(); ++end) {
2154 Stmt *child = *end;
2155 start_off = SM.getFileOffset(child->getLocStart());
2156 if (start_off >= loc.end)
2157 break;
2160 return extract_scop(extract(StmtRange(start, end), false, false));
2163 /* Set the size of index "pos" of "array" to "size".
2164 * In particular, add a constraint of the form
2166 * i_pos < size
2168 * to array->extent and a constraint of the form
2170 * size >= 0
2172 * to array->context.
2174 * The domain of "size" is assumed to be zero-dimensional.
2176 static struct pet_array *update_size(struct pet_array *array, int pos,
2177 __isl_take isl_pw_aff *size)
2179 isl_set *valid;
2180 isl_set *univ;
2181 isl_set *bound;
2182 isl_space *dim;
2183 isl_aff *aff;
2184 isl_pw_aff *index;
2185 isl_id *id;
2187 if (!array)
2188 goto error;
2190 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2191 array->context = isl_set_intersect(array->context, valid);
2193 dim = isl_set_get_space(array->extent);
2194 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2195 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2196 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2197 index = isl_pw_aff_alloc(univ, aff);
2199 size = isl_pw_aff_add_dims(size, isl_dim_in,
2200 isl_set_dim(array->extent, isl_dim_set));
2201 id = isl_set_get_tuple_id(array->extent);
2202 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2203 bound = isl_pw_aff_lt_set(index, size);
2205 array->extent = isl_set_intersect(array->extent, bound);
2207 if (!array->context || !array->extent)
2208 return pet_array_free(array);
2210 return array;
2211 error:
2212 isl_pw_aff_free(size);
2213 return NULL;
2216 #ifdef HAVE_DECAYEDTYPE
2218 /* If "type" is a decayed type, then set *decayed to true and
2219 * return the original type.
2221 static const Type *undecay(const Type *type, bool *decayed)
2223 *decayed = isa<DecayedType>(type);
2224 if (*decayed)
2225 type = cast<DecayedType>(type)->getOriginalType().getTypePtr();
2226 return type;
2229 #else
2231 /* If "type" is a decayed type, then set *decayed to true and
2232 * return the original type.
2233 * Since this version of clang does not define a DecayedType,
2234 * we cannot obtain the original type even if it had been decayed and
2235 * we set *decayed to false.
2237 static const Type *undecay(const Type *type, bool *decayed)
2239 *decayed = false;
2240 return type;
2243 #endif
2245 /* Figure out the size of the array at position "pos" and all
2246 * subsequent positions from "type" and update the corresponding
2247 * argument of "expr" accordingly.
2249 * The initial type (when pos is zero) may be a pointer type decayed
2250 * from an array type, if this initial type is the type of a function
2251 * argument. This only happens if the original array type has
2252 * a constant size in the outer dimension as otherwise we get
2253 * a VariableArrayType. Try and obtain this original type (if available) and
2254 * take the outer array size into account if it was marked static.
2256 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2257 const Type *type, int pos)
2259 const ArrayType *atype;
2260 pet_expr *size;
2261 bool decayed = false;
2263 if (!expr)
2264 return NULL;
2266 if (pos == 0)
2267 type = undecay(type, &decayed);
2269 if (type->isPointerType()) {
2270 type = type->getPointeeType().getTypePtr();
2271 return set_upper_bounds(expr, type, pos + 1);
2273 if (!type->isArrayType())
2274 return expr;
2276 type = type->getCanonicalTypeInternal().getTypePtr();
2277 atype = cast<ArrayType>(type);
2279 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2280 type = atype->getElementType().getTypePtr();
2281 return set_upper_bounds(expr, type, pos + 1);
2284 if (type->isConstantArrayType()) {
2285 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2286 size = extract_expr(ca->getSize());
2287 expr = pet_expr_set_arg(expr, pos, size);
2288 } else if (type->isVariableArrayType()) {
2289 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2290 size = extract_expr(vla->getSizeExpr());
2291 expr = pet_expr_set_arg(expr, pos, size);
2294 type = atype->getElementType().getTypePtr();
2296 return set_upper_bounds(expr, type, pos + 1);
2299 /* Construct a pet_expr that holds the sizes of an array of the given type.
2300 * The returned expression is a call expression with as arguments
2301 * the sizes in each dimension. If we are unable to derive the size
2302 * in a given dimension, then the corresponding argument is set to infinity.
2303 * In fact, we initialize all arguments to infinity and then update
2304 * them if we are able to figure out the size.
2306 * The result is stored in the type_size cache so that we can reuse
2307 * it if this method gets called on the same type again later on.
2309 __isl_give pet_expr *PetScan::get_array_size(const Type *type)
2311 int depth;
2312 pet_expr *expr, *inf;
2314 if (type_size.find(type) != type_size.end())
2315 return pet_expr_copy(type_size[type]);
2317 depth = array_depth(type);
2318 inf = pet_expr_new_int(isl_val_infty(ctx));
2319 expr = pet_expr_new_call(ctx, "bounds", depth);
2320 for (int i = 0; i < depth; ++i)
2321 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2322 pet_expr_free(inf);
2324 expr = set_upper_bounds(expr, type, 0);
2325 type_size[type] = pet_expr_copy(expr);
2327 return expr;
2330 /* Does "expr" represent the "integer" infinity?
2332 static int is_infty(__isl_keep pet_expr *expr)
2334 isl_val *v;
2335 int res;
2337 if (pet_expr_get_type(expr) != pet_expr_int)
2338 return 0;
2339 v = pet_expr_int_get_val(expr);
2340 res = isl_val_is_infty(v);
2341 isl_val_free(v);
2343 return res;
2346 /* Figure out the dimensions of an array "array" based on its type
2347 * "type" and update "array" accordingly.
2349 * We first construct a pet_expr that holds the sizes of the array
2350 * in each dimension. The resulting expression may containing
2351 * infinity values for dimension where we are unable to derive
2352 * a size expression.
2354 * The arguments of the size expression that have a value different from
2355 * infinity are then converted to an affine expression
2356 * within the context "pc" and incorporated into the size of "array".
2357 * If we are unable to convert a size expression to an affine expression or
2358 * if the size is not a (symbolic) constant,
2359 * then we leave the corresponding size of "array" untouched.
2361 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2362 const Type *type, __isl_keep pet_context *pc)
2364 int n;
2365 pet_expr *expr;
2367 if (!array)
2368 return NULL;
2370 expr = get_array_size(type);
2372 n = pet_expr_get_n_arg(expr);
2373 for (int i = 0; i < n; ++i) {
2374 pet_expr *arg;
2375 isl_pw_aff *size;
2377 arg = pet_expr_get_arg(expr, i);
2378 if (!is_infty(arg)) {
2379 int dim;
2381 size = pet_expr_extract_affine(arg, pc);
2382 dim = isl_pw_aff_dim(size, isl_dim_in);
2383 if (!size)
2384 array = pet_array_free(array);
2385 else if (isl_pw_aff_involves_nan(size) ||
2386 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2387 isl_pw_aff_free(size);
2388 else {
2389 size = isl_pw_aff_drop_dims(size,
2390 isl_dim_in, 0, dim);
2391 array = update_size(array, i, size);
2394 pet_expr_free(arg);
2396 pet_expr_free(expr);
2398 return array;
2401 /* Does "decl" have a definition that we can keep track of in a pet_type?
2403 static bool has_printable_definition(RecordDecl *decl)
2405 if (!decl->getDeclName())
2406 return false;
2407 return decl->getLexicalDeclContext() == decl->getDeclContext();
2410 /* Construct and return a pet_array corresponding to the variable "decl".
2411 * In particular, initialize array->extent to
2413 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2415 * and then call set_upper_bounds to set the upper bounds on the indices
2416 * based on the type of the variable. The upper bounds are converted
2417 * to affine expressions within the context "pc".
2419 * If the base type is that of a record with a top-level definition or
2420 * of a typedef and if "types" is not null, then the RecordDecl or
2421 * TypedefType corresponding to the type
2422 * is added to "types".
2424 * If the base type is that of a record with no top-level definition,
2425 * then we replace it by "<subfield>".
2427 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
2428 PetTypes *types, __isl_keep pet_context *pc)
2430 struct pet_array *array;
2431 QualType qt = get_array_type(decl);
2432 const Type *type = qt.getTypePtr();
2433 int depth = array_depth(type);
2434 QualType base = pet_clang_base_type(qt);
2435 string name;
2436 isl_id *id;
2437 isl_space *space;
2439 array = isl_calloc_type(ctx, struct pet_array);
2440 if (!array)
2441 return NULL;
2443 id = create_decl_id(ctx, decl);
2444 space = isl_space_set_alloc(ctx, 0, depth);
2445 space = isl_space_set_tuple_id(space, isl_dim_set, id);
2447 array->extent = isl_set_nat_universe(space);
2449 space = isl_space_params_alloc(ctx, 0);
2450 array->context = isl_set_universe(space);
2452 array = set_upper_bounds(array, type, pc);
2453 if (!array)
2454 return NULL;
2456 name = base.getAsString();
2458 if (types) {
2459 if (isa<TypedefType>(base)) {
2460 types->insert(cast<TypedefType>(base)->getDecl());
2461 } else if (base->isRecordType()) {
2462 RecordDecl *decl = pet_clang_record_decl(base);
2463 TypedefNameDecl *typedecl;
2464 typedecl = decl->getTypedefNameForAnonDecl();
2465 if (typedecl)
2466 types->insert(typedecl);
2467 else if (has_printable_definition(decl))
2468 types->insert(decl);
2469 else
2470 name = "<subfield>";
2474 array->element_type = strdup(name.c_str());
2475 array->element_is_record = base->isRecordType();
2476 array->element_size = size_in_bytes(decl->getASTContext(), base);
2478 return array;
2481 /* Construct and return a pet_array corresponding to the sequence
2482 * of declarations "decls".
2483 * The upper bounds of the array are converted to affine expressions
2484 * within the context "pc".
2485 * If the sequence contains a single declaration, then it corresponds
2486 * to a simple array access. Otherwise, it corresponds to a member access,
2487 * with the declaration for the substructure following that of the containing
2488 * structure in the sequence of declarations.
2489 * We start with the outermost substructure and then combine it with
2490 * information from the inner structures.
2492 * Additionally, keep track of all required types in "types".
2494 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
2495 vector<ValueDecl *> decls, PetTypes *types, __isl_keep pet_context *pc)
2497 struct pet_array *array;
2498 vector<ValueDecl *>::iterator it;
2500 it = decls.begin();
2502 array = extract_array(ctx, *it, types, pc);
2504 for (++it; it != decls.end(); ++it) {
2505 struct pet_array *parent;
2506 const char *base_name, *field_name;
2507 char *product_name;
2509 parent = array;
2510 array = extract_array(ctx, *it, types, pc);
2511 if (!array)
2512 return pet_array_free(parent);
2514 base_name = isl_set_get_tuple_name(parent->extent);
2515 field_name = isl_set_get_tuple_name(array->extent);
2516 product_name = pet_array_member_access_name(ctx,
2517 base_name, field_name);
2519 array->extent = isl_set_product(isl_set_copy(parent->extent),
2520 array->extent);
2521 if (product_name)
2522 array->extent = isl_set_set_tuple_name(array->extent,
2523 product_name);
2524 array->context = isl_set_intersect(array->context,
2525 isl_set_copy(parent->context));
2527 pet_array_free(parent);
2528 free(product_name);
2530 if (!array->extent || !array->context || !product_name)
2531 return pet_array_free(array);
2534 return array;
2537 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2538 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2539 std::set<TypeDecl *> &types_done);
2540 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2541 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2542 std::set<TypeDecl *> &types_done);
2544 /* For each of the fields of "decl" that is itself a record type
2545 * or a typedef, add a corresponding pet_type to "scop".
2547 static struct pet_scop *add_field_types(isl_ctx *ctx, struct pet_scop *scop,
2548 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2549 std::set<TypeDecl *> &types_done)
2551 RecordDecl::field_iterator it;
2553 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
2554 QualType type = it->getType();
2556 if (isa<TypedefType>(type)) {
2557 TypedefNameDecl *typedefdecl;
2559 typedefdecl = cast<TypedefType>(type)->getDecl();
2560 scop = add_type(ctx, scop, typedefdecl,
2561 PP, types, types_done);
2562 } else if (type->isRecordType()) {
2563 RecordDecl *record;
2565 record = pet_clang_record_decl(type);
2566 scop = add_type(ctx, scop, record,
2567 PP, types, types_done);
2571 return scop;
2574 /* Add a pet_type corresponding to "decl" to "scop", provided
2575 * it is a member of types.records and it has not been added before
2576 * (i.e., it is not a member of "types_done").
2578 * Since we want the user to be able to print the types
2579 * in the order in which they appear in the scop, we need to
2580 * make sure that types of fields in a structure appear before
2581 * that structure. We therefore call ourselves recursively
2582 * through add_field_types on the types of all record subfields.
2584 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2585 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2586 std::set<TypeDecl *> &types_done)
2588 string s;
2589 llvm::raw_string_ostream S(s);
2591 if (types.records.find(decl) == types.records.end())
2592 return scop;
2593 if (types_done.find(decl) != types_done.end())
2594 return scop;
2596 add_field_types(ctx, scop, decl, PP, types, types_done);
2598 if (strlen(decl->getName().str().c_str()) == 0)
2599 return scop;
2601 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2602 S.str();
2604 scop->types[scop->n_type] = pet_type_alloc(ctx,
2605 decl->getName().str().c_str(), s.c_str());
2606 if (!scop->types[scop->n_type])
2607 return pet_scop_free(scop);
2609 types_done.insert(decl);
2611 scop->n_type++;
2613 return scop;
2616 /* Add a pet_type corresponding to "decl" to "scop", provided
2617 * it is a member of types.typedefs and it has not been added before
2618 * (i.e., it is not a member of "types_done").
2620 * If the underlying type is a structure, then we print the typedef
2621 * ourselves since clang does not print the definition of the structure
2622 * in the typedef. We also make sure in this case that the types of
2623 * the fields in the structure are added first.
2625 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2626 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2627 std::set<TypeDecl *> &types_done)
2629 string s;
2630 llvm::raw_string_ostream S(s);
2631 QualType qt = decl->getUnderlyingType();
2633 if (types.typedefs.find(decl) == types.typedefs.end())
2634 return scop;
2635 if (types_done.find(decl) != types_done.end())
2636 return scop;
2638 if (qt->isRecordType()) {
2639 RecordDecl *rec = pet_clang_record_decl(qt);
2641 add_field_types(ctx, scop, rec, PP, types, types_done);
2642 S << "typedef ";
2643 rec->print(S, PrintingPolicy(PP.getLangOpts()));
2644 S << " ";
2645 S << decl->getName();
2646 } else {
2647 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2649 S.str();
2651 scop->types[scop->n_type] = pet_type_alloc(ctx,
2652 decl->getName().str().c_str(), s.c_str());
2653 if (!scop->types[scop->n_type])
2654 return pet_scop_free(scop);
2656 types_done.insert(decl);
2658 scop->n_type++;
2660 return scop;
2663 /* Construct a list of pet_arrays, one for each array (or scalar)
2664 * accessed inside "scop", add this list to "scop" and return the result.
2665 * The upper bounds of the arrays are converted to affine expressions
2666 * within the context "pc".
2668 * The context of "scop" is updated with the intersection of
2669 * the contexts of all arrays, i.e., constraints on the parameters
2670 * that ensure that the arrays have a valid (non-negative) size.
2672 * If any of the extracted arrays refers to a member access or
2673 * has a typedef'd type as base type,
2674 * then also add the required types to "scop".
2676 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
2677 __isl_keep pet_context *pc)
2679 int i, n;
2680 array_desc_set arrays;
2681 array_desc_set::iterator it;
2682 PetTypes types;
2683 std::set<TypeDecl *> types_done;
2684 std::set<clang::RecordDecl *, less_name>::iterator records_it;
2685 std::set<clang::TypedefNameDecl *, less_name>::iterator typedefs_it;
2686 int n_array;
2687 struct pet_array **scop_arrays;
2689 if (!scop)
2690 return NULL;
2692 pet_scop_collect_arrays(scop, arrays);
2693 if (arrays.size() == 0)
2694 return scop;
2696 n_array = scop->n_array;
2698 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2699 n_array + arrays.size());
2700 if (!scop_arrays)
2701 goto error;
2702 scop->arrays = scop_arrays;
2704 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
2705 struct pet_array *array;
2706 array = extract_array(ctx, *it, &types, pc);
2707 scop->arrays[n_array + i] = array;
2708 if (!scop->arrays[n_array + i])
2709 goto error;
2710 scop->n_array++;
2711 scop->context = isl_set_intersect(scop->context,
2712 isl_set_copy(array->context));
2713 if (!scop->context)
2714 goto error;
2717 n = types.records.size() + types.typedefs.size();
2718 if (n == 0)
2719 return scop;
2721 scop->types = isl_alloc_array(ctx, struct pet_type *, n);
2722 if (!scop->types)
2723 goto error;
2725 for (records_it = types.records.begin();
2726 records_it != types.records.end(); ++records_it)
2727 scop = add_type(ctx, scop, *records_it, PP, types, types_done);
2729 for (typedefs_it = types.typedefs.begin();
2730 typedefs_it != types.typedefs.end(); ++typedefs_it)
2731 scop = add_type(ctx, scop, *typedefs_it, PP, types, types_done);
2733 return scop;
2734 error:
2735 pet_scop_free(scop);
2736 return NULL;
2739 /* Bound all parameters in scop->context to the possible values
2740 * of the corresponding C variable.
2742 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
2744 int n;
2746 if (!scop)
2747 return NULL;
2749 n = isl_set_dim(scop->context, isl_dim_param);
2750 for (int i = 0; i < n; ++i) {
2751 isl_id *id;
2752 ValueDecl *decl;
2754 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
2755 if (pet_nested_in_id(id)) {
2756 isl_id_free(id);
2757 isl_die(isl_set_get_ctx(scop->context),
2758 isl_error_internal,
2759 "unresolved nested parameter", goto error);
2761 decl = (ValueDecl *) isl_id_get_user(id);
2762 isl_id_free(id);
2764 scop->context = set_parameter_bounds(scop->context, i, decl);
2766 if (!scop->context)
2767 goto error;
2770 return scop;
2771 error:
2772 pet_scop_free(scop);
2773 return NULL;
2776 /* Construct a pet_scop from the given function.
2778 * If the scop was delimited by scop and endscop pragmas, then we override
2779 * the file offsets by those derived from the pragmas.
2781 struct pet_scop *PetScan::scan(FunctionDecl *fd)
2783 pet_scop *scop;
2784 Stmt *stmt;
2786 stmt = fd->getBody();
2788 if (options->autodetect) {
2789 set_current_stmt(stmt);
2790 scop = extract_scop(extract(stmt, true));
2791 } else {
2792 current_line = loc.start_line;
2793 scop = scan(stmt);
2794 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
2796 scop = add_parameter_bounds(scop);
2797 scop = pet_scop_gist(scop, value_bounds);
2799 return scop;
2802 /* Update this->last_line and this->current_line based on the fact
2803 * that we are about to consider "stmt".
2805 void PetScan::set_current_stmt(Stmt *stmt)
2807 SourceLocation loc = stmt->getLocStart();
2808 SourceManager &SM = PP.getSourceManager();
2810 last_line = current_line;
2811 current_line = SM.getExpansionLineNumber(loc);
2814 /* Is the current statement marked by an independent pragma?
2815 * That is, is there an independent pragma on a line between
2816 * the line of the current statement and the line of the previous statement.
2817 * The search is not implemented very efficiently. We currently
2818 * assume that there are only a few independent pragmas, if any.
2820 bool PetScan::is_current_stmt_marked_independent()
2822 for (int i = 0; i < independent.size(); ++i) {
2823 unsigned line = independent[i].line;
2825 if (last_line < line && line < current_line)
2826 return true;
2829 return false;