PetScan::extract_argument: only perform write detection optionally
[pet.git] / scan.cc
blobbc61e545ddc3860454ca64e7717731bf6e06fede
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 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
931 pet_expr *res = NULL;
932 FunctionDecl *fd;
933 string name;
934 unsigned n_arg;
936 fd = expr->getDirectCallee();
937 if (!fd) {
938 unsupported(expr);
939 return NULL;
942 name = fd->getDeclName().getAsString();
943 n_arg = expr->getNumArgs();
945 if (n_arg == 1 && name == "__pencil_assume")
946 return extract_assume(expr->getArg(0));
948 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
949 if (!res)
950 return NULL;
952 for (int i = 0; i < n_arg; ++i) {
953 Expr *arg = expr->getArg(i);
954 res = pet_expr_set_arg(res, i,
955 PetScan::extract_argument(fd, i, arg, 1));
958 fd = get_summary_function(expr);
959 if (!fd)
960 return pet_expr_free(res);
962 res = set_summary(res, fd);
964 return res;
967 /* Construct a pet_expr representing a (C style) cast.
969 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
971 pet_expr *arg;
972 QualType type;
974 arg = extract_expr(expr->getSubExpr());
975 if (!arg)
976 return NULL;
978 type = expr->getTypeAsWritten();
979 return pet_expr_new_cast(type.getAsString().c_str(), arg);
982 /* Construct a pet_expr representing an integer.
984 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
986 return pet_expr_new_int(extract_int(expr));
989 /* Construct a pet_expr representing the integer enum constant "ecd".
991 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
993 isl_val *v;
994 const llvm::APSInt &init = ecd->getInitVal();
995 v = ::extract_int(ctx, init.isSigned(), init);
996 return pet_expr_new_int(v);
999 /* Try and construct a pet_expr representing "expr".
1001 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1003 switch (expr->getStmtClass()) {
1004 case Stmt::UnaryOperatorClass:
1005 return extract_expr(cast<UnaryOperator>(expr));
1006 case Stmt::CompoundAssignOperatorClass:
1007 case Stmt::BinaryOperatorClass:
1008 return extract_expr(cast<BinaryOperator>(expr));
1009 case Stmt::ImplicitCastExprClass:
1010 return extract_expr(cast<ImplicitCastExpr>(expr));
1011 case Stmt::ArraySubscriptExprClass:
1012 case Stmt::DeclRefExprClass:
1013 case Stmt::MemberExprClass:
1014 return extract_access_expr(expr);
1015 case Stmt::IntegerLiteralClass:
1016 return extract_expr(cast<IntegerLiteral>(expr));
1017 case Stmt::FloatingLiteralClass:
1018 return extract_expr(cast<FloatingLiteral>(expr));
1019 case Stmt::ParenExprClass:
1020 return extract_expr(cast<ParenExpr>(expr));
1021 case Stmt::ConditionalOperatorClass:
1022 return extract_expr(cast<ConditionalOperator>(expr));
1023 case Stmt::CallExprClass:
1024 return extract_expr(cast<CallExpr>(expr));
1025 case Stmt::CStyleCastExprClass:
1026 return extract_expr(cast<CStyleCastExpr>(expr));
1027 default:
1028 unsupported(expr);
1030 return NULL;
1033 /* Check if the given initialization statement is an assignment.
1034 * If so, return that assignment. Otherwise return NULL.
1036 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1038 BinaryOperator *ass;
1040 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1041 return NULL;
1043 ass = cast<BinaryOperator>(init);
1044 if (ass->getOpcode() != BO_Assign)
1045 return NULL;
1047 return ass;
1050 /* Check if the given initialization statement is a declaration
1051 * of a single variable.
1052 * If so, return that declaration. Otherwise return NULL.
1054 Decl *PetScan::initialization_declaration(Stmt *init)
1056 DeclStmt *decl;
1058 if (init->getStmtClass() != Stmt::DeclStmtClass)
1059 return NULL;
1061 decl = cast<DeclStmt>(init);
1063 if (!decl->isSingleDecl())
1064 return NULL;
1066 return decl->getSingleDecl();
1069 /* Given the assignment operator in the initialization of a for loop,
1070 * extract the induction variable, i.e., the (integer)variable being
1071 * assigned.
1073 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1075 Expr *lhs;
1076 DeclRefExpr *ref;
1077 ValueDecl *decl;
1078 const Type *type;
1080 lhs = init->getLHS();
1081 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1082 unsupported(init);
1083 return NULL;
1086 ref = cast<DeclRefExpr>(lhs);
1087 decl = ref->getDecl();
1088 type = decl->getType().getTypePtr();
1090 if (!type->isIntegerType()) {
1091 unsupported(lhs);
1092 return NULL;
1095 return decl;
1098 /* Given the initialization statement of a for loop and the single
1099 * declaration in this initialization statement,
1100 * extract the induction variable, i.e., the (integer) variable being
1101 * declared.
1103 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1105 VarDecl *vd;
1107 vd = cast<VarDecl>(decl);
1109 const QualType type = vd->getType();
1110 if (!type->isIntegerType()) {
1111 unsupported(init);
1112 return NULL;
1115 if (!vd->getInit()) {
1116 unsupported(init);
1117 return NULL;
1120 return vd;
1123 /* Check that op is of the form iv++ or iv--.
1124 * Return a pet_expr representing "1" or "-1" accordingly.
1126 __isl_give pet_expr *PetScan::extract_unary_increment(
1127 clang::UnaryOperator *op, clang::ValueDecl *iv)
1129 Expr *sub;
1130 DeclRefExpr *ref;
1131 isl_val *v;
1133 if (!op->isIncrementDecrementOp()) {
1134 unsupported(op);
1135 return NULL;
1138 sub = op->getSubExpr();
1139 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1140 unsupported(op);
1141 return NULL;
1144 ref = cast<DeclRefExpr>(sub);
1145 if (ref->getDecl() != iv) {
1146 unsupported(op);
1147 return NULL;
1150 if (op->isIncrementOp())
1151 v = isl_val_one(ctx);
1152 else
1153 v = isl_val_negone(ctx);
1155 return pet_expr_new_int(v);
1158 /* Check if op is of the form
1160 * iv = expr
1162 * and return the increment "expr - iv" as a pet_expr.
1164 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1165 clang::ValueDecl *iv)
1167 int type_size;
1168 Expr *lhs;
1169 DeclRefExpr *ref;
1170 pet_expr *expr, *expr_iv;
1172 if (op->getOpcode() != BO_Assign) {
1173 unsupported(op);
1174 return NULL;
1177 lhs = op->getLHS();
1178 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1179 unsupported(op);
1180 return NULL;
1183 ref = cast<DeclRefExpr>(lhs);
1184 if (ref->getDecl() != iv) {
1185 unsupported(op);
1186 return NULL;
1189 expr = extract_expr(op->getRHS());
1190 expr_iv = extract_expr(lhs);
1192 type_size = get_type_size(iv->getType(), ast_context);
1193 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1196 /* Check that op is of the form iv += cst or iv -= cst
1197 * and return a pet_expr corresponding to cst or -cst accordingly.
1199 __isl_give pet_expr *PetScan::extract_compound_increment(
1200 CompoundAssignOperator *op, clang::ValueDecl *iv)
1202 Expr *lhs;
1203 DeclRefExpr *ref;
1204 bool neg = false;
1205 pet_expr *expr;
1206 BinaryOperatorKind opcode;
1208 opcode = op->getOpcode();
1209 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1210 unsupported(op);
1211 return NULL;
1213 if (opcode == BO_SubAssign)
1214 neg = true;
1216 lhs = op->getLHS();
1217 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1218 unsupported(op);
1219 return NULL;
1222 ref = cast<DeclRefExpr>(lhs);
1223 if (ref->getDecl() != iv) {
1224 unsupported(op);
1225 return NULL;
1228 expr = extract_expr(op->getRHS());
1229 if (neg) {
1230 int type_size;
1231 type_size = get_type_size(op->getType(), ast_context);
1232 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1235 return expr;
1238 /* Check that the increment of the given for loop increments
1239 * (or decrements) the induction variable "iv" and return
1240 * the increment as a pet_expr if successful.
1242 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1243 ValueDecl *iv)
1245 Stmt *inc = stmt->getInc();
1247 if (!inc) {
1248 report_missing_increment(stmt);
1249 return NULL;
1252 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1253 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1254 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1255 return extract_compound_increment(
1256 cast<CompoundAssignOperator>(inc), iv);
1257 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1258 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1260 unsupported(inc);
1261 return NULL;
1264 /* Construct a pet_tree for a while loop.
1266 * If we were only able to extract part of the body, then simply
1267 * return that part.
1269 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1271 pet_expr *pe_cond;
1272 pet_tree *tree;
1274 tree = extract(stmt->getBody());
1275 if (partial)
1276 return tree;
1277 pe_cond = extract_expr(stmt->getCond());
1278 tree = pet_tree_new_while(pe_cond, tree);
1280 return tree;
1283 /* Construct a pet_tree for a for statement.
1284 * The for loop is required to be of one of the following forms
1286 * for (i = init; condition; ++i)
1287 * for (i = init; condition; --i)
1288 * for (i = init; condition; i += constant)
1289 * for (i = init; condition; i -= constant)
1291 * We extract a pet_tree for the body and then include it in a pet_tree
1292 * of type pet_tree_for.
1294 * As a special case, we also allow a for loop of the form
1296 * for (;;)
1298 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1300 * If we were only able to extract part of the body, then simply
1301 * return that part.
1303 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1305 BinaryOperator *ass;
1306 Decl *decl;
1307 Stmt *init;
1308 Expr *lhs, *rhs;
1309 ValueDecl *iv;
1310 pet_tree *tree;
1311 struct pet_scop *scop;
1312 int independent;
1313 int declared;
1314 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1316 independent = is_current_stmt_marked_independent();
1318 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1319 tree = extract(stmt->getBody());
1320 if (partial)
1321 return tree;
1322 tree = pet_tree_new_infinite_loop(tree);
1323 return tree;
1326 init = stmt->getInit();
1327 if (!init) {
1328 unsupported(stmt);
1329 return NULL;
1331 if ((ass = initialization_assignment(init)) != NULL) {
1332 iv = extract_induction_variable(ass);
1333 if (!iv)
1334 return NULL;
1335 lhs = ass->getLHS();
1336 rhs = ass->getRHS();
1337 } else if ((decl = initialization_declaration(init)) != NULL) {
1338 VarDecl *var = extract_induction_variable(init, decl);
1339 if (!var)
1340 return NULL;
1341 iv = var;
1342 rhs = var->getInit();
1343 lhs = create_DeclRefExpr(var);
1344 } else {
1345 unsupported(stmt->getInit());
1346 return NULL;
1349 declared = !initialization_assignment(stmt->getInit());
1350 tree = extract(stmt->getBody());
1351 if (partial)
1352 return tree;
1353 pe_iv = extract_access_expr(iv);
1354 pe_iv = mark_write(pe_iv);
1355 pe_init = extract_expr(rhs);
1356 if (!stmt->getCond())
1357 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1358 else
1359 pe_cond = extract_expr(stmt->getCond());
1360 pe_inc = extract_increment(stmt, iv);
1361 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1362 pe_inc, tree);
1363 return tree;
1366 /* Try and construct a pet_tree corresponding to a compound statement.
1368 * "skip_declarations" is set if we should skip initial declarations
1369 * in the children of the compound statements. This then implies
1370 * that this sequence of children should not be treated as a block
1371 * since the initial statements may be skipped.
1373 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1374 bool skip_declarations)
1376 return extract(stmt->children(), !skip_declarations, skip_declarations);
1379 /* Return the file offset of the expansion location of "Loc".
1381 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1383 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1386 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1388 /* Return a SourceLocation for the location after the first semicolon
1389 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1390 * call it and also skip trailing spaces and newline.
1392 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1393 const LangOptions &LO)
1395 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1398 #else
1400 /* Return a SourceLocation for the location after the first semicolon
1401 * after "loc". If Lexer::findLocationAfterToken is not available,
1402 * we look in the underlying character data for the first semicolon.
1404 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1405 const LangOptions &LO)
1407 const char *semi;
1408 const char *s = SM.getCharacterData(loc);
1410 semi = strchr(s, ';');
1411 if (!semi)
1412 return SourceLocation();
1413 return loc.getFileLocWithOffset(semi + 1 - s);
1416 #endif
1418 /* If the token at "loc" is the first token on the line, then return
1419 * a location referring to the start of the line and set *indent
1420 * to the indentation of "loc"
1421 * Otherwise, return "loc" and set *indent to "".
1423 * This function is used to extend a scop to the start of the line
1424 * if the first token of the scop is also the first token on the line.
1426 * We look for the first token on the line. If its location is equal to "loc",
1427 * then the latter is the location of the first token on the line.
1429 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1430 SourceManager &SM, const LangOptions &LO, char **indent)
1432 std::pair<FileID, unsigned> file_offset_pair;
1433 llvm::StringRef file;
1434 const char *pos;
1435 Token tok;
1436 SourceLocation token_loc, line_loc;
1437 int col;
1438 const char *s;
1440 loc = SM.getExpansionLoc(loc);
1441 col = SM.getExpansionColumnNumber(loc);
1442 line_loc = loc.getLocWithOffset(1 - col);
1443 file_offset_pair = SM.getDecomposedLoc(line_loc);
1444 file = SM.getBufferData(file_offset_pair.first, NULL);
1445 pos = file.data() + file_offset_pair.second;
1447 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1448 file.begin(), pos, file.end());
1449 lexer.LexFromRawLexer(tok);
1450 token_loc = tok.getLocation();
1452 s = SM.getCharacterData(line_loc);
1453 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1455 if (token_loc == loc)
1456 return line_loc;
1457 else
1458 return loc;
1461 /* Construct a pet_loc corresponding to the region covered by "range".
1462 * If "skip_semi" is set, then we assume "range" is followed by
1463 * a semicolon and also include this semicolon.
1465 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1466 bool skip_semi)
1468 SourceLocation loc = range.getBegin();
1469 SourceManager &SM = PP.getSourceManager();
1470 const LangOptions &LO = PP.getLangOpts();
1471 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1472 unsigned start, end;
1473 char *indent;
1475 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1476 start = getExpansionOffset(SM, loc);
1477 loc = range.getEnd();
1478 if (skip_semi)
1479 loc = location_after_semi(loc, SM, LO);
1480 else
1481 loc = PP.getLocForEndOfToken(loc);
1482 end = getExpansionOffset(SM, loc);
1484 return pet_loc_alloc(ctx, start, end, line, indent);
1487 /* Convert a top-level pet_expr to an expression pet_tree.
1489 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1490 SourceRange range, bool skip_semi)
1492 pet_loc *loc;
1493 pet_tree *tree;
1495 tree = pet_tree_new_expr(expr);
1496 loc = construct_pet_loc(range, skip_semi);
1497 tree = pet_tree_set_loc(tree, loc);
1499 return tree;
1502 /* Construct a pet_tree for an if statement.
1504 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1506 pet_expr *pe_cond;
1507 pet_tree *tree, *tree_else;
1508 struct pet_scop *scop;
1509 int int_size;
1511 pe_cond = extract_expr(stmt->getCond());
1512 tree = extract(stmt->getThen());
1513 if (stmt->getElse()) {
1514 tree_else = extract(stmt->getElse());
1515 if (options->autodetect) {
1516 if (tree && !tree_else) {
1517 partial = true;
1518 pet_expr_free(pe_cond);
1519 return tree;
1521 if (!tree && tree_else) {
1522 partial = true;
1523 pet_expr_free(pe_cond);
1524 return tree_else;
1527 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1528 } else
1529 tree = pet_tree_new_if(pe_cond, tree);
1530 return tree;
1533 /* Try and construct a pet_tree for a label statement.
1534 * We currently only allow labels on expression statements.
1536 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1538 isl_id *label;
1539 pet_tree *tree;
1540 Stmt *sub;
1542 sub = stmt->getSubStmt();
1543 if (!isa<Expr>(sub)) {
1544 unsupported(stmt);
1545 return NULL;
1548 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1550 tree = extract(extract_expr(cast<Expr>(sub)), stmt->getSourceRange(),
1551 true);
1552 tree = pet_tree_set_label(tree, label);
1553 return tree;
1556 /* Update the location of "tree" to include the source range of "stmt".
1558 * Actually, we create a new location based on the source range of "stmt" and
1559 * then extend this new location to include the region of the original location.
1560 * This ensures that the line number of the final location refers to "stmt".
1562 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1564 pet_loc *loc, *tree_loc;
1566 tree_loc = pet_tree_get_loc(tree);
1567 loc = construct_pet_loc(stmt->getSourceRange(), false);
1568 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1569 pet_loc_free(tree_loc);
1571 tree = pet_tree_set_loc(tree, loc);
1572 return tree;
1575 /* Try and construct a pet_tree corresponding to "stmt".
1577 * If "stmt" is a compound statement, then "skip_declarations"
1578 * indicates whether we should skip initial declarations in the
1579 * compound statement.
1581 * If the constructed pet_tree is not a (possibly) partial representation
1582 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1583 * In particular, if skip_declarations is set, then we may have skipped
1584 * declarations inside "stmt" and so the pet_scop may not represent
1585 * the entire "stmt".
1586 * Note that this function may be called with "stmt" referring to the entire
1587 * body of the function, including the outer braces. In such cases,
1588 * skip_declarations will be set and the braces will not be taken into
1589 * account in tree->loc.
1591 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
1593 pet_tree *tree;
1595 set_current_stmt(stmt);
1597 if (isa<Expr>(stmt))
1598 return extract(extract_expr(cast<Expr>(stmt)),
1599 stmt->getSourceRange(), true);
1601 switch (stmt->getStmtClass()) {
1602 case Stmt::WhileStmtClass:
1603 tree = extract(cast<WhileStmt>(stmt));
1604 break;
1605 case Stmt::ForStmtClass:
1606 tree = extract_for(cast<ForStmt>(stmt));
1607 break;
1608 case Stmt::IfStmtClass:
1609 tree = extract(cast<IfStmt>(stmt));
1610 break;
1611 case Stmt::CompoundStmtClass:
1612 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
1613 break;
1614 case Stmt::LabelStmtClass:
1615 tree = extract(cast<LabelStmt>(stmt));
1616 break;
1617 case Stmt::ContinueStmtClass:
1618 tree = pet_tree_new_continue(ctx);
1619 break;
1620 case Stmt::BreakStmtClass:
1621 tree = pet_tree_new_break(ctx);
1622 break;
1623 case Stmt::DeclStmtClass:
1624 tree = extract(cast<DeclStmt>(stmt));
1625 break;
1626 default:
1627 unsupported(stmt);
1628 return NULL;
1631 if (partial || skip_declarations)
1632 return tree;
1634 return update_loc(tree, stmt);
1637 /* Try and construct a pet_tree corresponding to (part of)
1638 * a sequence of statements.
1640 * "block" is set if the sequence represents the children of
1641 * a compound statement.
1642 * "skip_declarations" is set if we should skip initial declarations
1643 * in the sequence of statements.
1645 * If autodetect is set, then we allow the extraction of only a subrange
1646 * of the sequence of statements. However, if there is at least one statement
1647 * for which we could not construct a scop and the final range contains
1648 * either no statements or at least one kill, then we discard the entire
1649 * range.
1651 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
1652 bool skip_declarations)
1654 StmtIterator i;
1655 int j;
1656 bool has_kills = false;
1657 bool partial_range = false;
1658 pet_tree *tree;
1659 set<struct pet_stmt *> kills;
1660 set<struct pet_stmt *>::iterator it;
1662 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
1665 tree = pet_tree_new_block(ctx, block, j);
1667 for (i = stmt_range.first; i != stmt_range.second; ++i) {
1668 Stmt *child = *i;
1669 pet_tree *tree_i;
1671 if (pet_tree_block_n_child(tree) == 0 && skip_declarations &&
1672 child->getStmtClass() == Stmt::DeclStmtClass)
1673 continue;
1675 tree_i = extract(child);
1676 if (pet_tree_block_n_child(tree) != 0 && partial) {
1677 pet_tree_free(tree_i);
1678 break;
1680 if (tree_i && child->getStmtClass() == Stmt::DeclStmtClass &&
1681 block)
1682 has_kills = true;
1683 if (options->autodetect) {
1684 if (tree_i)
1685 tree = pet_tree_block_add_child(tree, tree_i);
1686 else
1687 partial_range = true;
1688 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
1689 partial = true;
1690 } else {
1691 tree = pet_tree_block_add_child(tree, tree_i);
1694 if (partial || !tree)
1695 break;
1698 if (tree && partial_range) {
1699 if (pet_tree_block_n_child(tree) == 0 || has_kills) {
1700 pet_tree_free(tree);
1701 return NULL;
1703 partial = true;
1706 return tree;
1709 /* Is "T" the type of a variable length array with static size?
1711 static bool is_vla_with_static_size(QualType T)
1713 const VariableArrayType *vlatype;
1715 if (!T->isVariableArrayType())
1716 return false;
1717 vlatype = cast<VariableArrayType>(T);
1718 return vlatype->getSizeModifier() == VariableArrayType::Static;
1721 /* Return the type of "decl" as an array.
1723 * In particular, if "decl" is a parameter declaration that
1724 * is a variable length array with a static size, then
1725 * return the original type (i.e., the variable length array).
1726 * Otherwise, return the type of decl.
1728 static QualType get_array_type(ValueDecl *decl)
1730 ParmVarDecl *parm;
1731 QualType T;
1733 parm = dyn_cast<ParmVarDecl>(decl);
1734 if (!parm)
1735 return decl->getType();
1737 T = parm->getOriginalType();
1738 if (!is_vla_with_static_size(T))
1739 return decl->getType();
1740 return T;
1743 extern "C" {
1744 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1745 void *user);
1746 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1747 __isl_keep pet_context *pc, void *user);
1750 /* Construct a pet_expr that holds the sizes of the array accessed
1751 * by "access".
1752 * This function is used as a callback to pet_context_add_parameters,
1753 * which is also passed a pointer to the PetScan object.
1755 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1756 void *user)
1758 PetScan *ps = (PetScan *) user;
1759 isl_id *id;
1760 ValueDecl *decl;
1761 const Type *type;
1763 id = pet_expr_access_get_id(access);
1764 decl = (ValueDecl *) isl_id_get_user(id);
1765 isl_id_free(id);
1766 type = get_array_type(decl).getTypePtr();
1767 return ps->get_array_size(type);
1770 /* Construct and return a pet_array corresponding to the variable
1771 * accessed by "access".
1772 * This function is used as a callback to pet_scop_from_pet_tree,
1773 * which is also passed a pointer to the PetScan object.
1775 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1776 __isl_keep pet_context *pc, void *user)
1778 PetScan *ps = (PetScan *) user;
1779 isl_ctx *ctx;
1780 isl_id *id;
1781 ValueDecl *iv;
1783 ctx = pet_expr_get_ctx(access);
1784 id = pet_expr_access_get_id(access);
1785 iv = (ValueDecl *) isl_id_get_user(id);
1786 isl_id_free(id);
1787 return ps->extract_array(ctx, iv, NULL, pc);
1790 /* Extract a function summary from the body of "fd".
1792 * We extract a scop from the function body in a context with as
1793 * parameters the integer arguments of the function.
1794 * We turn off autodetection (in case it was set) to ensure that
1795 * the entire function body is considered.
1796 * We then collect the accessed array elements and attach them
1797 * to the corresponding array arguments, taking into account
1798 * that the function body may access members of array elements.
1800 * The reason for representing the integer arguments as parameters in
1801 * the context is that if we were to instead start with a context
1802 * with the function arguments as initial dimensions, then we would not
1803 * be able to refer to them from the array extents, without turning
1804 * array extents into maps.
1806 * The result is stored in the summary_cache cache so that we can reuse
1807 * it if this method gets called on the same function again later on.
1809 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
1811 isl_space *space;
1812 isl_set *domain;
1813 pet_context *pc;
1814 pet_tree *tree;
1815 pet_function_summary *summary;
1816 unsigned n;
1817 ScopLoc loc;
1818 int save_autodetect;
1819 struct pet_scop *scop;
1820 int int_size;
1821 isl_union_set *may_read, *may_write, *must_write;
1822 isl_union_map *to_inner;
1824 if (summary_cache.find(fd) != summary_cache.end())
1825 return pet_function_summary_copy(summary_cache[fd]);
1827 space = isl_space_set_alloc(ctx, 0, 0);
1829 n = fd->getNumParams();
1830 summary = pet_function_summary_alloc(ctx, n);
1831 for (int i = 0; i < n; ++i) {
1832 ParmVarDecl *parm = fd->getParamDecl(i);
1833 QualType type = parm->getType();
1834 isl_id *id;
1836 if (!type->isIntegerType())
1837 continue;
1838 id = create_decl_id(ctx, parm);
1839 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
1840 space = isl_space_set_dim_id(space, isl_dim_param, 0,
1841 isl_id_copy(id));
1842 summary = pet_function_summary_set_int(summary, i, id);
1845 save_autodetect = options->autodetect;
1846 options->autodetect = 0;
1847 PetScan body_scan(PP, ast_context, loc, options,
1848 isl_union_map_copy(value_bounds), independent);
1850 tree = body_scan.extract(fd->getBody(), false);
1852 domain = isl_set_universe(space);
1853 pc = pet_context_alloc(domain);
1854 pc = pet_context_add_parameters(pc, tree,
1855 &::get_array_size, &body_scan);
1856 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
1857 scop = pet_scop_from_pet_tree(tree, int_size,
1858 &::extract_array, &body_scan, pc);
1859 scop = scan_arrays(scop, pc);
1860 may_read = isl_union_map_range(pet_scop_collect_may_reads(scop));
1861 may_write = isl_union_map_range(pet_scop_collect_may_writes(scop));
1862 must_write = isl_union_map_range(pet_scop_collect_must_writes(scop));
1863 to_inner = pet_scop_compute_outer_to_inner(scop);
1864 pet_scop_free(scop);
1866 for (int i = 0; i < n; ++i) {
1867 ParmVarDecl *parm = fd->getParamDecl(i);
1868 QualType type = parm->getType();
1869 struct pet_array *array;
1870 isl_space *space;
1871 isl_union_set *data_set;
1872 isl_union_set *may_read_i, *may_write_i, *must_write_i;
1874 if (array_depth(type.getTypePtr()) == 0)
1875 continue;
1877 array = body_scan.extract_array(ctx, parm, NULL, pc);
1878 space = array ? isl_set_get_space(array->extent) : NULL;
1879 pet_array_free(array);
1880 data_set = isl_union_set_from_set(isl_set_universe(space));
1881 data_set = isl_union_set_apply(data_set,
1882 isl_union_map_copy(to_inner));
1883 may_read_i = isl_union_set_intersect(
1884 isl_union_set_copy(may_read),
1885 isl_union_set_copy(data_set));
1886 may_write_i = isl_union_set_intersect(
1887 isl_union_set_copy(may_write),
1888 isl_union_set_copy(data_set));
1889 must_write_i = isl_union_set_intersect(
1890 isl_union_set_copy(must_write), data_set);
1891 summary = pet_function_summary_set_array(summary, i,
1892 may_read_i, may_write_i, must_write_i);
1895 isl_union_set_free(may_read);
1896 isl_union_set_free(may_write);
1897 isl_union_set_free(must_write);
1898 isl_union_map_free(to_inner);
1900 options->autodetect = save_autodetect;
1901 pet_context_free(pc);
1903 summary_cache[fd] = pet_function_summary_copy(summary);
1905 return summary;
1908 /* If "fd" has a function body, then extract a function summary from
1909 * this body and attach it to the call expression "expr".
1911 * Even if a function body is available, "fd" itself may point
1912 * to a declaration without function body. We therefore first
1913 * replace it by the declaration that comes with a body (if any).
1915 * It is not clear why hasBody takes a reference to a const FunctionDecl *.
1916 * It seems that it is possible to directly use the iterators to obtain
1917 * a non-const pointer.
1918 * Since we are not going to use the pointer to modify anything anyway,
1919 * it seems safe to drop the constness. The alternative would be to
1920 * modify a lot of other functions to include const qualifiers.
1922 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
1923 FunctionDecl *fd)
1925 pet_function_summary *summary;
1926 const FunctionDecl *def;
1928 if (!expr)
1929 return NULL;
1930 if (!fd->hasBody(def))
1931 return expr;
1933 fd = const_cast<FunctionDecl *>(def);
1935 summary = get_summary(fd);
1937 expr = pet_expr_call_set_summary(expr, summary);
1939 return expr;
1942 /* Extract a pet_scop from "tree".
1944 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
1945 * then add pet_arrays for all accessed arrays.
1946 * We populate the pet_context with assignments for all parameters used
1947 * inside "tree" or any of the size expressions for the arrays accessed
1948 * by "tree" so that they can be used in affine expressions.
1950 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
1952 int int_size;
1953 isl_set *domain;
1954 pet_context *pc;
1955 pet_scop *scop;
1957 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
1959 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
1960 pc = pet_context_alloc(domain);
1961 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
1962 scop = pet_scop_from_pet_tree(tree, int_size,
1963 &::extract_array, this, pc);
1964 scop = scan_arrays(scop, pc);
1965 pet_context_free(pc);
1967 return scop;
1970 /* Check if the scop marked by the user is exactly this Stmt
1971 * or part of this Stmt.
1972 * If so, return a pet_scop corresponding to the marked region.
1973 * Otherwise, return NULL.
1975 struct pet_scop *PetScan::scan(Stmt *stmt)
1977 SourceManager &SM = PP.getSourceManager();
1978 unsigned start_off, end_off;
1980 start_off = getExpansionOffset(SM, stmt->getLocStart());
1981 end_off = getExpansionOffset(SM, stmt->getLocEnd());
1983 if (start_off > loc.end)
1984 return NULL;
1985 if (end_off < loc.start)
1986 return NULL;
1988 if (start_off >= loc.start && end_off <= loc.end)
1989 return extract_scop(extract(stmt));
1991 StmtIterator start;
1992 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
1993 Stmt *child = *start;
1994 if (!child)
1995 continue;
1996 start_off = getExpansionOffset(SM, child->getLocStart());
1997 end_off = getExpansionOffset(SM, child->getLocEnd());
1998 if (start_off < loc.start && end_off >= loc.end)
1999 return scan(child);
2000 if (start_off >= loc.start)
2001 break;
2004 StmtIterator end;
2005 for (end = start; end != stmt->child_end(); ++end) {
2006 Stmt *child = *end;
2007 start_off = SM.getFileOffset(child->getLocStart());
2008 if (start_off >= loc.end)
2009 break;
2012 return extract_scop(extract(StmtRange(start, end), false, false));
2015 /* Set the size of index "pos" of "array" to "size".
2016 * In particular, add a constraint of the form
2018 * i_pos < size
2020 * to array->extent and a constraint of the form
2022 * size >= 0
2024 * to array->context.
2026 * The domain of "size" is assumed to be zero-dimensional.
2028 static struct pet_array *update_size(struct pet_array *array, int pos,
2029 __isl_take isl_pw_aff *size)
2031 isl_set *valid;
2032 isl_set *univ;
2033 isl_set *bound;
2034 isl_space *dim;
2035 isl_aff *aff;
2036 isl_pw_aff *index;
2037 isl_id *id;
2039 if (!array)
2040 goto error;
2042 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2043 array->context = isl_set_intersect(array->context, valid);
2045 dim = isl_set_get_space(array->extent);
2046 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2047 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2048 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2049 index = isl_pw_aff_alloc(univ, aff);
2051 size = isl_pw_aff_add_dims(size, isl_dim_in,
2052 isl_set_dim(array->extent, isl_dim_set));
2053 id = isl_set_get_tuple_id(array->extent);
2054 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2055 bound = isl_pw_aff_lt_set(index, size);
2057 array->extent = isl_set_intersect(array->extent, bound);
2059 if (!array->context || !array->extent)
2060 return pet_array_free(array);
2062 return array;
2063 error:
2064 isl_pw_aff_free(size);
2065 return NULL;
2068 #ifdef HAVE_DECAYEDTYPE
2070 /* If "type" is a decayed type, then set *decayed to true and
2071 * return the original type.
2073 static const Type *undecay(const Type *type, bool *decayed)
2075 *decayed = isa<DecayedType>(type);
2076 if (*decayed)
2077 type = cast<DecayedType>(type)->getOriginalType().getTypePtr();
2078 return type;
2081 #else
2083 /* If "type" is a decayed type, then set *decayed to true and
2084 * return the original type.
2085 * Since this version of clang does not define a DecayedType,
2086 * we cannot obtain the original type even if it had been decayed and
2087 * we set *decayed to false.
2089 static const Type *undecay(const Type *type, bool *decayed)
2091 *decayed = false;
2092 return type;
2095 #endif
2097 /* Figure out the size of the array at position "pos" and all
2098 * subsequent positions from "type" and update the corresponding
2099 * argument of "expr" accordingly.
2101 * The initial type (when pos is zero) may be a pointer type decayed
2102 * from an array type, if this initial type is the type of a function
2103 * argument. This only happens if the original array type has
2104 * a constant size in the outer dimension as otherwise we get
2105 * a VariableArrayType. Try and obtain this original type (if available) and
2106 * take the outer array size into account if it was marked static.
2108 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2109 const Type *type, int pos)
2111 const ArrayType *atype;
2112 pet_expr *size;
2113 bool decayed = false;
2115 if (!expr)
2116 return NULL;
2118 if (pos == 0)
2119 type = undecay(type, &decayed);
2121 if (type->isPointerType()) {
2122 type = type->getPointeeType().getTypePtr();
2123 return set_upper_bounds(expr, type, pos + 1);
2125 if (!type->isArrayType())
2126 return expr;
2128 type = type->getCanonicalTypeInternal().getTypePtr();
2129 atype = cast<ArrayType>(type);
2131 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2132 type = atype->getElementType().getTypePtr();
2133 return set_upper_bounds(expr, type, pos + 1);
2136 if (type->isConstantArrayType()) {
2137 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2138 size = extract_expr(ca->getSize());
2139 expr = pet_expr_set_arg(expr, pos, size);
2140 } else if (type->isVariableArrayType()) {
2141 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2142 size = extract_expr(vla->getSizeExpr());
2143 expr = pet_expr_set_arg(expr, pos, size);
2146 type = atype->getElementType().getTypePtr();
2148 return set_upper_bounds(expr, type, pos + 1);
2151 /* Construct a pet_expr that holds the sizes of an array of the given type.
2152 * The returned expression is a call expression with as arguments
2153 * the sizes in each dimension. If we are unable to derive the size
2154 * in a given dimension, then the corresponding argument is set to infinity.
2155 * In fact, we initialize all arguments to infinity and then update
2156 * them if we are able to figure out the size.
2158 * The result is stored in the type_size cache so that we can reuse
2159 * it if this method gets called on the same type again later on.
2161 __isl_give pet_expr *PetScan::get_array_size(const Type *type)
2163 int depth;
2164 pet_expr *expr, *inf;
2166 if (type_size.find(type) != type_size.end())
2167 return pet_expr_copy(type_size[type]);
2169 depth = array_depth(type);
2170 inf = pet_expr_new_int(isl_val_infty(ctx));
2171 expr = pet_expr_new_call(ctx, "bounds", depth);
2172 for (int i = 0; i < depth; ++i)
2173 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2174 pet_expr_free(inf);
2176 expr = set_upper_bounds(expr, type, 0);
2177 type_size[type] = pet_expr_copy(expr);
2179 return expr;
2182 /* Does "expr" represent the "integer" infinity?
2184 static int is_infty(__isl_keep pet_expr *expr)
2186 isl_val *v;
2187 int res;
2189 if (pet_expr_get_type(expr) != pet_expr_int)
2190 return 0;
2191 v = pet_expr_int_get_val(expr);
2192 res = isl_val_is_infty(v);
2193 isl_val_free(v);
2195 return res;
2198 /* Figure out the dimensions of an array "array" based on its type
2199 * "type" and update "array" accordingly.
2201 * We first construct a pet_expr that holds the sizes of the array
2202 * in each dimension. The resulting expression may containing
2203 * infinity values for dimension where we are unable to derive
2204 * a size expression.
2206 * The arguments of the size expression that have a value different from
2207 * infinity are then converted to an affine expression
2208 * within the context "pc" and incorporated into the size of "array".
2209 * If we are unable to convert a size expression to an affine expression or
2210 * if the size is not a (symbolic) constant,
2211 * then we leave the corresponding size of "array" untouched.
2213 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2214 const Type *type, __isl_keep pet_context *pc)
2216 int n;
2217 pet_expr *expr;
2219 if (!array)
2220 return NULL;
2222 expr = get_array_size(type);
2224 n = pet_expr_get_n_arg(expr);
2225 for (int i = 0; i < n; ++i) {
2226 pet_expr *arg;
2227 isl_pw_aff *size;
2229 arg = pet_expr_get_arg(expr, i);
2230 if (!is_infty(arg)) {
2231 int dim;
2233 size = pet_expr_extract_affine(arg, pc);
2234 dim = isl_pw_aff_dim(size, isl_dim_in);
2235 if (!size)
2236 array = pet_array_free(array);
2237 else if (isl_pw_aff_involves_nan(size) ||
2238 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2239 isl_pw_aff_free(size);
2240 else {
2241 size = isl_pw_aff_drop_dims(size,
2242 isl_dim_in, 0, dim);
2243 array = update_size(array, i, size);
2246 pet_expr_free(arg);
2248 pet_expr_free(expr);
2250 return array;
2253 /* Does "decl" have definition that we can keep track of in a pet_type?
2255 static bool has_printable_definition(RecordDecl *decl)
2257 if (!decl->getDeclName())
2258 return false;
2259 return decl->getLexicalDeclContext() == decl->getDeclContext();
2262 /* Construct and return a pet_array corresponding to the variable "decl".
2263 * In particular, initialize array->extent to
2265 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2267 * and then call set_upper_bounds to set the upper bounds on the indices
2268 * based on the type of the variable. The upper bounds are converted
2269 * to affine expressions within the context "pc".
2271 * If the base type is that of a record with a top-level definition and
2272 * if "types" is not null, then the RecordDecl corresponding to the type
2273 * is added to "types".
2275 * If the base type is that of a record with no top-level definition,
2276 * then we replace it by "<subfield>".
2278 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
2279 lex_recorddecl_set *types, __isl_keep pet_context *pc)
2281 struct pet_array *array;
2282 QualType qt = get_array_type(decl);
2283 const Type *type = qt.getTypePtr();
2284 int depth = array_depth(type);
2285 QualType base = pet_clang_base_type(qt);
2286 string name;
2287 isl_id *id;
2288 isl_space *dim;
2290 array = isl_calloc_type(ctx, struct pet_array);
2291 if (!array)
2292 return NULL;
2294 id = create_decl_id(ctx, decl);
2295 dim = isl_space_set_alloc(ctx, 0, depth);
2296 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
2298 array->extent = isl_set_nat_universe(dim);
2300 dim = isl_space_params_alloc(ctx, 0);
2301 array->context = isl_set_universe(dim);
2303 array = set_upper_bounds(array, type, pc);
2304 if (!array)
2305 return NULL;
2307 name = base.getAsString();
2309 if (types && base->isRecordType()) {
2310 RecordDecl *decl = pet_clang_record_decl(base);
2311 if (has_printable_definition(decl))
2312 types->insert(decl);
2313 else
2314 name = "<subfield>";
2317 array->element_type = strdup(name.c_str());
2318 array->element_is_record = base->isRecordType();
2319 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
2321 return array;
2324 /* Construct and return a pet_array corresponding to the sequence
2325 * of declarations "decls".
2326 * The upper bounds of the array are converted to affine expressions
2327 * within the context "pc".
2328 * If the sequence contains a single declaration, then it corresponds
2329 * to a simple array access. Otherwise, it corresponds to a member access,
2330 * with the declaration for the substructure following that of the containing
2331 * structure in the sequence of declarations.
2332 * We start with the outermost substructure and then combine it with
2333 * information from the inner structures.
2335 * Additionally, keep track of all required types in "types".
2337 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
2338 vector<ValueDecl *> decls, lex_recorddecl_set *types,
2339 __isl_keep pet_context *pc)
2341 struct pet_array *array;
2342 vector<ValueDecl *>::iterator it;
2344 it = decls.begin();
2346 array = extract_array(ctx, *it, types, pc);
2348 for (++it; it != decls.end(); ++it) {
2349 struct pet_array *parent;
2350 const char *base_name, *field_name;
2351 char *product_name;
2353 parent = array;
2354 array = extract_array(ctx, *it, types, pc);
2355 if (!array)
2356 return pet_array_free(parent);
2358 base_name = isl_set_get_tuple_name(parent->extent);
2359 field_name = isl_set_get_tuple_name(array->extent);
2360 product_name = pet_array_member_access_name(ctx,
2361 base_name, field_name);
2363 array->extent = isl_set_product(isl_set_copy(parent->extent),
2364 array->extent);
2365 if (product_name)
2366 array->extent = isl_set_set_tuple_name(array->extent,
2367 product_name);
2368 array->context = isl_set_intersect(array->context,
2369 isl_set_copy(parent->context));
2371 pet_array_free(parent);
2372 free(product_name);
2374 if (!array->extent || !array->context || !product_name)
2375 return pet_array_free(array);
2378 return array;
2381 /* Add a pet_type corresponding to "decl" to "scop, provided
2382 * it is a member of "types" and it has not been added before
2383 * (i.e., it is not a member of "types_done".
2385 * Since we want the user to be able to print the types
2386 * in the order in which they appear in the scop, we need to
2387 * make sure that types of fields in a structure appear before
2388 * that structure. We therefore call ourselves recursively
2389 * on the types of all record subfields.
2391 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2392 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
2393 lex_recorddecl_set &types_done)
2395 string s;
2396 llvm::raw_string_ostream S(s);
2397 RecordDecl::field_iterator it;
2399 if (types.find(decl) == types.end())
2400 return scop;
2401 if (types_done.find(decl) != types_done.end())
2402 return scop;
2404 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
2405 RecordDecl *record;
2406 QualType type = it->getType();
2408 if (!type->isRecordType())
2409 continue;
2410 record = pet_clang_record_decl(type);
2411 scop = add_type(ctx, scop, record, PP, types, types_done);
2414 if (strlen(decl->getName().str().c_str()) == 0)
2415 return scop;
2417 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2418 S.str();
2420 scop->types[scop->n_type] = pet_type_alloc(ctx,
2421 decl->getName().str().c_str(), s.c_str());
2422 if (!scop->types[scop->n_type])
2423 return pet_scop_free(scop);
2425 types_done.insert(decl);
2427 scop->n_type++;
2429 return scop;
2432 /* Construct a list of pet_arrays, one for each array (or scalar)
2433 * accessed inside "scop", add this list to "scop" and return the result.
2434 * The upper bounds of the arrays are converted to affine expressions
2435 * within the context "pc".
2437 * The context of "scop" is updated with the intersection of
2438 * the contexts of all arrays, i.e., constraints on the parameters
2439 * that ensure that the arrays have a valid (non-negative) size.
2441 * If the any of the extracted arrays refers to a member access,
2442 * then also add the required types to "scop".
2444 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
2445 __isl_keep pet_context *pc)
2447 int i;
2448 array_desc_set arrays;
2449 array_desc_set::iterator it;
2450 lex_recorddecl_set types;
2451 lex_recorddecl_set types_done;
2452 lex_recorddecl_set::iterator types_it;
2453 int n_array;
2454 struct pet_array **scop_arrays;
2456 if (!scop)
2457 return NULL;
2459 pet_scop_collect_arrays(scop, arrays);
2460 if (arrays.size() == 0)
2461 return scop;
2463 n_array = scop->n_array;
2465 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2466 n_array + arrays.size());
2467 if (!scop_arrays)
2468 goto error;
2469 scop->arrays = scop_arrays;
2471 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
2472 struct pet_array *array;
2473 array = extract_array(ctx, *it, &types, pc);
2474 scop->arrays[n_array + i] = array;
2475 if (!scop->arrays[n_array + i])
2476 goto error;
2477 scop->n_array++;
2478 scop->context = isl_set_intersect(scop->context,
2479 isl_set_copy(array->context));
2480 if (!scop->context)
2481 goto error;
2484 if (types.size() == 0)
2485 return scop;
2487 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
2488 if (!scop->types)
2489 goto error;
2491 for (types_it = types.begin(); types_it != types.end(); ++types_it)
2492 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
2494 return scop;
2495 error:
2496 pet_scop_free(scop);
2497 return NULL;
2500 /* Bound all parameters in scop->context to the possible values
2501 * of the corresponding C variable.
2503 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
2505 int n;
2507 if (!scop)
2508 return NULL;
2510 n = isl_set_dim(scop->context, isl_dim_param);
2511 for (int i = 0; i < n; ++i) {
2512 isl_id *id;
2513 ValueDecl *decl;
2515 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
2516 if (pet_nested_in_id(id)) {
2517 isl_id_free(id);
2518 isl_die(isl_set_get_ctx(scop->context),
2519 isl_error_internal,
2520 "unresolved nested parameter", goto error);
2522 decl = (ValueDecl *) isl_id_get_user(id);
2523 isl_id_free(id);
2525 scop->context = set_parameter_bounds(scop->context, i, decl);
2527 if (!scop->context)
2528 goto error;
2531 return scop;
2532 error:
2533 pet_scop_free(scop);
2534 return NULL;
2537 /* Construct a pet_scop from the given function.
2539 * If the scop was delimited by scop and endscop pragmas, then we override
2540 * the file offsets by those derived from the pragmas.
2542 struct pet_scop *PetScan::scan(FunctionDecl *fd)
2544 pet_scop *scop;
2545 Stmt *stmt;
2547 stmt = fd->getBody();
2549 if (options->autodetect) {
2550 set_current_stmt(stmt);
2551 scop = extract_scop(extract(stmt, true));
2552 } else {
2553 current_line = loc.start_line;
2554 scop = scan(stmt);
2555 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
2557 scop = add_parameter_bounds(scop);
2558 scop = pet_scop_gist(scop, value_bounds);
2560 return scop;
2563 /* Update this->last_line and this->current_line based on the fact
2564 * that we are about to consider "stmt".
2566 void PetScan::set_current_stmt(Stmt *stmt)
2568 SourceLocation loc = stmt->getLocStart();
2569 SourceManager &SM = PP.getSourceManager();
2571 last_line = current_line;
2572 current_line = SM.getExpansionLineNumber(loc);
2575 /* Is the current statement marked by an independent pragma?
2576 * That is, is there an independent pragma on a line between
2577 * the line of the current statement and the line of the previous statement.
2578 * The search is not implemented very efficiently. We currently
2579 * assume that there are only a few independent pragmas, if any.
2581 bool PetScan::is_current_stmt_marked_independent()
2583 for (int i = 0; i < independent.size(); ++i) {
2584 unsigned line = independent[i].line;
2586 if (last_line < line && line < current_line)
2587 return true;
2590 return false;