adjust to change in clang's JobList
[pet.git] / scan.cc
blob8a3e75d0204e1b8565df41039c352b5cc198afca
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 an unsupported statement type, unless autodetect is set.
233 void PetScan::report_unsupported_statement_type(Stmt *stmt)
235 DiagnosticsEngine &diag = PP.getDiagnostics();
236 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
237 "this type of statement is not supported");
238 report(stmt, id);
241 /* Report a missing prototype, unless autodetect is set.
243 void PetScan::report_prototype_required(Stmt *stmt)
245 DiagnosticsEngine &diag = PP.getDiagnostics();
246 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
247 "prototype required");
248 report(stmt, id);
251 /* Report a missing increment, unless autodetect is set.
253 void PetScan::report_missing_increment(Stmt *stmt)
255 DiagnosticsEngine &diag = PP.getDiagnostics();
256 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
257 "missing increment");
258 report(stmt, id);
261 /* Report a missing summary function, unless autodetect is set.
263 void PetScan::report_missing_summary_function(Stmt *stmt)
265 DiagnosticsEngine &diag = PP.getDiagnostics();
266 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
267 "missing summary function");
268 report(stmt, id);
271 /* Report a missing summary function body, unless autodetect is set.
273 void PetScan::report_missing_summary_function_body(Stmt *stmt)
275 DiagnosticsEngine &diag = PP.getDiagnostics();
276 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
277 "missing summary function body");
278 report(stmt, id);
281 /* Extract an integer from "val", which is assumed to be non-negative.
283 static __isl_give isl_val *extract_unsigned(isl_ctx *ctx,
284 const llvm::APInt &val)
286 unsigned n;
287 const uint64_t *data;
289 data = val.getRawData();
290 n = val.getNumWords();
291 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
294 /* Extract an integer from "val". If "is_signed" is set, then "val"
295 * is signed. Otherwise it it unsigned.
297 static __isl_give isl_val *extract_int(isl_ctx *ctx, bool is_signed,
298 llvm::APInt val)
300 int is_negative = is_signed && val.isNegative();
301 isl_val *v;
303 if (is_negative)
304 val = -val;
306 v = extract_unsigned(ctx, val);
308 if (is_negative)
309 v = isl_val_neg(v);
310 return v;
313 /* Extract an integer from "expr".
315 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
317 const Type *type = expr->getType().getTypePtr();
318 bool is_signed = type->hasSignedIntegerRepresentation();
320 return ::extract_int(ctx, is_signed, expr->getValue());
323 /* Extract an integer from "expr".
324 * Return NULL if "expr" does not (obviously) represent an integer.
326 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
328 return extract_int(expr->getSubExpr());
331 /* Extract an integer from "expr".
332 * Return NULL if "expr" does not (obviously) represent an integer.
334 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
336 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
337 return extract_int(ctx, cast<IntegerLiteral>(expr));
338 if (expr->getStmtClass() == Stmt::ParenExprClass)
339 return extract_int(cast<ParenExpr>(expr));
341 unsupported(expr);
342 return NULL;
345 /* Extract a pet_expr from the APInt "val", which is assumed
346 * to be non-negative.
348 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
350 return pet_expr_new_int(extract_unsigned(ctx, val));
353 /* Return the number of bits needed to represent the type "qt",
354 * if it is an integer type. Otherwise return 0.
355 * If qt is signed then return the opposite of the number of bits.
357 static int get_type_size(QualType qt, ASTContext &ast_context)
359 int size;
361 if (!qt->isIntegerType())
362 return 0;
364 size = ast_context.getIntWidth(qt);
365 if (!qt->isUnsignedIntegerType())
366 size = -size;
368 return size;
371 /* Return the number of bits needed to represent the type of "decl",
372 * if it is an integer type. Otherwise return 0.
373 * If qt is signed then return the opposite of the number of bits.
375 static int get_type_size(ValueDecl *decl)
377 return get_type_size(decl->getType(), decl->getASTContext());
380 /* Bound parameter "pos" of "set" to the possible values of "decl".
382 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
383 unsigned pos, ValueDecl *decl)
385 int type_size;
386 isl_ctx *ctx;
387 isl_val *bound;
389 ctx = isl_set_get_ctx(set);
390 type_size = get_type_size(decl);
391 if (type_size == 0)
392 isl_die(ctx, isl_error_invalid, "not an integer type",
393 return isl_set_free(set));
394 if (type_size > 0) {
395 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
396 bound = isl_val_int_from_ui(ctx, type_size);
397 bound = isl_val_2exp(bound);
398 bound = isl_val_sub_ui(bound, 1);
399 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
400 } else {
401 bound = isl_val_int_from_ui(ctx, -type_size - 1);
402 bound = isl_val_2exp(bound);
403 bound = isl_val_sub_ui(bound, 1);
404 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
405 isl_val_copy(bound));
406 bound = isl_val_neg(bound);
407 bound = isl_val_sub_ui(bound, 1);
408 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
411 return set;
414 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
416 return extract_index_expr(expr->getSubExpr());
419 /* Return the depth of an array of the given type.
421 static int array_depth(const Type *type)
423 if (type->isPointerType())
424 return 1 + array_depth(type->getPointeeType().getTypePtr());
425 if (type->isArrayType()) {
426 const ArrayType *atype;
427 type = type->getCanonicalTypeInternal().getTypePtr();
428 atype = cast<ArrayType>(type);
429 return 1 + array_depth(atype->getElementType().getTypePtr());
431 return 0;
434 /* Return the depth of the array accessed by the index expression "index".
435 * If "index" is an affine expression, i.e., if it does not access
436 * any array, then return 1.
437 * If "index" represent a member access, i.e., if its range is a wrapped
438 * relation, then return the sum of the depth of the array of structures
439 * and that of the member inside the structure.
441 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
443 isl_id *id;
444 ValueDecl *decl;
446 if (!index)
447 return -1;
449 if (isl_multi_pw_aff_range_is_wrapping(index)) {
450 int domain_depth, range_depth;
451 isl_multi_pw_aff *domain, *range;
453 domain = isl_multi_pw_aff_copy(index);
454 domain = isl_multi_pw_aff_range_factor_domain(domain);
455 domain_depth = extract_depth(domain);
456 isl_multi_pw_aff_free(domain);
457 range = isl_multi_pw_aff_copy(index);
458 range = isl_multi_pw_aff_range_factor_range(range);
459 range_depth = extract_depth(range);
460 isl_multi_pw_aff_free(range);
462 return domain_depth + range_depth;
465 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
466 return 1;
468 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
469 if (!id)
470 return -1;
471 decl = (ValueDecl *) isl_id_get_user(id);
472 isl_id_free(id);
474 return array_depth(decl->getType().getTypePtr());
477 /* Return the depth of the array accessed by the access expression "expr".
479 static int extract_depth(__isl_keep pet_expr *expr)
481 isl_multi_pw_aff *index;
482 int depth;
484 index = pet_expr_access_get_index(expr);
485 depth = extract_depth(index);
486 isl_multi_pw_aff_free(index);
488 return depth;
491 /* Construct a pet_expr representing an index expression for an access
492 * to the variable referenced by "expr".
494 * If "expr" references an enum constant, then return an integer expression
495 * instead, representing the value of the enum constant.
497 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
499 return extract_index_expr(expr->getDecl());
502 /* Construct a pet_expr representing an index expression for an access
503 * to the variable "decl".
505 * If "decl" is an enum constant, then we return an integer expression
506 * instead, representing the value of the enum constant.
508 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
510 isl_id *id;
511 isl_space *space;
513 if (isa<EnumConstantDecl>(decl))
514 return extract_expr(cast<EnumConstantDecl>(decl));
516 id = create_decl_id(ctx, decl);
517 space = isl_space_alloc(ctx, 0, 0, 0);
518 space = isl_space_set_tuple_id(space, isl_dim_out, id);
520 return pet_expr_from_index(isl_multi_pw_aff_zero(space));
523 /* Construct a pet_expr representing the index expression "expr"
524 * Return NULL on error.
526 * If "expr" is a reference to an enum constant, then return
527 * an integer expression instead, representing the value of the enum constant.
529 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
531 switch (expr->getStmtClass()) {
532 case Stmt::ImplicitCastExprClass:
533 return extract_index_expr(cast<ImplicitCastExpr>(expr));
534 case Stmt::DeclRefExprClass:
535 return extract_index_expr(cast<DeclRefExpr>(expr));
536 case Stmt::ArraySubscriptExprClass:
537 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
538 case Stmt::IntegerLiteralClass:
539 return extract_expr(cast<IntegerLiteral>(expr));
540 case Stmt::MemberExprClass:
541 return extract_index_expr(cast<MemberExpr>(expr));
542 default:
543 unsupported(expr);
545 return NULL;
548 /* Extract an index expression from the given array subscript expression.
550 * We first extract an index expression from the base.
551 * This will result in an index expression with a range that corresponds
552 * to the earlier indices.
553 * We then extract the current index and let
554 * pet_expr_access_subscript combine the two.
556 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
558 Expr *base = expr->getBase();
559 Expr *idx = expr->getIdx();
560 pet_expr *index;
561 pet_expr *base_expr;
563 base_expr = extract_index_expr(base);
564 index = extract_expr(idx);
566 base_expr = pet_expr_access_subscript(base_expr, index);
568 return base_expr;
571 /* Extract an index expression from a member expression.
573 * If the base access (to the structure containing the member)
574 * is of the form
576 * A[..]
578 * and the member is called "f", then the member access is of
579 * the form
581 * A_f[A[..] -> f[]]
583 * If the member access is to an anonymous struct, then simply return
585 * A[..]
587 * If the member access in the source code is of the form
589 * A->f
591 * then it is treated as
593 * A[0].f
595 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
597 Expr *base = expr->getBase();
598 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
599 pet_expr *base_index;
600 isl_id *id;
602 base_index = extract_index_expr(base);
604 if (expr->isArrow()) {
605 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
606 base_index = pet_expr_access_subscript(base_index, index);
609 if (field->isAnonymousStructOrUnion())
610 return base_index;
612 id = create_decl_id(ctx, field);
614 return pet_expr_access_member(base_index, id);
617 /* Mark the given access pet_expr as a write.
619 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
621 access = pet_expr_access_set_write(access, 1);
622 access = pet_expr_access_set_read(access, 0);
624 return access;
627 /* Construct a pet_expr representing a unary operator expression.
629 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
631 int type_size;
632 pet_expr *arg;
633 enum pet_op_type op;
635 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
636 if (op == pet_op_last) {
637 unsupported(expr);
638 return NULL;
641 arg = extract_expr(expr->getSubExpr());
643 if (expr->isIncrementDecrementOp() &&
644 pet_expr_get_type(arg) == pet_expr_access) {
645 arg = mark_write(arg);
646 arg = pet_expr_access_set_read(arg, 1);
649 type_size = get_type_size(expr->getType(), ast_context);
650 return pet_expr_new_unary(type_size, op, arg);
653 /* Construct a pet_expr representing a binary operator expression.
655 * If the top level operator is an assignment and the LHS is an access,
656 * then we mark that access as a write. If the operator is a compound
657 * assignment, the access is marked as both a read and a write.
659 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
661 int type_size;
662 pet_expr *lhs, *rhs;
663 enum pet_op_type op;
665 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
666 if (op == pet_op_last) {
667 unsupported(expr);
668 return NULL;
671 lhs = extract_expr(expr->getLHS());
672 rhs = extract_expr(expr->getRHS());
674 if (expr->isAssignmentOp() &&
675 pet_expr_get_type(lhs) == pet_expr_access) {
676 lhs = mark_write(lhs);
677 if (expr->isCompoundAssignmentOp())
678 lhs = pet_expr_access_set_read(lhs, 1);
681 type_size = get_type_size(expr->getType(), ast_context);
682 return pet_expr_new_binary(type_size, op, lhs, rhs);
685 /* Construct a pet_tree for a (single) variable declaration.
687 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
689 Decl *decl;
690 VarDecl *vd;
691 pet_expr *lhs, *rhs;
692 pet_tree *tree;
694 if (!stmt->isSingleDecl()) {
695 unsupported(stmt);
696 return NULL;
699 decl = stmt->getSingleDecl();
700 vd = cast<VarDecl>(decl);
702 lhs = extract_access_expr(vd);
703 lhs = mark_write(lhs);
704 if (!vd->getInit())
705 tree = pet_tree_new_decl(lhs);
706 else {
707 rhs = extract_expr(vd->getInit());
708 tree = pet_tree_new_decl_init(lhs, rhs);
711 return tree;
714 /* Construct a pet_expr representing a conditional operation.
716 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
718 pet_expr *cond, *lhs, *rhs;
719 isl_pw_aff *pa;
721 cond = extract_expr(expr->getCond());
722 lhs = extract_expr(expr->getTrueExpr());
723 rhs = extract_expr(expr->getFalseExpr());
725 return pet_expr_new_ternary(cond, lhs, rhs);
728 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
730 return extract_expr(expr->getSubExpr());
733 /* Construct a pet_expr representing a floating point value.
735 * If the floating point literal does not appear in a macro,
736 * then we use the original representation in the source code
737 * as the string representation. Otherwise, we use the pretty
738 * printer to produce a string representation.
740 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
742 double d;
743 string s;
744 const LangOptions &LO = PP.getLangOpts();
745 SourceLocation loc = expr->getLocation();
747 if (!loc.isMacroID()) {
748 SourceManager &SM = PP.getSourceManager();
749 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
750 s = string(SM.getCharacterData(loc), len);
751 } else {
752 llvm::raw_string_ostream S(s);
753 expr->printPretty(S, 0, PrintingPolicy(LO));
754 S.str();
756 d = expr->getValueAsApproximateDouble();
757 return pet_expr_new_double(ctx, d, s.c_str());
760 /* Convert the index expression "index" into an access pet_expr of type "qt".
762 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
763 __isl_take pet_expr *index)
765 int depth;
766 int type_size;
768 depth = extract_depth(index);
769 type_size = get_type_size(qt, ast_context);
771 index = pet_expr_set_type_size(index, type_size);
772 index = pet_expr_access_set_depth(index, depth);
774 return index;
777 /* Extract an index expression from "expr" and then convert it into
778 * an access pet_expr.
780 * If "expr" is a reference to an enum constant, then return
781 * an integer expression instead, representing the value of the enum constant.
783 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
785 pet_expr *index;
787 index = extract_index_expr(expr);
789 if (pet_expr_get_type(index) == pet_expr_int)
790 return index;
792 return extract_access_expr(expr->getType(), index);
795 /* Extract an index expression from "decl" and then convert it into
796 * an access pet_expr.
798 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
800 return extract_access_expr(decl->getType(), extract_index_expr(decl));
803 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
805 return extract_expr(expr->getSubExpr());
808 /* Extract an assume statement from the argument "expr"
809 * of a __pencil_assume statement.
811 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
813 return pet_expr_new_unary(0, pet_op_assume, extract_expr(expr));
816 /* Construct a pet_expr corresponding to the function call argument "expr".
817 * The argument appears in position "pos" of a call to function "fd".
819 * If we are passing along a pointer to an array element
820 * or an entire row or even higher dimensional slice of an array,
821 * then the function being called may write into the array.
823 * We assume here that if the function is declared to take a pointer
824 * to a const type, then the function will perform a read
825 * and that otherwise, it will perform a write.
826 * We only perform this check if "detect_writes" is set.
828 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
829 Expr *expr, bool detect_writes)
831 pet_expr *res;
832 int is_addr = 0, is_partial = 0;
833 Stmt::StmtClass sc;
835 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
836 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
837 expr = ice->getSubExpr();
839 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
840 UnaryOperator *op = cast<UnaryOperator>(expr);
841 if (op->getOpcode() == UO_AddrOf) {
842 is_addr = 1;
843 expr = op->getSubExpr();
846 res = extract_expr(expr);
847 if (!res)
848 return NULL;
849 sc = expr->getStmtClass();
850 if ((sc == Stmt::ArraySubscriptExprClass ||
851 sc == Stmt::DeclRefExprClass ||
852 sc == Stmt::MemberExprClass) &&
853 array_depth(expr->getType().getTypePtr()) > 0)
854 is_partial = 1;
855 if (detect_writes && (is_addr || is_partial) &&
856 pet_expr_get_type(res) == pet_expr_access) {
857 ParmVarDecl *parm;
858 if (!fd->hasPrototype()) {
859 report_prototype_required(expr);
860 return pet_expr_free(res);
862 parm = fd->getParamDecl(pos);
863 if (!const_base(parm->getType()))
864 res = mark_write(res);
867 if (is_addr)
868 res = pet_expr_new_unary(0, pet_op_address_of, res);
869 return res;
872 /* Find the first FunctionDecl with the given name.
873 * "call" is the corresponding call expression and is only used
874 * for reporting errors.
876 * Return NULL on error.
878 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
880 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
881 DeclContext::decl_iterator begin = tu->decls_begin();
882 DeclContext::decl_iterator end = tu->decls_end();
883 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
884 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
885 if (!fd)
886 continue;
887 if (fd->getName().str().compare(name) != 0)
888 continue;
889 if (fd->hasBody())
890 return fd;
891 report_missing_summary_function_body(call);
892 return NULL;
894 report_missing_summary_function(call);
895 return NULL;
898 /* Return the FunctionDecl for the summary function associated to the
899 * function called by "call".
901 * In particular, search for an annotate attribute formatted as
902 * "pencil_access(name)", where "name" is the name of the summary function.
904 * If no summary function was specified, then return the FunctionDecl
905 * that is actually being called.
907 * Return NULL on error.
909 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
911 FunctionDecl *decl = call->getDirectCallee();
912 if (!decl)
913 return NULL;
915 specific_attr_iterator<AnnotateAttr> begin, end, i;
916 begin = decl->specific_attr_begin<AnnotateAttr>();
917 end = decl->specific_attr_end<AnnotateAttr>();
918 for (i = begin; i != end; ++i) {
919 string attr = (*i)->getAnnotation().str();
921 const char prefix[] = "pencil_access(";
922 size_t start = attr.find(prefix);
923 if (start == string::npos)
924 continue;
925 start += strlen(prefix);
926 string name = attr.substr(start, attr.find(')') - start);
928 return find_decl_from_name(call, name);
931 return decl;
934 /* Construct a pet_expr representing a function call.
936 * In the special case of a "call" to __pencil_assume,
937 * construct an assume expression instead.
939 * In the case of a "call" to __pencil_kill, the arguments
940 * are neither read nor written (only killed), so there
941 * is no need to check for writes to these arguments.
943 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
945 pet_expr *res = NULL;
946 FunctionDecl *fd;
947 string name;
948 unsigned n_arg;
949 bool is_kill;
951 fd = expr->getDirectCallee();
952 if (!fd) {
953 unsupported(expr);
954 return NULL;
957 name = fd->getDeclName().getAsString();
958 n_arg = expr->getNumArgs();
960 if (n_arg == 1 && name == "__pencil_assume")
961 return extract_assume(expr->getArg(0));
962 is_kill = name == "__pencil_kill";
964 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
965 if (!res)
966 return NULL;
968 for (int i = 0; i < n_arg; ++i) {
969 Expr *arg = expr->getArg(i);
970 res = pet_expr_set_arg(res, i,
971 PetScan::extract_argument(fd, i, arg, !is_kill));
974 fd = get_summary_function(expr);
975 if (!fd)
976 return pet_expr_free(res);
978 res = set_summary(res, fd);
980 return res;
983 /* Construct a pet_expr representing a (C style) cast.
985 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
987 pet_expr *arg;
988 QualType type;
990 arg = extract_expr(expr->getSubExpr());
991 if (!arg)
992 return NULL;
994 type = expr->getTypeAsWritten();
995 return pet_expr_new_cast(type.getAsString().c_str(), arg);
998 /* Construct a pet_expr representing an integer.
1000 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1002 return pet_expr_new_int(extract_int(expr));
1005 /* Construct a pet_expr representing the integer enum constant "ecd".
1007 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
1009 isl_val *v;
1010 const llvm::APSInt &init = ecd->getInitVal();
1011 v = ::extract_int(ctx, init.isSigned(), init);
1012 return pet_expr_new_int(v);
1015 /* Try and construct a pet_expr representing "expr".
1017 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1019 switch (expr->getStmtClass()) {
1020 case Stmt::UnaryOperatorClass:
1021 return extract_expr(cast<UnaryOperator>(expr));
1022 case Stmt::CompoundAssignOperatorClass:
1023 case Stmt::BinaryOperatorClass:
1024 return extract_expr(cast<BinaryOperator>(expr));
1025 case Stmt::ImplicitCastExprClass:
1026 return extract_expr(cast<ImplicitCastExpr>(expr));
1027 case Stmt::ArraySubscriptExprClass:
1028 case Stmt::DeclRefExprClass:
1029 case Stmt::MemberExprClass:
1030 return extract_access_expr(expr);
1031 case Stmt::IntegerLiteralClass:
1032 return extract_expr(cast<IntegerLiteral>(expr));
1033 case Stmt::FloatingLiteralClass:
1034 return extract_expr(cast<FloatingLiteral>(expr));
1035 case Stmt::ParenExprClass:
1036 return extract_expr(cast<ParenExpr>(expr));
1037 case Stmt::ConditionalOperatorClass:
1038 return extract_expr(cast<ConditionalOperator>(expr));
1039 case Stmt::CallExprClass:
1040 return extract_expr(cast<CallExpr>(expr));
1041 case Stmt::CStyleCastExprClass:
1042 return extract_expr(cast<CStyleCastExpr>(expr));
1043 default:
1044 unsupported(expr);
1046 return NULL;
1049 /* Check if the given initialization statement is an assignment.
1050 * If so, return that assignment. Otherwise return NULL.
1052 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1054 BinaryOperator *ass;
1056 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1057 return NULL;
1059 ass = cast<BinaryOperator>(init);
1060 if (ass->getOpcode() != BO_Assign)
1061 return NULL;
1063 return ass;
1066 /* Check if the given initialization statement is a declaration
1067 * of a single variable.
1068 * If so, return that declaration. Otherwise return NULL.
1070 Decl *PetScan::initialization_declaration(Stmt *init)
1072 DeclStmt *decl;
1074 if (init->getStmtClass() != Stmt::DeclStmtClass)
1075 return NULL;
1077 decl = cast<DeclStmt>(init);
1079 if (!decl->isSingleDecl())
1080 return NULL;
1082 return decl->getSingleDecl();
1085 /* Given the assignment operator in the initialization of a for loop,
1086 * extract the induction variable, i.e., the (integer)variable being
1087 * assigned.
1089 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1091 Expr *lhs;
1092 DeclRefExpr *ref;
1093 ValueDecl *decl;
1094 const Type *type;
1096 lhs = init->getLHS();
1097 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1098 unsupported(init);
1099 return NULL;
1102 ref = cast<DeclRefExpr>(lhs);
1103 decl = ref->getDecl();
1104 type = decl->getType().getTypePtr();
1106 if (!type->isIntegerType()) {
1107 unsupported(lhs);
1108 return NULL;
1111 return decl;
1114 /* Given the initialization statement of a for loop and the single
1115 * declaration in this initialization statement,
1116 * extract the induction variable, i.e., the (integer) variable being
1117 * declared.
1119 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1121 VarDecl *vd;
1123 vd = cast<VarDecl>(decl);
1125 const QualType type = vd->getType();
1126 if (!type->isIntegerType()) {
1127 unsupported(init);
1128 return NULL;
1131 if (!vd->getInit()) {
1132 unsupported(init);
1133 return NULL;
1136 return vd;
1139 /* Check that op is of the form iv++ or iv--.
1140 * Return a pet_expr representing "1" or "-1" accordingly.
1142 __isl_give pet_expr *PetScan::extract_unary_increment(
1143 clang::UnaryOperator *op, clang::ValueDecl *iv)
1145 Expr *sub;
1146 DeclRefExpr *ref;
1147 isl_val *v;
1149 if (!op->isIncrementDecrementOp()) {
1150 unsupported(op);
1151 return NULL;
1154 sub = op->getSubExpr();
1155 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1156 unsupported(op);
1157 return NULL;
1160 ref = cast<DeclRefExpr>(sub);
1161 if (ref->getDecl() != iv) {
1162 unsupported(op);
1163 return NULL;
1166 if (op->isIncrementOp())
1167 v = isl_val_one(ctx);
1168 else
1169 v = isl_val_negone(ctx);
1171 return pet_expr_new_int(v);
1174 /* Check if op is of the form
1176 * iv = expr
1178 * and return the increment "expr - iv" as a pet_expr.
1180 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1181 clang::ValueDecl *iv)
1183 int type_size;
1184 Expr *lhs;
1185 DeclRefExpr *ref;
1186 pet_expr *expr, *expr_iv;
1188 if (op->getOpcode() != BO_Assign) {
1189 unsupported(op);
1190 return NULL;
1193 lhs = op->getLHS();
1194 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1195 unsupported(op);
1196 return NULL;
1199 ref = cast<DeclRefExpr>(lhs);
1200 if (ref->getDecl() != iv) {
1201 unsupported(op);
1202 return NULL;
1205 expr = extract_expr(op->getRHS());
1206 expr_iv = extract_expr(lhs);
1208 type_size = get_type_size(iv->getType(), ast_context);
1209 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1212 /* Check that op is of the form iv += cst or iv -= cst
1213 * and return a pet_expr corresponding to cst or -cst accordingly.
1215 __isl_give pet_expr *PetScan::extract_compound_increment(
1216 CompoundAssignOperator *op, clang::ValueDecl *iv)
1218 Expr *lhs;
1219 DeclRefExpr *ref;
1220 bool neg = false;
1221 pet_expr *expr;
1222 BinaryOperatorKind opcode;
1224 opcode = op->getOpcode();
1225 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1226 unsupported(op);
1227 return NULL;
1229 if (opcode == BO_SubAssign)
1230 neg = true;
1232 lhs = op->getLHS();
1233 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1234 unsupported(op);
1235 return NULL;
1238 ref = cast<DeclRefExpr>(lhs);
1239 if (ref->getDecl() != iv) {
1240 unsupported(op);
1241 return NULL;
1244 expr = extract_expr(op->getRHS());
1245 if (neg) {
1246 int type_size;
1247 type_size = get_type_size(op->getType(), ast_context);
1248 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1251 return expr;
1254 /* Check that the increment of the given for loop increments
1255 * (or decrements) the induction variable "iv" and return
1256 * the increment as a pet_expr if successful.
1258 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1259 ValueDecl *iv)
1261 Stmt *inc = stmt->getInc();
1263 if (!inc) {
1264 report_missing_increment(stmt);
1265 return NULL;
1268 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1269 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1270 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1271 return extract_compound_increment(
1272 cast<CompoundAssignOperator>(inc), iv);
1273 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1274 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1276 unsupported(inc);
1277 return NULL;
1280 /* Construct a pet_tree for a while loop.
1282 * If we were only able to extract part of the body, then simply
1283 * return that part.
1285 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1287 pet_expr *pe_cond;
1288 pet_tree *tree;
1290 tree = extract(stmt->getBody());
1291 if (partial)
1292 return tree;
1293 pe_cond = extract_expr(stmt->getCond());
1294 tree = pet_tree_new_while(pe_cond, tree);
1296 return tree;
1299 /* Construct a pet_tree for a for statement.
1300 * The for loop is required to be of one of the following forms
1302 * for (i = init; condition; ++i)
1303 * for (i = init; condition; --i)
1304 * for (i = init; condition; i += constant)
1305 * for (i = init; condition; i -= constant)
1307 * We extract a pet_tree for the body and then include it in a pet_tree
1308 * of type pet_tree_for.
1310 * As a special case, we also allow a for loop of the form
1312 * for (;;)
1314 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1316 * If we were only able to extract part of the body, then simply
1317 * return that part.
1319 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1321 BinaryOperator *ass;
1322 Decl *decl;
1323 Stmt *init;
1324 Expr *lhs, *rhs;
1325 ValueDecl *iv;
1326 pet_tree *tree;
1327 struct pet_scop *scop;
1328 int independent;
1329 int declared;
1330 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1332 independent = is_current_stmt_marked_independent();
1334 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1335 tree = extract(stmt->getBody());
1336 if (partial)
1337 return tree;
1338 tree = pet_tree_new_infinite_loop(tree);
1339 return tree;
1342 init = stmt->getInit();
1343 if (!init) {
1344 unsupported(stmt);
1345 return NULL;
1347 if ((ass = initialization_assignment(init)) != NULL) {
1348 iv = extract_induction_variable(ass);
1349 if (!iv)
1350 return NULL;
1351 lhs = ass->getLHS();
1352 rhs = ass->getRHS();
1353 } else if ((decl = initialization_declaration(init)) != NULL) {
1354 VarDecl *var = extract_induction_variable(init, decl);
1355 if (!var)
1356 return NULL;
1357 iv = var;
1358 rhs = var->getInit();
1359 lhs = create_DeclRefExpr(var);
1360 } else {
1361 unsupported(stmt->getInit());
1362 return NULL;
1365 declared = !initialization_assignment(stmt->getInit());
1366 tree = extract(stmt->getBody());
1367 if (partial)
1368 return tree;
1369 pe_iv = extract_access_expr(iv);
1370 pe_iv = mark_write(pe_iv);
1371 pe_init = extract_expr(rhs);
1372 if (!stmt->getCond())
1373 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1374 else
1375 pe_cond = extract_expr(stmt->getCond());
1376 pe_inc = extract_increment(stmt, iv);
1377 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1378 pe_inc, tree);
1379 return tree;
1382 /* Try and construct a pet_tree corresponding to a compound statement.
1384 * "skip_declarations" is set if we should skip initial declarations
1385 * in the children of the compound statements. This then implies
1386 * that this sequence of children should not be treated as a block
1387 * since the initial statements may be skipped.
1389 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1390 bool skip_declarations)
1392 return extract(stmt->children(), !skip_declarations, skip_declarations);
1395 /* Return the file offset of the expansion location of "Loc".
1397 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1399 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1402 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1404 /* Return a SourceLocation for the location after the first semicolon
1405 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1406 * call it and also skip trailing spaces and newline.
1408 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1409 const LangOptions &LO)
1411 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1414 #else
1416 /* Return a SourceLocation for the location after the first semicolon
1417 * after "loc". If Lexer::findLocationAfterToken is not available,
1418 * we look in the underlying character data for the first semicolon.
1420 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1421 const LangOptions &LO)
1423 const char *semi;
1424 const char *s = SM.getCharacterData(loc);
1426 semi = strchr(s, ';');
1427 if (!semi)
1428 return SourceLocation();
1429 return loc.getFileLocWithOffset(semi + 1 - s);
1432 #endif
1434 /* If the token at "loc" is the first token on the line, then return
1435 * a location referring to the start of the line and set *indent
1436 * to the indentation of "loc"
1437 * Otherwise, return "loc" and set *indent to "".
1439 * This function is used to extend a scop to the start of the line
1440 * if the first token of the scop is also the first token on the line.
1442 * We look for the first token on the line. If its location is equal to "loc",
1443 * then the latter is the location of the first token on the line.
1445 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1446 SourceManager &SM, const LangOptions &LO, char **indent)
1448 std::pair<FileID, unsigned> file_offset_pair;
1449 llvm::StringRef file;
1450 const char *pos;
1451 Token tok;
1452 SourceLocation token_loc, line_loc;
1453 int col;
1454 const char *s;
1456 loc = SM.getExpansionLoc(loc);
1457 col = SM.getExpansionColumnNumber(loc);
1458 line_loc = loc.getLocWithOffset(1 - col);
1459 file_offset_pair = SM.getDecomposedLoc(line_loc);
1460 file = SM.getBufferData(file_offset_pair.first, NULL);
1461 pos = file.data() + file_offset_pair.second;
1463 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1464 file.begin(), pos, file.end());
1465 lexer.LexFromRawLexer(tok);
1466 token_loc = tok.getLocation();
1468 s = SM.getCharacterData(line_loc);
1469 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1471 if (token_loc == loc)
1472 return line_loc;
1473 else
1474 return loc;
1477 /* Construct a pet_loc corresponding to the region covered by "range".
1478 * If "skip_semi" is set, then we assume "range" is followed by
1479 * a semicolon and also include this semicolon.
1481 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1482 bool skip_semi)
1484 SourceLocation loc = range.getBegin();
1485 SourceManager &SM = PP.getSourceManager();
1486 const LangOptions &LO = PP.getLangOpts();
1487 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1488 unsigned start, end;
1489 char *indent;
1491 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1492 start = getExpansionOffset(SM, loc);
1493 loc = range.getEnd();
1494 if (skip_semi)
1495 loc = location_after_semi(loc, SM, LO);
1496 else
1497 loc = PP.getLocForEndOfToken(loc);
1498 end = getExpansionOffset(SM, loc);
1500 return pet_loc_alloc(ctx, start, end, line, indent);
1503 /* Convert a top-level pet_expr to an expression pet_tree.
1505 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1506 SourceRange range, bool skip_semi)
1508 pet_loc *loc;
1509 pet_tree *tree;
1511 tree = pet_tree_new_expr(expr);
1512 loc = construct_pet_loc(range, skip_semi);
1513 tree = pet_tree_set_loc(tree, loc);
1515 return tree;
1518 /* Construct a pet_tree for an if statement.
1520 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1522 pet_expr *pe_cond;
1523 pet_tree *tree, *tree_else;
1524 struct pet_scop *scop;
1525 int int_size;
1527 pe_cond = extract_expr(stmt->getCond());
1528 tree = extract(stmt->getThen());
1529 if (stmt->getElse()) {
1530 tree_else = extract(stmt->getElse());
1531 if (options->autodetect) {
1532 if (tree && !tree_else) {
1533 partial = true;
1534 pet_expr_free(pe_cond);
1535 return tree;
1537 if (!tree && tree_else) {
1538 partial = true;
1539 pet_expr_free(pe_cond);
1540 return tree_else;
1543 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1544 } else
1545 tree = pet_tree_new_if(pe_cond, tree);
1546 return tree;
1549 /* Try and construct a pet_tree for a label statement.
1551 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1553 isl_id *label;
1554 pet_tree *tree;
1556 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1558 tree = extract(stmt->getSubStmt());
1559 tree = pet_tree_set_label(tree, label);
1560 return tree;
1563 /* Update the location of "tree" to include the source range of "stmt".
1565 * Actually, we create a new location based on the source range of "stmt" and
1566 * then extend this new location to include the region of the original location.
1567 * This ensures that the line number of the final location refers to "stmt".
1569 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1571 pet_loc *loc, *tree_loc;
1573 tree_loc = pet_tree_get_loc(tree);
1574 loc = construct_pet_loc(stmt->getSourceRange(), false);
1575 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1576 pet_loc_free(tree_loc);
1578 tree = pet_tree_set_loc(tree, loc);
1579 return tree;
1582 /* Try and construct a pet_tree corresponding to "stmt".
1584 * If "stmt" is a compound statement, then "skip_declarations"
1585 * indicates whether we should skip initial declarations in the
1586 * compound statement.
1588 * If the constructed pet_tree is not a (possibly) partial representation
1589 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1590 * In particular, if skip_declarations is set, then we may have skipped
1591 * declarations inside "stmt" and so the pet_scop may not represent
1592 * the entire "stmt".
1593 * Note that this function may be called with "stmt" referring to the entire
1594 * body of the function, including the outer braces. In such cases,
1595 * skip_declarations will be set and the braces will not be taken into
1596 * account in tree->loc.
1598 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
1600 pet_tree *tree;
1602 set_current_stmt(stmt);
1604 if (isa<Expr>(stmt))
1605 return extract(extract_expr(cast<Expr>(stmt)),
1606 stmt->getSourceRange(), true);
1608 switch (stmt->getStmtClass()) {
1609 case Stmt::WhileStmtClass:
1610 tree = extract(cast<WhileStmt>(stmt));
1611 break;
1612 case Stmt::ForStmtClass:
1613 tree = extract_for(cast<ForStmt>(stmt));
1614 break;
1615 case Stmt::IfStmtClass:
1616 tree = extract(cast<IfStmt>(stmt));
1617 break;
1618 case Stmt::CompoundStmtClass:
1619 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
1620 break;
1621 case Stmt::LabelStmtClass:
1622 tree = extract(cast<LabelStmt>(stmt));
1623 break;
1624 case Stmt::ContinueStmtClass:
1625 tree = pet_tree_new_continue(ctx);
1626 break;
1627 case Stmt::BreakStmtClass:
1628 tree = pet_tree_new_break(ctx);
1629 break;
1630 case Stmt::DeclStmtClass:
1631 tree = extract(cast<DeclStmt>(stmt));
1632 break;
1633 default:
1634 report_unsupported_statement_type(stmt);
1635 return NULL;
1638 if (partial || skip_declarations)
1639 return tree;
1641 return update_loc(tree, stmt);
1644 /* Try and construct a pet_tree corresponding to (part of)
1645 * a sequence of statements.
1647 * "block" is set if the sequence represents the children of
1648 * a compound statement.
1649 * "skip_declarations" is set if we should skip initial declarations
1650 * in the sequence of statements.
1652 * If autodetect is set, then we allow the extraction of only a subrange
1653 * of the sequence of statements. However, if there is at least one statement
1654 * for which we could not construct a scop and the final range contains
1655 * either no statements or at least one kill, then we discard the entire
1656 * range.
1658 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
1659 bool skip_declarations)
1661 StmtIterator i;
1662 int j;
1663 bool has_kills = false;
1664 bool partial_range = false;
1665 pet_tree *tree;
1666 set<struct pet_stmt *> kills;
1667 set<struct pet_stmt *>::iterator it;
1669 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
1672 tree = pet_tree_new_block(ctx, block, j);
1674 for (i = stmt_range.first; i != stmt_range.second; ++i) {
1675 Stmt *child = *i;
1676 pet_tree *tree_i;
1678 if (pet_tree_block_n_child(tree) == 0 && skip_declarations &&
1679 child->getStmtClass() == Stmt::DeclStmtClass)
1680 continue;
1682 tree_i = extract(child);
1683 if (pet_tree_block_n_child(tree) != 0 && partial) {
1684 pet_tree_free(tree_i);
1685 break;
1687 if (tree_i && child->getStmtClass() == Stmt::DeclStmtClass &&
1688 block)
1689 has_kills = true;
1690 if (options->autodetect) {
1691 if (tree_i)
1692 tree = pet_tree_block_add_child(tree, tree_i);
1693 else
1694 partial_range = true;
1695 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
1696 partial = true;
1697 } else {
1698 tree = pet_tree_block_add_child(tree, tree_i);
1701 if (partial || !tree)
1702 break;
1705 if (tree && partial_range) {
1706 if (pet_tree_block_n_child(tree) == 0 || has_kills) {
1707 pet_tree_free(tree);
1708 return NULL;
1710 partial = true;
1713 return tree;
1716 /* Is "T" the type of a variable length array with static size?
1718 static bool is_vla_with_static_size(QualType T)
1720 const VariableArrayType *vlatype;
1722 if (!T->isVariableArrayType())
1723 return false;
1724 vlatype = cast<VariableArrayType>(T);
1725 return vlatype->getSizeModifier() == VariableArrayType::Static;
1728 /* Return the type of "decl" as an array.
1730 * In particular, if "decl" is a parameter declaration that
1731 * is a variable length array with a static size, then
1732 * return the original type (i.e., the variable length array).
1733 * Otherwise, return the type of decl.
1735 static QualType get_array_type(ValueDecl *decl)
1737 ParmVarDecl *parm;
1738 QualType T;
1740 parm = dyn_cast<ParmVarDecl>(decl);
1741 if (!parm)
1742 return decl->getType();
1744 T = parm->getOriginalType();
1745 if (!is_vla_with_static_size(T))
1746 return decl->getType();
1747 return T;
1750 extern "C" {
1751 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1752 void *user);
1753 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1754 __isl_keep pet_context *pc, void *user);
1757 /* Construct a pet_expr that holds the sizes of the array accessed
1758 * by "access".
1759 * This function is used as a callback to pet_context_add_parameters,
1760 * which is also passed a pointer to the PetScan object.
1762 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1763 void *user)
1765 PetScan *ps = (PetScan *) user;
1766 isl_id *id;
1767 ValueDecl *decl;
1768 const Type *type;
1770 id = pet_expr_access_get_id(access);
1771 decl = (ValueDecl *) isl_id_get_user(id);
1772 isl_id_free(id);
1773 type = get_array_type(decl).getTypePtr();
1774 return ps->get_array_size(type);
1777 /* Construct and return a pet_array corresponding to the variable
1778 * accessed by "access".
1779 * This function is used as a callback to pet_scop_from_pet_tree,
1780 * which is also passed a pointer to the PetScan object.
1782 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1783 __isl_keep pet_context *pc, void *user)
1785 PetScan *ps = (PetScan *) user;
1786 isl_ctx *ctx;
1787 isl_id *id;
1788 ValueDecl *iv;
1790 ctx = pet_expr_get_ctx(access);
1791 id = pet_expr_access_get_id(access);
1792 iv = (ValueDecl *) isl_id_get_user(id);
1793 isl_id_free(id);
1794 return ps->extract_array(ctx, iv, NULL, pc);
1797 /* Extract a function summary from the body of "fd".
1799 * We extract a scop from the function body in a context with as
1800 * parameters the integer arguments of the function.
1801 * We turn off autodetection (in case it was set) to ensure that
1802 * the entire function body is considered.
1803 * We then collect the accessed array elements and attach them
1804 * to the corresponding array arguments, taking into account
1805 * that the function body may access members of array elements.
1807 * The reason for representing the integer arguments as parameters in
1808 * the context is that if we were to instead start with a context
1809 * with the function arguments as initial dimensions, then we would not
1810 * be able to refer to them from the array extents, without turning
1811 * array extents into maps.
1813 * The result is stored in the summary_cache cache so that we can reuse
1814 * it if this method gets called on the same function again later on.
1816 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
1818 isl_space *space;
1819 isl_set *domain;
1820 pet_context *pc;
1821 pet_tree *tree;
1822 pet_function_summary *summary;
1823 unsigned n;
1824 ScopLoc loc;
1825 int save_autodetect;
1826 struct pet_scop *scop;
1827 int int_size;
1828 isl_union_set *may_read, *may_write, *must_write;
1829 isl_union_map *to_inner;
1831 if (summary_cache.find(fd) != summary_cache.end())
1832 return pet_function_summary_copy(summary_cache[fd]);
1834 space = isl_space_set_alloc(ctx, 0, 0);
1836 n = fd->getNumParams();
1837 summary = pet_function_summary_alloc(ctx, n);
1838 for (int i = 0; i < n; ++i) {
1839 ParmVarDecl *parm = fd->getParamDecl(i);
1840 QualType type = parm->getType();
1841 isl_id *id;
1843 if (!type->isIntegerType())
1844 continue;
1845 id = create_decl_id(ctx, parm);
1846 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
1847 space = isl_space_set_dim_id(space, isl_dim_param, 0,
1848 isl_id_copy(id));
1849 summary = pet_function_summary_set_int(summary, i, id);
1852 save_autodetect = options->autodetect;
1853 options->autodetect = 0;
1854 PetScan body_scan(PP, ast_context, loc, options,
1855 isl_union_map_copy(value_bounds), independent);
1857 tree = body_scan.extract(fd->getBody(), false);
1859 domain = isl_set_universe(space);
1860 pc = pet_context_alloc(domain);
1861 pc = pet_context_add_parameters(pc, tree,
1862 &::get_array_size, &body_scan);
1863 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
1864 scop = pet_scop_from_pet_tree(tree, int_size,
1865 &::extract_array, &body_scan, pc);
1866 scop = scan_arrays(scop, pc);
1867 may_read = isl_union_map_range(pet_scop_collect_may_reads(scop));
1868 may_write = isl_union_map_range(pet_scop_collect_may_writes(scop));
1869 must_write = isl_union_map_range(pet_scop_collect_must_writes(scop));
1870 to_inner = pet_scop_compute_outer_to_inner(scop);
1871 pet_scop_free(scop);
1873 for (int i = 0; i < n; ++i) {
1874 ParmVarDecl *parm = fd->getParamDecl(i);
1875 QualType type = parm->getType();
1876 struct pet_array *array;
1877 isl_space *space;
1878 isl_union_set *data_set;
1879 isl_union_set *may_read_i, *may_write_i, *must_write_i;
1881 if (array_depth(type.getTypePtr()) == 0)
1882 continue;
1884 array = body_scan.extract_array(ctx, parm, NULL, pc);
1885 space = array ? isl_set_get_space(array->extent) : NULL;
1886 pet_array_free(array);
1887 data_set = isl_union_set_from_set(isl_set_universe(space));
1888 data_set = isl_union_set_apply(data_set,
1889 isl_union_map_copy(to_inner));
1890 may_read_i = isl_union_set_intersect(
1891 isl_union_set_copy(may_read),
1892 isl_union_set_copy(data_set));
1893 may_write_i = isl_union_set_intersect(
1894 isl_union_set_copy(may_write),
1895 isl_union_set_copy(data_set));
1896 must_write_i = isl_union_set_intersect(
1897 isl_union_set_copy(must_write), data_set);
1898 summary = pet_function_summary_set_array(summary, i,
1899 may_read_i, may_write_i, must_write_i);
1902 isl_union_set_free(may_read);
1903 isl_union_set_free(may_write);
1904 isl_union_set_free(must_write);
1905 isl_union_map_free(to_inner);
1907 options->autodetect = save_autodetect;
1908 pet_context_free(pc);
1910 summary_cache[fd] = pet_function_summary_copy(summary);
1912 return summary;
1915 /* If "fd" has a function body, then extract a function summary from
1916 * this body and attach it to the call expression "expr".
1918 * Even if a function body is available, "fd" itself may point
1919 * to a declaration without function body. We therefore first
1920 * replace it by the declaration that comes with a body (if any).
1922 * It is not clear why hasBody takes a reference to a const FunctionDecl *.
1923 * It seems that it is possible to directly use the iterators to obtain
1924 * a non-const pointer.
1925 * Since we are not going to use the pointer to modify anything anyway,
1926 * it seems safe to drop the constness. The alternative would be to
1927 * modify a lot of other functions to include const qualifiers.
1929 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
1930 FunctionDecl *fd)
1932 pet_function_summary *summary;
1933 const FunctionDecl *def;
1935 if (!expr)
1936 return NULL;
1937 if (!fd->hasBody(def))
1938 return expr;
1940 fd = const_cast<FunctionDecl *>(def);
1942 summary = get_summary(fd);
1944 expr = pet_expr_call_set_summary(expr, summary);
1946 return expr;
1949 /* Extract a pet_scop from "tree".
1951 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
1952 * then add pet_arrays for all accessed arrays.
1953 * We populate the pet_context with assignments for all parameters used
1954 * inside "tree" or any of the size expressions for the arrays accessed
1955 * by "tree" so that they can be used in affine expressions.
1957 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
1959 int int_size;
1960 isl_set *domain;
1961 pet_context *pc;
1962 pet_scop *scop;
1964 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
1966 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
1967 pc = pet_context_alloc(domain);
1968 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
1969 scop = pet_scop_from_pet_tree(tree, int_size,
1970 &::extract_array, this, pc);
1971 scop = scan_arrays(scop, pc);
1972 pet_context_free(pc);
1974 return scop;
1977 /* Check if the scop marked by the user is exactly this Stmt
1978 * or part of this Stmt.
1979 * If so, return a pet_scop corresponding to the marked region.
1980 * Otherwise, return NULL.
1982 struct pet_scop *PetScan::scan(Stmt *stmt)
1984 SourceManager &SM = PP.getSourceManager();
1985 unsigned start_off, end_off;
1987 start_off = getExpansionOffset(SM, stmt->getLocStart());
1988 end_off = getExpansionOffset(SM, stmt->getLocEnd());
1990 if (start_off > loc.end)
1991 return NULL;
1992 if (end_off < loc.start)
1993 return NULL;
1995 if (start_off >= loc.start && end_off <= loc.end)
1996 return extract_scop(extract(stmt));
1998 StmtIterator start;
1999 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
2000 Stmt *child = *start;
2001 if (!child)
2002 continue;
2003 start_off = getExpansionOffset(SM, child->getLocStart());
2004 end_off = getExpansionOffset(SM, child->getLocEnd());
2005 if (start_off < loc.start && end_off >= loc.end)
2006 return scan(child);
2007 if (start_off >= loc.start)
2008 break;
2011 StmtIterator end;
2012 for (end = start; end != stmt->child_end(); ++end) {
2013 Stmt *child = *end;
2014 start_off = SM.getFileOffset(child->getLocStart());
2015 if (start_off >= loc.end)
2016 break;
2019 return extract_scop(extract(StmtRange(start, end), false, false));
2022 /* Set the size of index "pos" of "array" to "size".
2023 * In particular, add a constraint of the form
2025 * i_pos < size
2027 * to array->extent and a constraint of the form
2029 * size >= 0
2031 * to array->context.
2033 * The domain of "size" is assumed to be zero-dimensional.
2035 static struct pet_array *update_size(struct pet_array *array, int pos,
2036 __isl_take isl_pw_aff *size)
2038 isl_set *valid;
2039 isl_set *univ;
2040 isl_set *bound;
2041 isl_space *dim;
2042 isl_aff *aff;
2043 isl_pw_aff *index;
2044 isl_id *id;
2046 if (!array)
2047 goto error;
2049 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2050 array->context = isl_set_intersect(array->context, valid);
2052 dim = isl_set_get_space(array->extent);
2053 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2054 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2055 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2056 index = isl_pw_aff_alloc(univ, aff);
2058 size = isl_pw_aff_add_dims(size, isl_dim_in,
2059 isl_set_dim(array->extent, isl_dim_set));
2060 id = isl_set_get_tuple_id(array->extent);
2061 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2062 bound = isl_pw_aff_lt_set(index, size);
2064 array->extent = isl_set_intersect(array->extent, bound);
2066 if (!array->context || !array->extent)
2067 return pet_array_free(array);
2069 return array;
2070 error:
2071 isl_pw_aff_free(size);
2072 return NULL;
2075 #ifdef HAVE_DECAYEDTYPE
2077 /* If "type" is a decayed type, then set *decayed to true and
2078 * return the original type.
2080 static const Type *undecay(const Type *type, bool *decayed)
2082 *decayed = isa<DecayedType>(type);
2083 if (*decayed)
2084 type = cast<DecayedType>(type)->getOriginalType().getTypePtr();
2085 return type;
2088 #else
2090 /* If "type" is a decayed type, then set *decayed to true and
2091 * return the original type.
2092 * Since this version of clang does not define a DecayedType,
2093 * we cannot obtain the original type even if it had been decayed and
2094 * we set *decayed to false.
2096 static const Type *undecay(const Type *type, bool *decayed)
2098 *decayed = false;
2099 return type;
2102 #endif
2104 /* Figure out the size of the array at position "pos" and all
2105 * subsequent positions from "type" and update the corresponding
2106 * argument of "expr" accordingly.
2108 * The initial type (when pos is zero) may be a pointer type decayed
2109 * from an array type, if this initial type is the type of a function
2110 * argument. This only happens if the original array type has
2111 * a constant size in the outer dimension as otherwise we get
2112 * a VariableArrayType. Try and obtain this original type (if available) and
2113 * take the outer array size into account if it was marked static.
2115 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2116 const Type *type, int pos)
2118 const ArrayType *atype;
2119 pet_expr *size;
2120 bool decayed = false;
2122 if (!expr)
2123 return NULL;
2125 if (pos == 0)
2126 type = undecay(type, &decayed);
2128 if (type->isPointerType()) {
2129 type = type->getPointeeType().getTypePtr();
2130 return set_upper_bounds(expr, type, pos + 1);
2132 if (!type->isArrayType())
2133 return expr;
2135 type = type->getCanonicalTypeInternal().getTypePtr();
2136 atype = cast<ArrayType>(type);
2138 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2139 type = atype->getElementType().getTypePtr();
2140 return set_upper_bounds(expr, type, pos + 1);
2143 if (type->isConstantArrayType()) {
2144 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2145 size = extract_expr(ca->getSize());
2146 expr = pet_expr_set_arg(expr, pos, size);
2147 } else if (type->isVariableArrayType()) {
2148 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2149 size = extract_expr(vla->getSizeExpr());
2150 expr = pet_expr_set_arg(expr, pos, size);
2153 type = atype->getElementType().getTypePtr();
2155 return set_upper_bounds(expr, type, pos + 1);
2158 /* Construct a pet_expr that holds the sizes of an array of the given type.
2159 * The returned expression is a call expression with as arguments
2160 * the sizes in each dimension. If we are unable to derive the size
2161 * in a given dimension, then the corresponding argument is set to infinity.
2162 * In fact, we initialize all arguments to infinity and then update
2163 * them if we are able to figure out the size.
2165 * The result is stored in the type_size cache so that we can reuse
2166 * it if this method gets called on the same type again later on.
2168 __isl_give pet_expr *PetScan::get_array_size(const Type *type)
2170 int depth;
2171 pet_expr *expr, *inf;
2173 if (type_size.find(type) != type_size.end())
2174 return pet_expr_copy(type_size[type]);
2176 depth = array_depth(type);
2177 inf = pet_expr_new_int(isl_val_infty(ctx));
2178 expr = pet_expr_new_call(ctx, "bounds", depth);
2179 for (int i = 0; i < depth; ++i)
2180 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2181 pet_expr_free(inf);
2183 expr = set_upper_bounds(expr, type, 0);
2184 type_size[type] = pet_expr_copy(expr);
2186 return expr;
2189 /* Does "expr" represent the "integer" infinity?
2191 static int is_infty(__isl_keep pet_expr *expr)
2193 isl_val *v;
2194 int res;
2196 if (pet_expr_get_type(expr) != pet_expr_int)
2197 return 0;
2198 v = pet_expr_int_get_val(expr);
2199 res = isl_val_is_infty(v);
2200 isl_val_free(v);
2202 return res;
2205 /* Figure out the dimensions of an array "array" based on its type
2206 * "type" and update "array" accordingly.
2208 * We first construct a pet_expr that holds the sizes of the array
2209 * in each dimension. The resulting expression may containing
2210 * infinity values for dimension where we are unable to derive
2211 * a size expression.
2213 * The arguments of the size expression that have a value different from
2214 * infinity are then converted to an affine expression
2215 * within the context "pc" and incorporated into the size of "array".
2216 * If we are unable to convert a size expression to an affine expression or
2217 * if the size is not a (symbolic) constant,
2218 * then we leave the corresponding size of "array" untouched.
2220 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2221 const Type *type, __isl_keep pet_context *pc)
2223 int n;
2224 pet_expr *expr;
2226 if (!array)
2227 return NULL;
2229 expr = get_array_size(type);
2231 n = pet_expr_get_n_arg(expr);
2232 for (int i = 0; i < n; ++i) {
2233 pet_expr *arg;
2234 isl_pw_aff *size;
2236 arg = pet_expr_get_arg(expr, i);
2237 if (!is_infty(arg)) {
2238 int dim;
2240 size = pet_expr_extract_affine(arg, pc);
2241 dim = isl_pw_aff_dim(size, isl_dim_in);
2242 if (!size)
2243 array = pet_array_free(array);
2244 else if (isl_pw_aff_involves_nan(size) ||
2245 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2246 isl_pw_aff_free(size);
2247 else {
2248 size = isl_pw_aff_drop_dims(size,
2249 isl_dim_in, 0, dim);
2250 array = update_size(array, i, size);
2253 pet_expr_free(arg);
2255 pet_expr_free(expr);
2257 return array;
2260 /* Does "decl" have definition that we can keep track of in a pet_type?
2262 static bool has_printable_definition(RecordDecl *decl)
2264 if (!decl->getDeclName())
2265 return false;
2266 return decl->getLexicalDeclContext() == decl->getDeclContext();
2269 /* Construct and return a pet_array corresponding to the variable "decl".
2270 * In particular, initialize array->extent to
2272 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2274 * and then call set_upper_bounds to set the upper bounds on the indices
2275 * based on the type of the variable. The upper bounds are converted
2276 * to affine expressions within the context "pc".
2278 * If the base type is that of a record with a top-level definition and
2279 * if "types" is not null, then the RecordDecl corresponding to the type
2280 * is added to "types".
2282 * If the base type is that of a record with no top-level definition,
2283 * then we replace it by "<subfield>".
2285 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
2286 lex_recorddecl_set *types, __isl_keep pet_context *pc)
2288 struct pet_array *array;
2289 QualType qt = get_array_type(decl);
2290 const Type *type = qt.getTypePtr();
2291 int depth = array_depth(type);
2292 QualType base = pet_clang_base_type(qt);
2293 string name;
2294 isl_id *id;
2295 isl_space *dim;
2297 array = isl_calloc_type(ctx, struct pet_array);
2298 if (!array)
2299 return NULL;
2301 id = create_decl_id(ctx, decl);
2302 dim = isl_space_set_alloc(ctx, 0, depth);
2303 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
2305 array->extent = isl_set_nat_universe(dim);
2307 dim = isl_space_params_alloc(ctx, 0);
2308 array->context = isl_set_universe(dim);
2310 array = set_upper_bounds(array, type, pc);
2311 if (!array)
2312 return NULL;
2314 name = base.getAsString();
2316 if (types && base->isRecordType()) {
2317 RecordDecl *decl = pet_clang_record_decl(base);
2318 if (has_printable_definition(decl))
2319 types->insert(decl);
2320 else
2321 name = "<subfield>";
2324 array->element_type = strdup(name.c_str());
2325 array->element_is_record = base->isRecordType();
2326 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
2328 return array;
2331 /* Construct and return a pet_array corresponding to the sequence
2332 * of declarations "decls".
2333 * The upper bounds of the array are converted to affine expressions
2334 * within the context "pc".
2335 * If the sequence contains a single declaration, then it corresponds
2336 * to a simple array access. Otherwise, it corresponds to a member access,
2337 * with the declaration for the substructure following that of the containing
2338 * structure in the sequence of declarations.
2339 * We start with the outermost substructure and then combine it with
2340 * information from the inner structures.
2342 * Additionally, keep track of all required types in "types".
2344 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
2345 vector<ValueDecl *> decls, lex_recorddecl_set *types,
2346 __isl_keep pet_context *pc)
2348 struct pet_array *array;
2349 vector<ValueDecl *>::iterator it;
2351 it = decls.begin();
2353 array = extract_array(ctx, *it, types, pc);
2355 for (++it; it != decls.end(); ++it) {
2356 struct pet_array *parent;
2357 const char *base_name, *field_name;
2358 char *product_name;
2360 parent = array;
2361 array = extract_array(ctx, *it, types, pc);
2362 if (!array)
2363 return pet_array_free(parent);
2365 base_name = isl_set_get_tuple_name(parent->extent);
2366 field_name = isl_set_get_tuple_name(array->extent);
2367 product_name = pet_array_member_access_name(ctx,
2368 base_name, field_name);
2370 array->extent = isl_set_product(isl_set_copy(parent->extent),
2371 array->extent);
2372 if (product_name)
2373 array->extent = isl_set_set_tuple_name(array->extent,
2374 product_name);
2375 array->context = isl_set_intersect(array->context,
2376 isl_set_copy(parent->context));
2378 pet_array_free(parent);
2379 free(product_name);
2381 if (!array->extent || !array->context || !product_name)
2382 return pet_array_free(array);
2385 return array;
2388 /* Add a pet_type corresponding to "decl" to "scop, provided
2389 * it is a member of "types" and it has not been added before
2390 * (i.e., it is not a member of "types_done".
2392 * Since we want the user to be able to print the types
2393 * in the order in which they appear in the scop, we need to
2394 * make sure that types of fields in a structure appear before
2395 * that structure. We therefore call ourselves recursively
2396 * on the types of all record subfields.
2398 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2399 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
2400 lex_recorddecl_set &types_done)
2402 string s;
2403 llvm::raw_string_ostream S(s);
2404 RecordDecl::field_iterator it;
2406 if (types.find(decl) == types.end())
2407 return scop;
2408 if (types_done.find(decl) != types_done.end())
2409 return scop;
2411 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
2412 RecordDecl *record;
2413 QualType type = it->getType();
2415 if (!type->isRecordType())
2416 continue;
2417 record = pet_clang_record_decl(type);
2418 scop = add_type(ctx, scop, record, PP, types, types_done);
2421 if (strlen(decl->getName().str().c_str()) == 0)
2422 return scop;
2424 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2425 S.str();
2427 scop->types[scop->n_type] = pet_type_alloc(ctx,
2428 decl->getName().str().c_str(), s.c_str());
2429 if (!scop->types[scop->n_type])
2430 return pet_scop_free(scop);
2432 types_done.insert(decl);
2434 scop->n_type++;
2436 return scop;
2439 /* Construct a list of pet_arrays, one for each array (or scalar)
2440 * accessed inside "scop", add this list to "scop" and return the result.
2441 * The upper bounds of the arrays are converted to affine expressions
2442 * within the context "pc".
2444 * The context of "scop" is updated with the intersection of
2445 * the contexts of all arrays, i.e., constraints on the parameters
2446 * that ensure that the arrays have a valid (non-negative) size.
2448 * If the any of the extracted arrays refers to a member access,
2449 * then also add the required types to "scop".
2451 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
2452 __isl_keep pet_context *pc)
2454 int i;
2455 array_desc_set arrays;
2456 array_desc_set::iterator it;
2457 lex_recorddecl_set types;
2458 lex_recorddecl_set types_done;
2459 lex_recorddecl_set::iterator types_it;
2460 int n_array;
2461 struct pet_array **scop_arrays;
2463 if (!scop)
2464 return NULL;
2466 pet_scop_collect_arrays(scop, arrays);
2467 if (arrays.size() == 0)
2468 return scop;
2470 n_array = scop->n_array;
2472 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2473 n_array + arrays.size());
2474 if (!scop_arrays)
2475 goto error;
2476 scop->arrays = scop_arrays;
2478 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
2479 struct pet_array *array;
2480 array = extract_array(ctx, *it, &types, pc);
2481 scop->arrays[n_array + i] = array;
2482 if (!scop->arrays[n_array + i])
2483 goto error;
2484 scop->n_array++;
2485 scop->context = isl_set_intersect(scop->context,
2486 isl_set_copy(array->context));
2487 if (!scop->context)
2488 goto error;
2491 if (types.size() == 0)
2492 return scop;
2494 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
2495 if (!scop->types)
2496 goto error;
2498 for (types_it = types.begin(); types_it != types.end(); ++types_it)
2499 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
2501 return scop;
2502 error:
2503 pet_scop_free(scop);
2504 return NULL;
2507 /* Bound all parameters in scop->context to the possible values
2508 * of the corresponding C variable.
2510 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
2512 int n;
2514 if (!scop)
2515 return NULL;
2517 n = isl_set_dim(scop->context, isl_dim_param);
2518 for (int i = 0; i < n; ++i) {
2519 isl_id *id;
2520 ValueDecl *decl;
2522 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
2523 if (pet_nested_in_id(id)) {
2524 isl_id_free(id);
2525 isl_die(isl_set_get_ctx(scop->context),
2526 isl_error_internal,
2527 "unresolved nested parameter", goto error);
2529 decl = (ValueDecl *) isl_id_get_user(id);
2530 isl_id_free(id);
2532 scop->context = set_parameter_bounds(scop->context, i, decl);
2534 if (!scop->context)
2535 goto error;
2538 return scop;
2539 error:
2540 pet_scop_free(scop);
2541 return NULL;
2544 /* Construct a pet_scop from the given function.
2546 * If the scop was delimited by scop and endscop pragmas, then we override
2547 * the file offsets by those derived from the pragmas.
2549 struct pet_scop *PetScan::scan(FunctionDecl *fd)
2551 pet_scop *scop;
2552 Stmt *stmt;
2554 stmt = fd->getBody();
2556 if (options->autodetect) {
2557 set_current_stmt(stmt);
2558 scop = extract_scop(extract(stmt, true));
2559 } else {
2560 current_line = loc.start_line;
2561 scop = scan(stmt);
2562 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
2564 scop = add_parameter_bounds(scop);
2565 scop = pet_scop_gist(scop, value_bounds);
2567 return scop;
2570 /* Update this->last_line and this->current_line based on the fact
2571 * that we are about to consider "stmt".
2573 void PetScan::set_current_stmt(Stmt *stmt)
2575 SourceLocation loc = stmt->getLocStart();
2576 SourceManager &SM = PP.getSourceManager();
2578 last_line = current_line;
2579 current_line = SM.getExpansionLineNumber(loc);
2582 /* Is the current statement marked by an independent pragma?
2583 * That is, is there an independent pragma on a line between
2584 * the line of the current statement and the line of the previous statement.
2585 * The search is not implemented very efficiently. We currently
2586 * assume that there are only a few independent pragmas, if any.
2588 bool PetScan::is_current_stmt_marked_independent()
2590 for (int i = 0; i < independent.size(); ++i) {
2591 unsigned line = independent[i].line;
2593 if (last_line < line && line < current_line)
2594 return true;
2597 return false;