PetScan: allow label on any statement
[pet.git] / scan.cc
blobbf08128c40671f7435c45d73bb540f17eddb2f1c
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2014 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 <string.h>
36 #include <set>
37 #include <map>
38 #include <iostream>
39 #include <llvm/Support/raw_ostream.h>
40 #include <clang/AST/ASTContext.h>
41 #include <clang/AST/ASTDiagnostic.h>
42 #include <clang/AST/Attr.h>
43 #include <clang/AST/Expr.h>
44 #include <clang/AST/RecursiveASTVisitor.h>
46 #include <isl/id.h>
47 #include <isl/space.h>
48 #include <isl/aff.h>
49 #include <isl/set.h>
51 #include "aff.h"
52 #include "array.h"
53 #include "clang.h"
54 #include "context.h"
55 #include "expr.h"
56 #include "nest.h"
57 #include "options.h"
58 #include "scan.h"
59 #include "scop.h"
60 #include "scop_plus.h"
61 #include "tree.h"
62 #include "tree2scop.h"
64 #include "config.h"
66 using namespace std;
67 using namespace clang;
69 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
71 switch (kind) {
72 case UO_Minus:
73 return pet_op_minus;
74 case UO_Not:
75 return pet_op_not;
76 case UO_LNot:
77 return pet_op_lnot;
78 case UO_PostInc:
79 return pet_op_post_inc;
80 case UO_PostDec:
81 return pet_op_post_dec;
82 case UO_PreInc:
83 return pet_op_pre_inc;
84 case UO_PreDec:
85 return pet_op_pre_dec;
86 default:
87 return pet_op_last;
91 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
93 switch (kind) {
94 case BO_AddAssign:
95 return pet_op_add_assign;
96 case BO_SubAssign:
97 return pet_op_sub_assign;
98 case BO_MulAssign:
99 return pet_op_mul_assign;
100 case BO_DivAssign:
101 return pet_op_div_assign;
102 case BO_Assign:
103 return pet_op_assign;
104 case BO_Add:
105 return pet_op_add;
106 case BO_Sub:
107 return pet_op_sub;
108 case BO_Mul:
109 return pet_op_mul;
110 case BO_Div:
111 return pet_op_div;
112 case BO_Rem:
113 return pet_op_mod;
114 case BO_Shl:
115 return pet_op_shl;
116 case BO_Shr:
117 return pet_op_shr;
118 case BO_EQ:
119 return pet_op_eq;
120 case BO_NE:
121 return pet_op_ne;
122 case BO_LE:
123 return pet_op_le;
124 case BO_GE:
125 return pet_op_ge;
126 case BO_LT:
127 return pet_op_lt;
128 case BO_GT:
129 return pet_op_gt;
130 case BO_And:
131 return pet_op_and;
132 case BO_Xor:
133 return pet_op_xor;
134 case BO_Or:
135 return pet_op_or;
136 case BO_LAnd:
137 return pet_op_land;
138 case BO_LOr:
139 return pet_op_lor;
140 default:
141 return pet_op_last;
145 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
146 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
148 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
149 SourceLocation(), var, false, var->getInnerLocStart(),
150 var->getType(), VK_LValue);
152 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
153 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
155 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
156 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
157 VK_LValue);
159 #else
160 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
162 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
163 var, var->getInnerLocStart(), var->getType(), VK_LValue);
165 #endif
167 /* Check if the element type corresponding to the given array type
168 * has a const qualifier.
170 static bool const_base(QualType qt)
172 const Type *type = qt.getTypePtr();
174 if (type->isPointerType())
175 return const_base(type->getPointeeType());
176 if (type->isArrayType()) {
177 const ArrayType *atype;
178 type = type->getCanonicalTypeInternal().getTypePtr();
179 atype = cast<ArrayType>(type);
180 return const_base(atype->getElementType());
183 return qt.isConstQualified();
186 /* Create an isl_id that refers to the named declarator "decl".
188 static __isl_give isl_id *create_decl_id(isl_ctx *ctx, NamedDecl *decl)
190 return isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
193 PetScan::~PetScan()
195 std::map<const Type *, pet_expr *>::iterator it;
196 std::map<FunctionDecl *, pet_function_summary *>::iterator it_s;
198 for (it = type_size.begin(); it != type_size.end(); ++it)
199 pet_expr_free(it->second);
200 for (it_s = summary_cache.begin(); it_s != summary_cache.end(); ++it_s)
201 pet_function_summary_free(it_s->second);
203 isl_union_map_free(value_bounds);
206 /* Report a diagnostic, unless autodetect is set.
208 void PetScan::report(Stmt *stmt, unsigned id)
210 if (options->autodetect)
211 return;
213 SourceLocation loc = stmt->getLocStart();
214 DiagnosticsEngine &diag = PP.getDiagnostics();
215 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
218 /* Called if we found something we (currently) cannot handle.
219 * We'll provide more informative warnings later.
221 * We only actually complain if autodetect is false.
223 void PetScan::unsupported(Stmt *stmt)
225 DiagnosticsEngine &diag = PP.getDiagnostics();
226 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
227 "unsupported");
228 report(stmt, id);
231 /* Report a missing prototype, unless autodetect is set.
233 void PetScan::report_prototype_required(Stmt *stmt)
235 DiagnosticsEngine &diag = PP.getDiagnostics();
236 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
237 "prototype required");
238 report(stmt, id);
241 /* Report a missing increment, unless autodetect is set.
243 void PetScan::report_missing_increment(Stmt *stmt)
245 DiagnosticsEngine &diag = PP.getDiagnostics();
246 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
247 "missing increment");
248 report(stmt, id);
251 /* Report a missing summary function, unless autodetect is set.
253 void PetScan::report_missing_summary_function(Stmt *stmt)
255 DiagnosticsEngine &diag = PP.getDiagnostics();
256 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
257 "missing summary function");
258 report(stmt, id);
261 /* Report a missing summary function body, unless autodetect is set.
263 void PetScan::report_missing_summary_function_body(Stmt *stmt)
265 DiagnosticsEngine &diag = PP.getDiagnostics();
266 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
267 "missing summary function body");
268 report(stmt, id);
271 /* Extract an integer from "val", which is assumed to be non-negative.
273 static __isl_give isl_val *extract_unsigned(isl_ctx *ctx,
274 const llvm::APInt &val)
276 unsigned n;
277 const uint64_t *data;
279 data = val.getRawData();
280 n = val.getNumWords();
281 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
284 /* Extract an integer from "val". If "is_signed" is set, then "val"
285 * is signed. Otherwise it it unsigned.
287 static __isl_give isl_val *extract_int(isl_ctx *ctx, bool is_signed,
288 llvm::APInt val)
290 int is_negative = is_signed && val.isNegative();
291 isl_val *v;
293 if (is_negative)
294 val = -val;
296 v = extract_unsigned(ctx, val);
298 if (is_negative)
299 v = isl_val_neg(v);
300 return v;
303 /* Extract an integer from "expr".
305 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
307 const Type *type = expr->getType().getTypePtr();
308 bool is_signed = type->hasSignedIntegerRepresentation();
310 return ::extract_int(ctx, is_signed, expr->getValue());
313 /* Extract an integer from "expr".
314 * Return NULL if "expr" does not (obviously) represent an integer.
316 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
318 return extract_int(expr->getSubExpr());
321 /* Extract an integer from "expr".
322 * Return NULL if "expr" does not (obviously) represent an integer.
324 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
326 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
327 return extract_int(ctx, cast<IntegerLiteral>(expr));
328 if (expr->getStmtClass() == Stmt::ParenExprClass)
329 return extract_int(cast<ParenExpr>(expr));
331 unsupported(expr);
332 return NULL;
335 /* Extract a pet_expr from the APInt "val", which is assumed
336 * to be non-negative.
338 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
340 return pet_expr_new_int(extract_unsigned(ctx, val));
343 /* Return the number of bits needed to represent the type "qt",
344 * if it is an integer type. Otherwise return 0.
345 * If qt is signed then return the opposite of the number of bits.
347 static int get_type_size(QualType qt, ASTContext &ast_context)
349 int size;
351 if (!qt->isIntegerType())
352 return 0;
354 size = ast_context.getIntWidth(qt);
355 if (!qt->isUnsignedIntegerType())
356 size = -size;
358 return size;
361 /* Return the number of bits needed to represent the type of "decl",
362 * if it is an integer type. Otherwise return 0.
363 * If qt is signed then return the opposite of the number of bits.
365 static int get_type_size(ValueDecl *decl)
367 return get_type_size(decl->getType(), decl->getASTContext());
370 /* Bound parameter "pos" of "set" to the possible values of "decl".
372 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
373 unsigned pos, ValueDecl *decl)
375 int type_size;
376 isl_ctx *ctx;
377 isl_val *bound;
379 ctx = isl_set_get_ctx(set);
380 type_size = get_type_size(decl);
381 if (type_size == 0)
382 isl_die(ctx, isl_error_invalid, "not an integer type",
383 return isl_set_free(set));
384 if (type_size > 0) {
385 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
386 bound = isl_val_int_from_ui(ctx, type_size);
387 bound = isl_val_2exp(bound);
388 bound = isl_val_sub_ui(bound, 1);
389 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
390 } else {
391 bound = isl_val_int_from_ui(ctx, -type_size - 1);
392 bound = isl_val_2exp(bound);
393 bound = isl_val_sub_ui(bound, 1);
394 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
395 isl_val_copy(bound));
396 bound = isl_val_neg(bound);
397 bound = isl_val_sub_ui(bound, 1);
398 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
401 return set;
404 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
406 return extract_index_expr(expr->getSubExpr());
409 /* Return the depth of an array of the given type.
411 static int array_depth(const Type *type)
413 if (type->isPointerType())
414 return 1 + array_depth(type->getPointeeType().getTypePtr());
415 if (type->isArrayType()) {
416 const ArrayType *atype;
417 type = type->getCanonicalTypeInternal().getTypePtr();
418 atype = cast<ArrayType>(type);
419 return 1 + array_depth(atype->getElementType().getTypePtr());
421 return 0;
424 /* Return the depth of the array accessed by the index expression "index".
425 * If "index" is an affine expression, i.e., if it does not access
426 * any array, then return 1.
427 * If "index" represent a member access, i.e., if its range is a wrapped
428 * relation, then return the sum of the depth of the array of structures
429 * and that of the member inside the structure.
431 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
433 isl_id *id;
434 ValueDecl *decl;
436 if (!index)
437 return -1;
439 if (isl_multi_pw_aff_range_is_wrapping(index)) {
440 int domain_depth, range_depth;
441 isl_multi_pw_aff *domain, *range;
443 domain = isl_multi_pw_aff_copy(index);
444 domain = isl_multi_pw_aff_range_factor_domain(domain);
445 domain_depth = extract_depth(domain);
446 isl_multi_pw_aff_free(domain);
447 range = isl_multi_pw_aff_copy(index);
448 range = isl_multi_pw_aff_range_factor_range(range);
449 range_depth = extract_depth(range);
450 isl_multi_pw_aff_free(range);
452 return domain_depth + range_depth;
455 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
456 return 1;
458 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
459 if (!id)
460 return -1;
461 decl = (ValueDecl *) isl_id_get_user(id);
462 isl_id_free(id);
464 return array_depth(decl->getType().getTypePtr());
467 /* Return the depth of the array accessed by the access expression "expr".
469 static int extract_depth(__isl_keep pet_expr *expr)
471 isl_multi_pw_aff *index;
472 int depth;
474 index = pet_expr_access_get_index(expr);
475 depth = extract_depth(index);
476 isl_multi_pw_aff_free(index);
478 return depth;
481 /* Construct a pet_expr representing an index expression for an access
482 * to the variable referenced by "expr".
484 * If "expr" references an enum constant, then return an integer expression
485 * instead, representing the value of the enum constant.
487 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
489 return extract_index_expr(expr->getDecl());
492 /* Construct a pet_expr representing an index expression for an access
493 * to the variable "decl".
495 * If "decl" is an enum constant, then we return an integer expression
496 * instead, representing the value of the enum constant.
498 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
500 isl_id *id;
501 isl_space *space;
503 if (isa<EnumConstantDecl>(decl))
504 return extract_expr(cast<EnumConstantDecl>(decl));
506 id = create_decl_id(ctx, decl);
507 space = isl_space_alloc(ctx, 0, 0, 0);
508 space = isl_space_set_tuple_id(space, isl_dim_out, id);
510 return pet_expr_from_index(isl_multi_pw_aff_zero(space));
513 /* Construct a pet_expr representing the index expression "expr"
514 * Return NULL on error.
516 * If "expr" is a reference to an enum constant, then return
517 * an integer expression instead, representing the value of the enum constant.
519 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
521 switch (expr->getStmtClass()) {
522 case Stmt::ImplicitCastExprClass:
523 return extract_index_expr(cast<ImplicitCastExpr>(expr));
524 case Stmt::DeclRefExprClass:
525 return extract_index_expr(cast<DeclRefExpr>(expr));
526 case Stmt::ArraySubscriptExprClass:
527 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
528 case Stmt::IntegerLiteralClass:
529 return extract_expr(cast<IntegerLiteral>(expr));
530 case Stmt::MemberExprClass:
531 return extract_index_expr(cast<MemberExpr>(expr));
532 default:
533 unsupported(expr);
535 return NULL;
538 /* Extract an index expression from the given array subscript expression.
540 * We first extract an index expression from the base.
541 * This will result in an index expression with a range that corresponds
542 * to the earlier indices.
543 * We then extract the current index and let
544 * pet_expr_access_subscript combine the two.
546 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
548 Expr *base = expr->getBase();
549 Expr *idx = expr->getIdx();
550 pet_expr *index;
551 pet_expr *base_expr;
553 base_expr = extract_index_expr(base);
554 index = extract_expr(idx);
556 base_expr = pet_expr_access_subscript(base_expr, index);
558 return base_expr;
561 /* Extract an index expression from a member expression.
563 * If the base access (to the structure containing the member)
564 * is of the form
566 * A[..]
568 * and the member is called "f", then the member access is of
569 * the form
571 * A_f[A[..] -> f[]]
573 * If the member access is to an anonymous struct, then simply return
575 * A[..]
577 * If the member access in the source code is of the form
579 * A->f
581 * then it is treated as
583 * A[0].f
585 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
587 Expr *base = expr->getBase();
588 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
589 pet_expr *base_index;
590 isl_id *id;
592 base_index = extract_index_expr(base);
594 if (expr->isArrow()) {
595 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
596 base_index = pet_expr_access_subscript(base_index, index);
599 if (field->isAnonymousStructOrUnion())
600 return base_index;
602 id = create_decl_id(ctx, field);
604 return pet_expr_access_member(base_index, id);
607 /* Mark the given access pet_expr as a write.
609 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
611 access = pet_expr_access_set_write(access, 1);
612 access = pet_expr_access_set_read(access, 0);
614 return access;
617 /* Construct a pet_expr representing a unary operator expression.
619 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
621 int type_size;
622 pet_expr *arg;
623 enum pet_op_type op;
625 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
626 if (op == pet_op_last) {
627 unsupported(expr);
628 return NULL;
631 arg = extract_expr(expr->getSubExpr());
633 if (expr->isIncrementDecrementOp() &&
634 pet_expr_get_type(arg) == pet_expr_access) {
635 arg = mark_write(arg);
636 arg = pet_expr_access_set_read(arg, 1);
639 type_size = get_type_size(expr->getType(), ast_context);
640 return pet_expr_new_unary(type_size, op, arg);
643 /* Construct a pet_expr representing a binary operator expression.
645 * If the top level operator is an assignment and the LHS is an access,
646 * then we mark that access as a write. If the operator is a compound
647 * assignment, the access is marked as both a read and a write.
649 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
651 int type_size;
652 pet_expr *lhs, *rhs;
653 enum pet_op_type op;
655 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
656 if (op == pet_op_last) {
657 unsupported(expr);
658 return NULL;
661 lhs = extract_expr(expr->getLHS());
662 rhs = extract_expr(expr->getRHS());
664 if (expr->isAssignmentOp() &&
665 pet_expr_get_type(lhs) == pet_expr_access) {
666 lhs = mark_write(lhs);
667 if (expr->isCompoundAssignmentOp())
668 lhs = pet_expr_access_set_read(lhs, 1);
671 type_size = get_type_size(expr->getType(), ast_context);
672 return pet_expr_new_binary(type_size, op, lhs, rhs);
675 /* Construct a pet_tree for a (single) variable declaration.
677 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
679 Decl *decl;
680 VarDecl *vd;
681 pet_expr *lhs, *rhs;
682 pet_tree *tree;
684 if (!stmt->isSingleDecl()) {
685 unsupported(stmt);
686 return NULL;
689 decl = stmt->getSingleDecl();
690 vd = cast<VarDecl>(decl);
692 lhs = extract_access_expr(vd);
693 lhs = mark_write(lhs);
694 if (!vd->getInit())
695 tree = pet_tree_new_decl(lhs);
696 else {
697 rhs = extract_expr(vd->getInit());
698 tree = pet_tree_new_decl_init(lhs, rhs);
701 return tree;
704 /* Construct a pet_expr representing a conditional operation.
706 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
708 pet_expr *cond, *lhs, *rhs;
709 isl_pw_aff *pa;
711 cond = extract_expr(expr->getCond());
712 lhs = extract_expr(expr->getTrueExpr());
713 rhs = extract_expr(expr->getFalseExpr());
715 return pet_expr_new_ternary(cond, lhs, rhs);
718 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
720 return extract_expr(expr->getSubExpr());
723 /* Construct a pet_expr representing a floating point value.
725 * If the floating point literal does not appear in a macro,
726 * then we use the original representation in the source code
727 * as the string representation. Otherwise, we use the pretty
728 * printer to produce a string representation.
730 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
732 double d;
733 string s;
734 const LangOptions &LO = PP.getLangOpts();
735 SourceLocation loc = expr->getLocation();
737 if (!loc.isMacroID()) {
738 SourceManager &SM = PP.getSourceManager();
739 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
740 s = string(SM.getCharacterData(loc), len);
741 } else {
742 llvm::raw_string_ostream S(s);
743 expr->printPretty(S, 0, PrintingPolicy(LO));
744 S.str();
746 d = expr->getValueAsApproximateDouble();
747 return pet_expr_new_double(ctx, d, s.c_str());
750 /* Convert the index expression "index" into an access pet_expr of type "qt".
752 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
753 __isl_take pet_expr *index)
755 int depth;
756 int type_size;
758 depth = extract_depth(index);
759 type_size = get_type_size(qt, ast_context);
761 index = pet_expr_set_type_size(index, type_size);
762 index = pet_expr_access_set_depth(index, depth);
764 return index;
767 /* Extract an index expression from "expr" and then convert it into
768 * an access pet_expr.
770 * If "expr" is a reference to an enum constant, then return
771 * an integer expression instead, representing the value of the enum constant.
773 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
775 pet_expr *index;
777 index = extract_index_expr(expr);
779 if (pet_expr_get_type(index) == pet_expr_int)
780 return index;
782 return extract_access_expr(expr->getType(), index);
785 /* Extract an index expression from "decl" and then convert it into
786 * an access pet_expr.
788 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
790 return extract_access_expr(decl->getType(), extract_index_expr(decl));
793 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
795 return extract_expr(expr->getSubExpr());
798 /* Extract an assume statement from the argument "expr"
799 * of a __pencil_assume statement.
801 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
803 return pet_expr_new_unary(0, pet_op_assume, extract_expr(expr));
806 /* Construct a pet_expr corresponding to the function call argument "expr".
807 * The argument appears in position "pos" of a call to function "fd".
809 * If we are passing along a pointer to an array element
810 * or an entire row or even higher dimensional slice of an array,
811 * then the function being called may write into the array.
813 * We assume here that if the function is declared to take a pointer
814 * to a const type, then the function will perform a read
815 * and that otherwise, it will perform a write.
816 * We only perform this check if "detect_writes" is set.
818 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
819 Expr *expr, bool detect_writes)
821 pet_expr *res;
822 int is_addr = 0, is_partial = 0;
823 Stmt::StmtClass sc;
825 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
826 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
827 expr = ice->getSubExpr();
829 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
830 UnaryOperator *op = cast<UnaryOperator>(expr);
831 if (op->getOpcode() == UO_AddrOf) {
832 is_addr = 1;
833 expr = op->getSubExpr();
836 res = extract_expr(expr);
837 if (!res)
838 return NULL;
839 sc = expr->getStmtClass();
840 if ((sc == Stmt::ArraySubscriptExprClass ||
841 sc == Stmt::DeclRefExprClass ||
842 sc == Stmt::MemberExprClass) &&
843 array_depth(expr->getType().getTypePtr()) > 0)
844 is_partial = 1;
845 if (detect_writes && (is_addr || is_partial) &&
846 pet_expr_get_type(res) == pet_expr_access) {
847 ParmVarDecl *parm;
848 if (!fd->hasPrototype()) {
849 report_prototype_required(expr);
850 return pet_expr_free(res);
852 parm = fd->getParamDecl(pos);
853 if (!const_base(parm->getType()))
854 res = mark_write(res);
857 if (is_addr)
858 res = pet_expr_new_unary(0, pet_op_address_of, res);
859 return res;
862 /* Find the first FunctionDecl with the given name.
863 * "call" is the corresponding call expression and is only used
864 * for reporting errors.
866 * Return NULL on error.
868 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
870 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
871 DeclContext::decl_iterator begin = tu->decls_begin();
872 DeclContext::decl_iterator end = tu->decls_end();
873 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
874 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
875 if (!fd)
876 continue;
877 if (fd->getName().str().compare(name) != 0)
878 continue;
879 if (fd->hasBody())
880 return fd;
881 report_missing_summary_function_body(call);
882 return NULL;
884 report_missing_summary_function(call);
885 return NULL;
888 /* Return the FunctionDecl for the summary function associated to the
889 * function called by "call".
891 * In particular, search for an annotate attribute formatted as
892 * "pencil_access(name)", where "name" is the name of the summary function.
894 * If no summary function was specified, then return the FunctionDecl
895 * that is actually being called.
897 * Return NULL on error.
899 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
901 FunctionDecl *decl = call->getDirectCallee();
902 if (!decl)
903 return NULL;
905 specific_attr_iterator<AnnotateAttr> begin, end, i;
906 begin = decl->specific_attr_begin<AnnotateAttr>();
907 end = decl->specific_attr_end<AnnotateAttr>();
908 for (i = begin; i != end; ++i) {
909 string attr = (*i)->getAnnotation().str();
911 const char prefix[] = "pencil_access(";
912 size_t start = attr.find(prefix);
913 if (start == string::npos)
914 continue;
915 start += strlen(prefix);
916 string name = attr.substr(start, attr.find(')') - start);
918 return find_decl_from_name(call, name);
921 return decl;
924 /* Construct a pet_expr representing a function call.
926 * In the special case of a "call" to __pencil_assume,
927 * construct an assume expression instead.
929 * In the case of a "call" to __pencil_kill, the arguments
930 * are neither read nor written (only killed), so there
931 * is no need to check for writes to these arguments.
933 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
935 pet_expr *res = NULL;
936 FunctionDecl *fd;
937 string name;
938 unsigned n_arg;
939 bool is_kill;
941 fd = expr->getDirectCallee();
942 if (!fd) {
943 unsupported(expr);
944 return NULL;
947 name = fd->getDeclName().getAsString();
948 n_arg = expr->getNumArgs();
950 if (n_arg == 1 && name == "__pencil_assume")
951 return extract_assume(expr->getArg(0));
952 is_kill = name == "__pencil_kill";
954 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
955 if (!res)
956 return NULL;
958 for (int i = 0; i < n_arg; ++i) {
959 Expr *arg = expr->getArg(i);
960 res = pet_expr_set_arg(res, i,
961 PetScan::extract_argument(fd, i, arg, !is_kill));
964 fd = get_summary_function(expr);
965 if (!fd)
966 return pet_expr_free(res);
968 res = set_summary(res, fd);
970 return res;
973 /* Construct a pet_expr representing a (C style) cast.
975 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
977 pet_expr *arg;
978 QualType type;
980 arg = extract_expr(expr->getSubExpr());
981 if (!arg)
982 return NULL;
984 type = expr->getTypeAsWritten();
985 return pet_expr_new_cast(type.getAsString().c_str(), arg);
988 /* Construct a pet_expr representing an integer.
990 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
992 return pet_expr_new_int(extract_int(expr));
995 /* Construct a pet_expr representing the integer enum constant "ecd".
997 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
999 isl_val *v;
1000 const llvm::APSInt &init = ecd->getInitVal();
1001 v = ::extract_int(ctx, init.isSigned(), init);
1002 return pet_expr_new_int(v);
1005 /* Try and construct a pet_expr representing "expr".
1007 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1009 switch (expr->getStmtClass()) {
1010 case Stmt::UnaryOperatorClass:
1011 return extract_expr(cast<UnaryOperator>(expr));
1012 case Stmt::CompoundAssignOperatorClass:
1013 case Stmt::BinaryOperatorClass:
1014 return extract_expr(cast<BinaryOperator>(expr));
1015 case Stmt::ImplicitCastExprClass:
1016 return extract_expr(cast<ImplicitCastExpr>(expr));
1017 case Stmt::ArraySubscriptExprClass:
1018 case Stmt::DeclRefExprClass:
1019 case Stmt::MemberExprClass:
1020 return extract_access_expr(expr);
1021 case Stmt::IntegerLiteralClass:
1022 return extract_expr(cast<IntegerLiteral>(expr));
1023 case Stmt::FloatingLiteralClass:
1024 return extract_expr(cast<FloatingLiteral>(expr));
1025 case Stmt::ParenExprClass:
1026 return extract_expr(cast<ParenExpr>(expr));
1027 case Stmt::ConditionalOperatorClass:
1028 return extract_expr(cast<ConditionalOperator>(expr));
1029 case Stmt::CallExprClass:
1030 return extract_expr(cast<CallExpr>(expr));
1031 case Stmt::CStyleCastExprClass:
1032 return extract_expr(cast<CStyleCastExpr>(expr));
1033 default:
1034 unsupported(expr);
1036 return NULL;
1039 /* Check if the given initialization statement is an assignment.
1040 * If so, return that assignment. Otherwise return NULL.
1042 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1044 BinaryOperator *ass;
1046 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1047 return NULL;
1049 ass = cast<BinaryOperator>(init);
1050 if (ass->getOpcode() != BO_Assign)
1051 return NULL;
1053 return ass;
1056 /* Check if the given initialization statement is a declaration
1057 * of a single variable.
1058 * If so, return that declaration. Otherwise return NULL.
1060 Decl *PetScan::initialization_declaration(Stmt *init)
1062 DeclStmt *decl;
1064 if (init->getStmtClass() != Stmt::DeclStmtClass)
1065 return NULL;
1067 decl = cast<DeclStmt>(init);
1069 if (!decl->isSingleDecl())
1070 return NULL;
1072 return decl->getSingleDecl();
1075 /* Given the assignment operator in the initialization of a for loop,
1076 * extract the induction variable, i.e., the (integer)variable being
1077 * assigned.
1079 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1081 Expr *lhs;
1082 DeclRefExpr *ref;
1083 ValueDecl *decl;
1084 const Type *type;
1086 lhs = init->getLHS();
1087 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1088 unsupported(init);
1089 return NULL;
1092 ref = cast<DeclRefExpr>(lhs);
1093 decl = ref->getDecl();
1094 type = decl->getType().getTypePtr();
1096 if (!type->isIntegerType()) {
1097 unsupported(lhs);
1098 return NULL;
1101 return decl;
1104 /* Given the initialization statement of a for loop and the single
1105 * declaration in this initialization statement,
1106 * extract the induction variable, i.e., the (integer) variable being
1107 * declared.
1109 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1111 VarDecl *vd;
1113 vd = cast<VarDecl>(decl);
1115 const QualType type = vd->getType();
1116 if (!type->isIntegerType()) {
1117 unsupported(init);
1118 return NULL;
1121 if (!vd->getInit()) {
1122 unsupported(init);
1123 return NULL;
1126 return vd;
1129 /* Check that op is of the form iv++ or iv--.
1130 * Return a pet_expr representing "1" or "-1" accordingly.
1132 __isl_give pet_expr *PetScan::extract_unary_increment(
1133 clang::UnaryOperator *op, clang::ValueDecl *iv)
1135 Expr *sub;
1136 DeclRefExpr *ref;
1137 isl_val *v;
1139 if (!op->isIncrementDecrementOp()) {
1140 unsupported(op);
1141 return NULL;
1144 sub = op->getSubExpr();
1145 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1146 unsupported(op);
1147 return NULL;
1150 ref = cast<DeclRefExpr>(sub);
1151 if (ref->getDecl() != iv) {
1152 unsupported(op);
1153 return NULL;
1156 if (op->isIncrementOp())
1157 v = isl_val_one(ctx);
1158 else
1159 v = isl_val_negone(ctx);
1161 return pet_expr_new_int(v);
1164 /* Check if op is of the form
1166 * iv = expr
1168 * and return the increment "expr - iv" as a pet_expr.
1170 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1171 clang::ValueDecl *iv)
1173 int type_size;
1174 Expr *lhs;
1175 DeclRefExpr *ref;
1176 pet_expr *expr, *expr_iv;
1178 if (op->getOpcode() != BO_Assign) {
1179 unsupported(op);
1180 return NULL;
1183 lhs = op->getLHS();
1184 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1185 unsupported(op);
1186 return NULL;
1189 ref = cast<DeclRefExpr>(lhs);
1190 if (ref->getDecl() != iv) {
1191 unsupported(op);
1192 return NULL;
1195 expr = extract_expr(op->getRHS());
1196 expr_iv = extract_expr(lhs);
1198 type_size = get_type_size(iv->getType(), ast_context);
1199 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1202 /* Check that op is of the form iv += cst or iv -= cst
1203 * and return a pet_expr corresponding to cst or -cst accordingly.
1205 __isl_give pet_expr *PetScan::extract_compound_increment(
1206 CompoundAssignOperator *op, clang::ValueDecl *iv)
1208 Expr *lhs;
1209 DeclRefExpr *ref;
1210 bool neg = false;
1211 pet_expr *expr;
1212 BinaryOperatorKind opcode;
1214 opcode = op->getOpcode();
1215 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1216 unsupported(op);
1217 return NULL;
1219 if (opcode == BO_SubAssign)
1220 neg = true;
1222 lhs = op->getLHS();
1223 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1224 unsupported(op);
1225 return NULL;
1228 ref = cast<DeclRefExpr>(lhs);
1229 if (ref->getDecl() != iv) {
1230 unsupported(op);
1231 return NULL;
1234 expr = extract_expr(op->getRHS());
1235 if (neg) {
1236 int type_size;
1237 type_size = get_type_size(op->getType(), ast_context);
1238 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1241 return expr;
1244 /* Check that the increment of the given for loop increments
1245 * (or decrements) the induction variable "iv" and return
1246 * the increment as a pet_expr if successful.
1248 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1249 ValueDecl *iv)
1251 Stmt *inc = stmt->getInc();
1253 if (!inc) {
1254 report_missing_increment(stmt);
1255 return NULL;
1258 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1259 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1260 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1261 return extract_compound_increment(
1262 cast<CompoundAssignOperator>(inc), iv);
1263 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1264 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1266 unsupported(inc);
1267 return NULL;
1270 /* Construct a pet_tree for a while loop.
1272 * If we were only able to extract part of the body, then simply
1273 * return that part.
1275 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1277 pet_expr *pe_cond;
1278 pet_tree *tree;
1280 tree = extract(stmt->getBody());
1281 if (partial)
1282 return tree;
1283 pe_cond = extract_expr(stmt->getCond());
1284 tree = pet_tree_new_while(pe_cond, tree);
1286 return tree;
1289 /* Construct a pet_tree for a for statement.
1290 * The for loop is required to be of one of the following forms
1292 * for (i = init; condition; ++i)
1293 * for (i = init; condition; --i)
1294 * for (i = init; condition; i += constant)
1295 * for (i = init; condition; i -= constant)
1297 * We extract a pet_tree for the body and then include it in a pet_tree
1298 * of type pet_tree_for.
1300 * As a special case, we also allow a for loop of the form
1302 * for (;;)
1304 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1306 * If we were only able to extract part of the body, then simply
1307 * return that part.
1309 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1311 BinaryOperator *ass;
1312 Decl *decl;
1313 Stmt *init;
1314 Expr *lhs, *rhs;
1315 ValueDecl *iv;
1316 pet_tree *tree;
1317 struct pet_scop *scop;
1318 int independent;
1319 int declared;
1320 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1322 independent = is_current_stmt_marked_independent();
1324 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1325 tree = extract(stmt->getBody());
1326 if (partial)
1327 return tree;
1328 tree = pet_tree_new_infinite_loop(tree);
1329 return tree;
1332 init = stmt->getInit();
1333 if (!init) {
1334 unsupported(stmt);
1335 return NULL;
1337 if ((ass = initialization_assignment(init)) != NULL) {
1338 iv = extract_induction_variable(ass);
1339 if (!iv)
1340 return NULL;
1341 lhs = ass->getLHS();
1342 rhs = ass->getRHS();
1343 } else if ((decl = initialization_declaration(init)) != NULL) {
1344 VarDecl *var = extract_induction_variable(init, decl);
1345 if (!var)
1346 return NULL;
1347 iv = var;
1348 rhs = var->getInit();
1349 lhs = create_DeclRefExpr(var);
1350 } else {
1351 unsupported(stmt->getInit());
1352 return NULL;
1355 declared = !initialization_assignment(stmt->getInit());
1356 tree = extract(stmt->getBody());
1357 if (partial)
1358 return tree;
1359 pe_iv = extract_access_expr(iv);
1360 pe_iv = mark_write(pe_iv);
1361 pe_init = extract_expr(rhs);
1362 if (!stmt->getCond())
1363 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1364 else
1365 pe_cond = extract_expr(stmt->getCond());
1366 pe_inc = extract_increment(stmt, iv);
1367 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1368 pe_inc, tree);
1369 return tree;
1372 /* Try and construct a pet_tree corresponding to a compound statement.
1374 * "skip_declarations" is set if we should skip initial declarations
1375 * in the children of the compound statements. This then implies
1376 * that this sequence of children should not be treated as a block
1377 * since the initial statements may be skipped.
1379 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1380 bool skip_declarations)
1382 return extract(stmt->children(), !skip_declarations, skip_declarations);
1385 /* Return the file offset of the expansion location of "Loc".
1387 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1389 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1392 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1394 /* Return a SourceLocation for the location after the first semicolon
1395 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1396 * call it and also skip trailing spaces and newline.
1398 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1399 const LangOptions &LO)
1401 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1404 #else
1406 /* Return a SourceLocation for the location after the first semicolon
1407 * after "loc". If Lexer::findLocationAfterToken is not available,
1408 * we look in the underlying character data for the first semicolon.
1410 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1411 const LangOptions &LO)
1413 const char *semi;
1414 const char *s = SM.getCharacterData(loc);
1416 semi = strchr(s, ';');
1417 if (!semi)
1418 return SourceLocation();
1419 return loc.getFileLocWithOffset(semi + 1 - s);
1422 #endif
1424 /* If the token at "loc" is the first token on the line, then return
1425 * a location referring to the start of the line and set *indent
1426 * to the indentation of "loc"
1427 * Otherwise, return "loc" and set *indent to "".
1429 * This function is used to extend a scop to the start of the line
1430 * if the first token of the scop is also the first token on the line.
1432 * We look for the first token on the line. If its location is equal to "loc",
1433 * then the latter is the location of the first token on the line.
1435 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1436 SourceManager &SM, const LangOptions &LO, char **indent)
1438 std::pair<FileID, unsigned> file_offset_pair;
1439 llvm::StringRef file;
1440 const char *pos;
1441 Token tok;
1442 SourceLocation token_loc, line_loc;
1443 int col;
1444 const char *s;
1446 loc = SM.getExpansionLoc(loc);
1447 col = SM.getExpansionColumnNumber(loc);
1448 line_loc = loc.getLocWithOffset(1 - col);
1449 file_offset_pair = SM.getDecomposedLoc(line_loc);
1450 file = SM.getBufferData(file_offset_pair.first, NULL);
1451 pos = file.data() + file_offset_pair.second;
1453 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1454 file.begin(), pos, file.end());
1455 lexer.LexFromRawLexer(tok);
1456 token_loc = tok.getLocation();
1458 s = SM.getCharacterData(line_loc);
1459 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1461 if (token_loc == loc)
1462 return line_loc;
1463 else
1464 return loc;
1467 /* Construct a pet_loc corresponding to the region covered by "range".
1468 * If "skip_semi" is set, then we assume "range" is followed by
1469 * a semicolon and also include this semicolon.
1471 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1472 bool skip_semi)
1474 SourceLocation loc = range.getBegin();
1475 SourceManager &SM = PP.getSourceManager();
1476 const LangOptions &LO = PP.getLangOpts();
1477 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1478 unsigned start, end;
1479 char *indent;
1481 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1482 start = getExpansionOffset(SM, loc);
1483 loc = range.getEnd();
1484 if (skip_semi)
1485 loc = location_after_semi(loc, SM, LO);
1486 else
1487 loc = PP.getLocForEndOfToken(loc);
1488 end = getExpansionOffset(SM, loc);
1490 return pet_loc_alloc(ctx, start, end, line, indent);
1493 /* Convert a top-level pet_expr to an expression pet_tree.
1495 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1496 SourceRange range, bool skip_semi)
1498 pet_loc *loc;
1499 pet_tree *tree;
1501 tree = pet_tree_new_expr(expr);
1502 loc = construct_pet_loc(range, skip_semi);
1503 tree = pet_tree_set_loc(tree, loc);
1505 return tree;
1508 /* Construct a pet_tree for an if statement.
1510 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1512 pet_expr *pe_cond;
1513 pet_tree *tree, *tree_else;
1514 struct pet_scop *scop;
1515 int int_size;
1517 pe_cond = extract_expr(stmt->getCond());
1518 tree = extract(stmt->getThen());
1519 if (stmt->getElse()) {
1520 tree_else = extract(stmt->getElse());
1521 if (options->autodetect) {
1522 if (tree && !tree_else) {
1523 partial = true;
1524 pet_expr_free(pe_cond);
1525 return tree;
1527 if (!tree && tree_else) {
1528 partial = true;
1529 pet_expr_free(pe_cond);
1530 return tree_else;
1533 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1534 } else
1535 tree = pet_tree_new_if(pe_cond, tree);
1536 return tree;
1539 /* Try and construct a pet_tree for a label statement.
1541 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1543 isl_id *label;
1544 pet_tree *tree;
1546 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1548 tree = extract(stmt->getSubStmt());
1549 tree = pet_tree_set_label(tree, label);
1550 return tree;
1553 /* Update the location of "tree" to include the source range of "stmt".
1555 * Actually, we create a new location based on the source range of "stmt" and
1556 * then extend this new location to include the region of the original location.
1557 * This ensures that the line number of the final location refers to "stmt".
1559 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1561 pet_loc *loc, *tree_loc;
1563 tree_loc = pet_tree_get_loc(tree);
1564 loc = construct_pet_loc(stmt->getSourceRange(), false);
1565 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1566 pet_loc_free(tree_loc);
1568 tree = pet_tree_set_loc(tree, loc);
1569 return tree;
1572 /* Try and construct a pet_tree corresponding to "stmt".
1574 * If "stmt" is a compound statement, then "skip_declarations"
1575 * indicates whether we should skip initial declarations in the
1576 * compound statement.
1578 * If the constructed pet_tree is not a (possibly) partial representation
1579 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1580 * In particular, if skip_declarations is set, then we may have skipped
1581 * declarations inside "stmt" and so the pet_scop may not represent
1582 * the entire "stmt".
1583 * Note that this function may be called with "stmt" referring to the entire
1584 * body of the function, including the outer braces. In such cases,
1585 * skip_declarations will be set and the braces will not be taken into
1586 * account in tree->loc.
1588 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
1590 pet_tree *tree;
1592 set_current_stmt(stmt);
1594 if (isa<Expr>(stmt))
1595 return extract(extract_expr(cast<Expr>(stmt)),
1596 stmt->getSourceRange(), true);
1598 switch (stmt->getStmtClass()) {
1599 case Stmt::WhileStmtClass:
1600 tree = extract(cast<WhileStmt>(stmt));
1601 break;
1602 case Stmt::ForStmtClass:
1603 tree = extract_for(cast<ForStmt>(stmt));
1604 break;
1605 case Stmt::IfStmtClass:
1606 tree = extract(cast<IfStmt>(stmt));
1607 break;
1608 case Stmt::CompoundStmtClass:
1609 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
1610 break;
1611 case Stmt::LabelStmtClass:
1612 tree = extract(cast<LabelStmt>(stmt));
1613 break;
1614 case Stmt::ContinueStmtClass:
1615 tree = pet_tree_new_continue(ctx);
1616 break;
1617 case Stmt::BreakStmtClass:
1618 tree = pet_tree_new_break(ctx);
1619 break;
1620 case Stmt::DeclStmtClass:
1621 tree = extract(cast<DeclStmt>(stmt));
1622 break;
1623 default:
1624 unsupported(stmt);
1625 return NULL;
1628 if (partial || skip_declarations)
1629 return tree;
1631 return update_loc(tree, stmt);
1634 /* Try and construct a pet_tree corresponding to (part of)
1635 * a sequence of statements.
1637 * "block" is set if the sequence represents the children of
1638 * a compound statement.
1639 * "skip_declarations" is set if we should skip initial declarations
1640 * in the sequence of statements.
1642 * If autodetect is set, then we allow the extraction of only a subrange
1643 * of the sequence of statements. However, if there is at least one statement
1644 * for which we could not construct a scop and the final range contains
1645 * either no statements or at least one kill, then we discard the entire
1646 * range.
1648 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
1649 bool skip_declarations)
1651 StmtIterator i;
1652 int j;
1653 bool has_kills = false;
1654 bool partial_range = false;
1655 pet_tree *tree;
1656 set<struct pet_stmt *> kills;
1657 set<struct pet_stmt *>::iterator it;
1659 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
1662 tree = pet_tree_new_block(ctx, block, j);
1664 for (i = stmt_range.first; i != stmt_range.second; ++i) {
1665 Stmt *child = *i;
1666 pet_tree *tree_i;
1668 if (pet_tree_block_n_child(tree) == 0 && skip_declarations &&
1669 child->getStmtClass() == Stmt::DeclStmtClass)
1670 continue;
1672 tree_i = extract(child);
1673 if (pet_tree_block_n_child(tree) != 0 && partial) {
1674 pet_tree_free(tree_i);
1675 break;
1677 if (tree_i && child->getStmtClass() == Stmt::DeclStmtClass &&
1678 block)
1679 has_kills = true;
1680 if (options->autodetect) {
1681 if (tree_i)
1682 tree = pet_tree_block_add_child(tree, tree_i);
1683 else
1684 partial_range = true;
1685 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
1686 partial = true;
1687 } else {
1688 tree = pet_tree_block_add_child(tree, tree_i);
1691 if (partial || !tree)
1692 break;
1695 if (tree && partial_range) {
1696 if (pet_tree_block_n_child(tree) == 0 || has_kills) {
1697 pet_tree_free(tree);
1698 return NULL;
1700 partial = true;
1703 return tree;
1706 /* Is "T" the type of a variable length array with static size?
1708 static bool is_vla_with_static_size(QualType T)
1710 const VariableArrayType *vlatype;
1712 if (!T->isVariableArrayType())
1713 return false;
1714 vlatype = cast<VariableArrayType>(T);
1715 return vlatype->getSizeModifier() == VariableArrayType::Static;
1718 /* Return the type of "decl" as an array.
1720 * In particular, if "decl" is a parameter declaration that
1721 * is a variable length array with a static size, then
1722 * return the original type (i.e., the variable length array).
1723 * Otherwise, return the type of decl.
1725 static QualType get_array_type(ValueDecl *decl)
1727 ParmVarDecl *parm;
1728 QualType T;
1730 parm = dyn_cast<ParmVarDecl>(decl);
1731 if (!parm)
1732 return decl->getType();
1734 T = parm->getOriginalType();
1735 if (!is_vla_with_static_size(T))
1736 return decl->getType();
1737 return T;
1740 extern "C" {
1741 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1742 void *user);
1743 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1744 __isl_keep pet_context *pc, void *user);
1747 /* Construct a pet_expr that holds the sizes of the array accessed
1748 * by "access".
1749 * This function is used as a callback to pet_context_add_parameters,
1750 * which is also passed a pointer to the PetScan object.
1752 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1753 void *user)
1755 PetScan *ps = (PetScan *) user;
1756 isl_id *id;
1757 ValueDecl *decl;
1758 const Type *type;
1760 id = pet_expr_access_get_id(access);
1761 decl = (ValueDecl *) isl_id_get_user(id);
1762 isl_id_free(id);
1763 type = get_array_type(decl).getTypePtr();
1764 return ps->get_array_size(type);
1767 /* Construct and return a pet_array corresponding to the variable
1768 * accessed by "access".
1769 * This function is used as a callback to pet_scop_from_pet_tree,
1770 * which is also passed a pointer to the PetScan object.
1772 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1773 __isl_keep pet_context *pc, void *user)
1775 PetScan *ps = (PetScan *) user;
1776 isl_ctx *ctx;
1777 isl_id *id;
1778 ValueDecl *iv;
1780 ctx = pet_expr_get_ctx(access);
1781 id = pet_expr_access_get_id(access);
1782 iv = (ValueDecl *) isl_id_get_user(id);
1783 isl_id_free(id);
1784 return ps->extract_array(ctx, iv, NULL, pc);
1787 /* Extract a function summary from the body of "fd".
1789 * We extract a scop from the function body in a context with as
1790 * parameters the integer arguments of the function.
1791 * We turn off autodetection (in case it was set) to ensure that
1792 * the entire function body is considered.
1793 * We then collect the accessed array elements and attach them
1794 * to the corresponding array arguments, taking into account
1795 * that the function body may access members of array elements.
1797 * The reason for representing the integer arguments as parameters in
1798 * the context is that if we were to instead start with a context
1799 * with the function arguments as initial dimensions, then we would not
1800 * be able to refer to them from the array extents, without turning
1801 * array extents into maps.
1803 * The result is stored in the summary_cache cache so that we can reuse
1804 * it if this method gets called on the same function again later on.
1806 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
1808 isl_space *space;
1809 isl_set *domain;
1810 pet_context *pc;
1811 pet_tree *tree;
1812 pet_function_summary *summary;
1813 unsigned n;
1814 ScopLoc loc;
1815 int save_autodetect;
1816 struct pet_scop *scop;
1817 int int_size;
1818 isl_union_set *may_read, *may_write, *must_write;
1819 isl_union_map *to_inner;
1821 if (summary_cache.find(fd) != summary_cache.end())
1822 return pet_function_summary_copy(summary_cache[fd]);
1824 space = isl_space_set_alloc(ctx, 0, 0);
1826 n = fd->getNumParams();
1827 summary = pet_function_summary_alloc(ctx, n);
1828 for (int i = 0; i < n; ++i) {
1829 ParmVarDecl *parm = fd->getParamDecl(i);
1830 QualType type = parm->getType();
1831 isl_id *id;
1833 if (!type->isIntegerType())
1834 continue;
1835 id = create_decl_id(ctx, parm);
1836 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
1837 space = isl_space_set_dim_id(space, isl_dim_param, 0,
1838 isl_id_copy(id));
1839 summary = pet_function_summary_set_int(summary, i, id);
1842 save_autodetect = options->autodetect;
1843 options->autodetect = 0;
1844 PetScan body_scan(PP, ast_context, loc, options,
1845 isl_union_map_copy(value_bounds), independent);
1847 tree = body_scan.extract(fd->getBody(), false);
1849 domain = isl_set_universe(space);
1850 pc = pet_context_alloc(domain);
1851 pc = pet_context_add_parameters(pc, tree,
1852 &::get_array_size, &body_scan);
1853 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
1854 scop = pet_scop_from_pet_tree(tree, int_size,
1855 &::extract_array, &body_scan, pc);
1856 scop = scan_arrays(scop, pc);
1857 may_read = isl_union_map_range(pet_scop_collect_may_reads(scop));
1858 may_write = isl_union_map_range(pet_scop_collect_may_writes(scop));
1859 must_write = isl_union_map_range(pet_scop_collect_must_writes(scop));
1860 to_inner = pet_scop_compute_outer_to_inner(scop);
1861 pet_scop_free(scop);
1863 for (int i = 0; i < n; ++i) {
1864 ParmVarDecl *parm = fd->getParamDecl(i);
1865 QualType type = parm->getType();
1866 struct pet_array *array;
1867 isl_space *space;
1868 isl_union_set *data_set;
1869 isl_union_set *may_read_i, *may_write_i, *must_write_i;
1871 if (array_depth(type.getTypePtr()) == 0)
1872 continue;
1874 array = body_scan.extract_array(ctx, parm, NULL, pc);
1875 space = array ? isl_set_get_space(array->extent) : NULL;
1876 pet_array_free(array);
1877 data_set = isl_union_set_from_set(isl_set_universe(space));
1878 data_set = isl_union_set_apply(data_set,
1879 isl_union_map_copy(to_inner));
1880 may_read_i = isl_union_set_intersect(
1881 isl_union_set_copy(may_read),
1882 isl_union_set_copy(data_set));
1883 may_write_i = isl_union_set_intersect(
1884 isl_union_set_copy(may_write),
1885 isl_union_set_copy(data_set));
1886 must_write_i = isl_union_set_intersect(
1887 isl_union_set_copy(must_write), data_set);
1888 summary = pet_function_summary_set_array(summary, i,
1889 may_read_i, may_write_i, must_write_i);
1892 isl_union_set_free(may_read);
1893 isl_union_set_free(may_write);
1894 isl_union_set_free(must_write);
1895 isl_union_map_free(to_inner);
1897 options->autodetect = save_autodetect;
1898 pet_context_free(pc);
1900 summary_cache[fd] = pet_function_summary_copy(summary);
1902 return summary;
1905 /* If "fd" has a function body, then extract a function summary from
1906 * this body and attach it to the call expression "expr".
1908 * Even if a function body is available, "fd" itself may point
1909 * to a declaration without function body. We therefore first
1910 * replace it by the declaration that comes with a body (if any).
1912 * It is not clear why hasBody takes a reference to a const FunctionDecl *.
1913 * It seems that it is possible to directly use the iterators to obtain
1914 * a non-const pointer.
1915 * Since we are not going to use the pointer to modify anything anyway,
1916 * it seems safe to drop the constness. The alternative would be to
1917 * modify a lot of other functions to include const qualifiers.
1919 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
1920 FunctionDecl *fd)
1922 pet_function_summary *summary;
1923 const FunctionDecl *def;
1925 if (!expr)
1926 return NULL;
1927 if (!fd->hasBody(def))
1928 return expr;
1930 fd = const_cast<FunctionDecl *>(def);
1932 summary = get_summary(fd);
1934 expr = pet_expr_call_set_summary(expr, summary);
1936 return expr;
1939 /* Extract a pet_scop from "tree".
1941 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
1942 * then add pet_arrays for all accessed arrays.
1943 * We populate the pet_context with assignments for all parameters used
1944 * inside "tree" or any of the size expressions for the arrays accessed
1945 * by "tree" so that they can be used in affine expressions.
1947 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
1949 int int_size;
1950 isl_set *domain;
1951 pet_context *pc;
1952 pet_scop *scop;
1954 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
1956 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
1957 pc = pet_context_alloc(domain);
1958 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
1959 scop = pet_scop_from_pet_tree(tree, int_size,
1960 &::extract_array, this, pc);
1961 scop = scan_arrays(scop, pc);
1962 pet_context_free(pc);
1964 return scop;
1967 /* Check if the scop marked by the user is exactly this Stmt
1968 * or part of this Stmt.
1969 * If so, return a pet_scop corresponding to the marked region.
1970 * Otherwise, return NULL.
1972 struct pet_scop *PetScan::scan(Stmt *stmt)
1974 SourceManager &SM = PP.getSourceManager();
1975 unsigned start_off, end_off;
1977 start_off = getExpansionOffset(SM, stmt->getLocStart());
1978 end_off = getExpansionOffset(SM, stmt->getLocEnd());
1980 if (start_off > loc.end)
1981 return NULL;
1982 if (end_off < loc.start)
1983 return NULL;
1985 if (start_off >= loc.start && end_off <= loc.end)
1986 return extract_scop(extract(stmt));
1988 StmtIterator start;
1989 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
1990 Stmt *child = *start;
1991 if (!child)
1992 continue;
1993 start_off = getExpansionOffset(SM, child->getLocStart());
1994 end_off = getExpansionOffset(SM, child->getLocEnd());
1995 if (start_off < loc.start && end_off >= loc.end)
1996 return scan(child);
1997 if (start_off >= loc.start)
1998 break;
2001 StmtIterator end;
2002 for (end = start; end != stmt->child_end(); ++end) {
2003 Stmt *child = *end;
2004 start_off = SM.getFileOffset(child->getLocStart());
2005 if (start_off >= loc.end)
2006 break;
2009 return extract_scop(extract(StmtRange(start, end), false, false));
2012 /* Set the size of index "pos" of "array" to "size".
2013 * In particular, add a constraint of the form
2015 * i_pos < size
2017 * to array->extent and a constraint of the form
2019 * size >= 0
2021 * to array->context.
2023 * The domain of "size" is assumed to be zero-dimensional.
2025 static struct pet_array *update_size(struct pet_array *array, int pos,
2026 __isl_take isl_pw_aff *size)
2028 isl_set *valid;
2029 isl_set *univ;
2030 isl_set *bound;
2031 isl_space *dim;
2032 isl_aff *aff;
2033 isl_pw_aff *index;
2034 isl_id *id;
2036 if (!array)
2037 goto error;
2039 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2040 array->context = isl_set_intersect(array->context, valid);
2042 dim = isl_set_get_space(array->extent);
2043 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2044 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2045 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2046 index = isl_pw_aff_alloc(univ, aff);
2048 size = isl_pw_aff_add_dims(size, isl_dim_in,
2049 isl_set_dim(array->extent, isl_dim_set));
2050 id = isl_set_get_tuple_id(array->extent);
2051 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2052 bound = isl_pw_aff_lt_set(index, size);
2054 array->extent = isl_set_intersect(array->extent, bound);
2056 if (!array->context || !array->extent)
2057 return pet_array_free(array);
2059 return array;
2060 error:
2061 isl_pw_aff_free(size);
2062 return NULL;
2065 #ifdef HAVE_DECAYEDTYPE
2067 /* If "type" is a decayed type, then set *decayed to true and
2068 * return the original type.
2070 static const Type *undecay(const Type *type, bool *decayed)
2072 *decayed = isa<DecayedType>(type);
2073 if (*decayed)
2074 type = cast<DecayedType>(type)->getOriginalType().getTypePtr();
2075 return type;
2078 #else
2080 /* If "type" is a decayed type, then set *decayed to true and
2081 * return the original type.
2082 * Since this version of clang does not define a DecayedType,
2083 * we cannot obtain the original type even if it had been decayed and
2084 * we set *decayed to false.
2086 static const Type *undecay(const Type *type, bool *decayed)
2088 *decayed = false;
2089 return type;
2092 #endif
2094 /* Figure out the size of the array at position "pos" and all
2095 * subsequent positions from "type" and update the corresponding
2096 * argument of "expr" accordingly.
2098 * The initial type (when pos is zero) may be a pointer type decayed
2099 * from an array type, if this initial type is the type of a function
2100 * argument. This only happens if the original array type has
2101 * a constant size in the outer dimension as otherwise we get
2102 * a VariableArrayType. Try and obtain this original type (if available) and
2103 * take the outer array size into account if it was marked static.
2105 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2106 const Type *type, int pos)
2108 const ArrayType *atype;
2109 pet_expr *size;
2110 bool decayed = false;
2112 if (!expr)
2113 return NULL;
2115 if (pos == 0)
2116 type = undecay(type, &decayed);
2118 if (type->isPointerType()) {
2119 type = type->getPointeeType().getTypePtr();
2120 return set_upper_bounds(expr, type, pos + 1);
2122 if (!type->isArrayType())
2123 return expr;
2125 type = type->getCanonicalTypeInternal().getTypePtr();
2126 atype = cast<ArrayType>(type);
2128 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2129 type = atype->getElementType().getTypePtr();
2130 return set_upper_bounds(expr, type, pos + 1);
2133 if (type->isConstantArrayType()) {
2134 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2135 size = extract_expr(ca->getSize());
2136 expr = pet_expr_set_arg(expr, pos, size);
2137 } else if (type->isVariableArrayType()) {
2138 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2139 size = extract_expr(vla->getSizeExpr());
2140 expr = pet_expr_set_arg(expr, pos, size);
2143 type = atype->getElementType().getTypePtr();
2145 return set_upper_bounds(expr, type, pos + 1);
2148 /* Construct a pet_expr that holds the sizes of an array of the given type.
2149 * The returned expression is a call expression with as arguments
2150 * the sizes in each dimension. If we are unable to derive the size
2151 * in a given dimension, then the corresponding argument is set to infinity.
2152 * In fact, we initialize all arguments to infinity and then update
2153 * them if we are able to figure out the size.
2155 * The result is stored in the type_size cache so that we can reuse
2156 * it if this method gets called on the same type again later on.
2158 __isl_give pet_expr *PetScan::get_array_size(const Type *type)
2160 int depth;
2161 pet_expr *expr, *inf;
2163 if (type_size.find(type) != type_size.end())
2164 return pet_expr_copy(type_size[type]);
2166 depth = array_depth(type);
2167 inf = pet_expr_new_int(isl_val_infty(ctx));
2168 expr = pet_expr_new_call(ctx, "bounds", depth);
2169 for (int i = 0; i < depth; ++i)
2170 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2171 pet_expr_free(inf);
2173 expr = set_upper_bounds(expr, type, 0);
2174 type_size[type] = pet_expr_copy(expr);
2176 return expr;
2179 /* Does "expr" represent the "integer" infinity?
2181 static int is_infty(__isl_keep pet_expr *expr)
2183 isl_val *v;
2184 int res;
2186 if (pet_expr_get_type(expr) != pet_expr_int)
2187 return 0;
2188 v = pet_expr_int_get_val(expr);
2189 res = isl_val_is_infty(v);
2190 isl_val_free(v);
2192 return res;
2195 /* Figure out the dimensions of an array "array" based on its type
2196 * "type" and update "array" accordingly.
2198 * We first construct a pet_expr that holds the sizes of the array
2199 * in each dimension. The resulting expression may containing
2200 * infinity values for dimension where we are unable to derive
2201 * a size expression.
2203 * The arguments of the size expression that have a value different from
2204 * infinity are then converted to an affine expression
2205 * within the context "pc" and incorporated into the size of "array".
2206 * If we are unable to convert a size expression to an affine expression or
2207 * if the size is not a (symbolic) constant,
2208 * then we leave the corresponding size of "array" untouched.
2210 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2211 const Type *type, __isl_keep pet_context *pc)
2213 int n;
2214 pet_expr *expr;
2216 if (!array)
2217 return NULL;
2219 expr = get_array_size(type);
2221 n = pet_expr_get_n_arg(expr);
2222 for (int i = 0; i < n; ++i) {
2223 pet_expr *arg;
2224 isl_pw_aff *size;
2226 arg = pet_expr_get_arg(expr, i);
2227 if (!is_infty(arg)) {
2228 int dim;
2230 size = pet_expr_extract_affine(arg, pc);
2231 dim = isl_pw_aff_dim(size, isl_dim_in);
2232 if (!size)
2233 array = pet_array_free(array);
2234 else if (isl_pw_aff_involves_nan(size) ||
2235 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2236 isl_pw_aff_free(size);
2237 else {
2238 size = isl_pw_aff_drop_dims(size,
2239 isl_dim_in, 0, dim);
2240 array = update_size(array, i, size);
2243 pet_expr_free(arg);
2245 pet_expr_free(expr);
2247 return array;
2250 /* Does "decl" have definition that we can keep track of in a pet_type?
2252 static bool has_printable_definition(RecordDecl *decl)
2254 if (!decl->getDeclName())
2255 return false;
2256 return decl->getLexicalDeclContext() == decl->getDeclContext();
2259 /* Construct and return a pet_array corresponding to the variable "decl".
2260 * In particular, initialize array->extent to
2262 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2264 * and then call set_upper_bounds to set the upper bounds on the indices
2265 * based on the type of the variable. The upper bounds are converted
2266 * to affine expressions within the context "pc".
2268 * If the base type is that of a record with a top-level definition and
2269 * if "types" is not null, then the RecordDecl corresponding to the type
2270 * is added to "types".
2272 * If the base type is that of a record with no top-level definition,
2273 * then we replace it by "<subfield>".
2275 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
2276 lex_recorddecl_set *types, __isl_keep pet_context *pc)
2278 struct pet_array *array;
2279 QualType qt = get_array_type(decl);
2280 const Type *type = qt.getTypePtr();
2281 int depth = array_depth(type);
2282 QualType base = pet_clang_base_type(qt);
2283 string name;
2284 isl_id *id;
2285 isl_space *dim;
2287 array = isl_calloc_type(ctx, struct pet_array);
2288 if (!array)
2289 return NULL;
2291 id = create_decl_id(ctx, decl);
2292 dim = isl_space_set_alloc(ctx, 0, depth);
2293 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
2295 array->extent = isl_set_nat_universe(dim);
2297 dim = isl_space_params_alloc(ctx, 0);
2298 array->context = isl_set_universe(dim);
2300 array = set_upper_bounds(array, type, pc);
2301 if (!array)
2302 return NULL;
2304 name = base.getAsString();
2306 if (types && base->isRecordType()) {
2307 RecordDecl *decl = pet_clang_record_decl(base);
2308 if (has_printable_definition(decl))
2309 types->insert(decl);
2310 else
2311 name = "<subfield>";
2314 array->element_type = strdup(name.c_str());
2315 array->element_is_record = base->isRecordType();
2316 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
2318 return array;
2321 /* Construct and return a pet_array corresponding to the sequence
2322 * of declarations "decls".
2323 * The upper bounds of the array are converted to affine expressions
2324 * within the context "pc".
2325 * If the sequence contains a single declaration, then it corresponds
2326 * to a simple array access. Otherwise, it corresponds to a member access,
2327 * with the declaration for the substructure following that of the containing
2328 * structure in the sequence of declarations.
2329 * We start with the outermost substructure and then combine it with
2330 * information from the inner structures.
2332 * Additionally, keep track of all required types in "types".
2334 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
2335 vector<ValueDecl *> decls, lex_recorddecl_set *types,
2336 __isl_keep pet_context *pc)
2338 struct pet_array *array;
2339 vector<ValueDecl *>::iterator it;
2341 it = decls.begin();
2343 array = extract_array(ctx, *it, types, pc);
2345 for (++it; it != decls.end(); ++it) {
2346 struct pet_array *parent;
2347 const char *base_name, *field_name;
2348 char *product_name;
2350 parent = array;
2351 array = extract_array(ctx, *it, types, pc);
2352 if (!array)
2353 return pet_array_free(parent);
2355 base_name = isl_set_get_tuple_name(parent->extent);
2356 field_name = isl_set_get_tuple_name(array->extent);
2357 product_name = pet_array_member_access_name(ctx,
2358 base_name, field_name);
2360 array->extent = isl_set_product(isl_set_copy(parent->extent),
2361 array->extent);
2362 if (product_name)
2363 array->extent = isl_set_set_tuple_name(array->extent,
2364 product_name);
2365 array->context = isl_set_intersect(array->context,
2366 isl_set_copy(parent->context));
2368 pet_array_free(parent);
2369 free(product_name);
2371 if (!array->extent || !array->context || !product_name)
2372 return pet_array_free(array);
2375 return array;
2378 /* Add a pet_type corresponding to "decl" to "scop, provided
2379 * it is a member of "types" and it has not been added before
2380 * (i.e., it is not a member of "types_done".
2382 * Since we want the user to be able to print the types
2383 * in the order in which they appear in the scop, we need to
2384 * make sure that types of fields in a structure appear before
2385 * that structure. We therefore call ourselves recursively
2386 * on the types of all record subfields.
2388 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2389 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
2390 lex_recorddecl_set &types_done)
2392 string s;
2393 llvm::raw_string_ostream S(s);
2394 RecordDecl::field_iterator it;
2396 if (types.find(decl) == types.end())
2397 return scop;
2398 if (types_done.find(decl) != types_done.end())
2399 return scop;
2401 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
2402 RecordDecl *record;
2403 QualType type = it->getType();
2405 if (!type->isRecordType())
2406 continue;
2407 record = pet_clang_record_decl(type);
2408 scop = add_type(ctx, scop, record, PP, types, types_done);
2411 if (strlen(decl->getName().str().c_str()) == 0)
2412 return scop;
2414 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2415 S.str();
2417 scop->types[scop->n_type] = pet_type_alloc(ctx,
2418 decl->getName().str().c_str(), s.c_str());
2419 if (!scop->types[scop->n_type])
2420 return pet_scop_free(scop);
2422 types_done.insert(decl);
2424 scop->n_type++;
2426 return scop;
2429 /* Construct a list of pet_arrays, one for each array (or scalar)
2430 * accessed inside "scop", add this list to "scop" and return the result.
2431 * The upper bounds of the arrays are converted to affine expressions
2432 * within the context "pc".
2434 * The context of "scop" is updated with the intersection of
2435 * the contexts of all arrays, i.e., constraints on the parameters
2436 * that ensure that the arrays have a valid (non-negative) size.
2438 * If the any of the extracted arrays refers to a member access,
2439 * then also add the required types to "scop".
2441 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
2442 __isl_keep pet_context *pc)
2444 int i;
2445 array_desc_set arrays;
2446 array_desc_set::iterator it;
2447 lex_recorddecl_set types;
2448 lex_recorddecl_set types_done;
2449 lex_recorddecl_set::iterator types_it;
2450 int n_array;
2451 struct pet_array **scop_arrays;
2453 if (!scop)
2454 return NULL;
2456 pet_scop_collect_arrays(scop, arrays);
2457 if (arrays.size() == 0)
2458 return scop;
2460 n_array = scop->n_array;
2462 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2463 n_array + arrays.size());
2464 if (!scop_arrays)
2465 goto error;
2466 scop->arrays = scop_arrays;
2468 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
2469 struct pet_array *array;
2470 array = extract_array(ctx, *it, &types, pc);
2471 scop->arrays[n_array + i] = array;
2472 if (!scop->arrays[n_array + i])
2473 goto error;
2474 scop->n_array++;
2475 scop->context = isl_set_intersect(scop->context,
2476 isl_set_copy(array->context));
2477 if (!scop->context)
2478 goto error;
2481 if (types.size() == 0)
2482 return scop;
2484 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
2485 if (!scop->types)
2486 goto error;
2488 for (types_it = types.begin(); types_it != types.end(); ++types_it)
2489 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
2491 return scop;
2492 error:
2493 pet_scop_free(scop);
2494 return NULL;
2497 /* Bound all parameters in scop->context to the possible values
2498 * of the corresponding C variable.
2500 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
2502 int n;
2504 if (!scop)
2505 return NULL;
2507 n = isl_set_dim(scop->context, isl_dim_param);
2508 for (int i = 0; i < n; ++i) {
2509 isl_id *id;
2510 ValueDecl *decl;
2512 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
2513 if (pet_nested_in_id(id)) {
2514 isl_id_free(id);
2515 isl_die(isl_set_get_ctx(scop->context),
2516 isl_error_internal,
2517 "unresolved nested parameter", goto error);
2519 decl = (ValueDecl *) isl_id_get_user(id);
2520 isl_id_free(id);
2522 scop->context = set_parameter_bounds(scop->context, i, decl);
2524 if (!scop->context)
2525 goto error;
2528 return scop;
2529 error:
2530 pet_scop_free(scop);
2531 return NULL;
2534 /* Construct a pet_scop from the given function.
2536 * If the scop was delimited by scop and endscop pragmas, then we override
2537 * the file offsets by those derived from the pragmas.
2539 struct pet_scop *PetScan::scan(FunctionDecl *fd)
2541 pet_scop *scop;
2542 Stmt *stmt;
2544 stmt = fd->getBody();
2546 if (options->autodetect) {
2547 set_current_stmt(stmt);
2548 scop = extract_scop(extract(stmt, true));
2549 } else {
2550 current_line = loc.start_line;
2551 scop = scan(stmt);
2552 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
2554 scop = add_parameter_bounds(scop);
2555 scop = pet_scop_gist(scop, value_bounds);
2557 return scop;
2560 /* Update this->last_line and this->current_line based on the fact
2561 * that we are about to consider "stmt".
2563 void PetScan::set_current_stmt(Stmt *stmt)
2565 SourceLocation loc = stmt->getLocStart();
2566 SourceManager &SM = PP.getSourceManager();
2568 last_line = current_line;
2569 current_line = SM.getExpansionLineNumber(loc);
2572 /* Is the current statement marked by an independent pragma?
2573 * That is, is there an independent pragma on a line between
2574 * the line of the current statement and the line of the previous statement.
2575 * The search is not implemented very efficiently. We currently
2576 * assume that there are only a few independent pragmas, if any.
2578 bool PetScan::is_current_stmt_marked_independent()
2580 for (int i = 0; i < independent.size(); ++i) {
2581 unsigned line = independent[i].line;
2583 if (last_line < line && line < current_line)
2584 return true;
2587 return false;