add pet_expr_map_op
[pet.git] / scan.cc
blob04077aba89c22201480f12afc0c24858fd3147a8
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2015 Ecole Normale Superieure. All rights reserved.
4 * Copyright 2015-2016 Sven Verdoolaege. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
19 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
22 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
25 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 * The views and conclusions contained in the software and documentation
31 * are those of the authors and should not be interpreted as
32 * representing official policies, either expressed or implied, of
33 * Leiden University.
34 */
36 #include "config.h"
38 #include <string.h>
39 #include <set>
40 #include <map>
41 #include <iostream>
42 #include <sstream>
43 #include <llvm/Support/raw_ostream.h>
44 #include <clang/AST/ASTContext.h>
45 #include <clang/AST/ASTDiagnostic.h>
46 #include <clang/AST/Attr.h>
47 #include <clang/AST/Expr.h>
48 #include <clang/AST/RecursiveASTVisitor.h>
50 #include <isl/id.h>
51 #include <isl/space.h>
52 #include <isl/aff.h>
53 #include <isl/set.h>
54 #include <isl/union_set.h>
56 #include "aff.h"
57 #include "array.h"
58 #include "clang.h"
59 #include "context.h"
60 #include "expr.h"
61 #include "id.h"
62 #include "inliner.h"
63 #include "killed_locals.h"
64 #include "nest.h"
65 #include "options.h"
66 #include "scan.h"
67 #include "scop.h"
68 #include "scop_plus.h"
69 #include "substituter.h"
70 #include "tree.h"
71 #include "tree2scop.h"
73 using namespace std;
74 using namespace clang;
76 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
78 switch (kind) {
79 case UO_Minus:
80 return pet_op_minus;
81 case UO_Not:
82 return pet_op_not;
83 case UO_LNot:
84 return pet_op_lnot;
85 case UO_PostInc:
86 return pet_op_post_inc;
87 case UO_PostDec:
88 return pet_op_post_dec;
89 case UO_PreInc:
90 return pet_op_pre_inc;
91 case UO_PreDec:
92 return pet_op_pre_dec;
93 default:
94 return pet_op_last;
98 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
100 switch (kind) {
101 case BO_AddAssign:
102 return pet_op_add_assign;
103 case BO_SubAssign:
104 return pet_op_sub_assign;
105 case BO_MulAssign:
106 return pet_op_mul_assign;
107 case BO_DivAssign:
108 return pet_op_div_assign;
109 case BO_Assign:
110 return pet_op_assign;
111 case BO_Add:
112 return pet_op_add;
113 case BO_Sub:
114 return pet_op_sub;
115 case BO_Mul:
116 return pet_op_mul;
117 case BO_Div:
118 return pet_op_div;
119 case BO_Rem:
120 return pet_op_mod;
121 case BO_Shl:
122 return pet_op_shl;
123 case BO_Shr:
124 return pet_op_shr;
125 case BO_EQ:
126 return pet_op_eq;
127 case BO_NE:
128 return pet_op_ne;
129 case BO_LE:
130 return pet_op_le;
131 case BO_GE:
132 return pet_op_ge;
133 case BO_LT:
134 return pet_op_lt;
135 case BO_GT:
136 return pet_op_gt;
137 case BO_And:
138 return pet_op_and;
139 case BO_Xor:
140 return pet_op_xor;
141 case BO_Or:
142 return pet_op_or;
143 case BO_LAnd:
144 return pet_op_land;
145 case BO_LOr:
146 return pet_op_lor;
147 default:
148 return pet_op_last;
152 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
153 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
155 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
156 SourceLocation(), var, false, var->getInnerLocStart(),
157 var->getType(), VK_LValue);
159 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
160 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
162 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
163 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
164 VK_LValue);
166 #else
167 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
169 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
170 var, var->getInnerLocStart(), var->getType(), VK_LValue);
172 #endif
174 #ifdef GETTYPEINFORETURNSTYPEINFO
176 static int size_in_bytes(ASTContext &context, QualType type)
178 return context.getTypeInfo(type).Width / 8;
181 #else
183 static int size_in_bytes(ASTContext &context, QualType type)
185 return context.getTypeInfo(type).first / 8;
188 #endif
190 /* Check if the element type corresponding to the given array type
191 * has a const qualifier.
193 static bool const_base(QualType qt)
195 const Type *type = qt.getTypePtr();
197 if (type->isPointerType())
198 return const_base(type->getPointeeType());
199 if (type->isArrayType()) {
200 const ArrayType *atype;
201 type = type->getCanonicalTypeInternal().getTypePtr();
202 atype = cast<ArrayType>(type);
203 return const_base(atype->getElementType());
206 return qt.isConstQualified();
209 PetScan::~PetScan()
211 std::map<const Type *, pet_expr *>::iterator it;
212 std::map<FunctionDecl *, pet_function_summary *>::iterator it_s;
214 for (it = type_size.begin(); it != type_size.end(); ++it)
215 pet_expr_free(it->second);
216 for (it_s = summary_cache.begin(); it_s != summary_cache.end(); ++it_s)
217 pet_function_summary_free(it_s->second);
219 isl_union_map_free(value_bounds);
222 /* Report a diagnostic on the range "range", unless autodetect is set.
224 void PetScan::report(SourceRange range, unsigned id)
226 if (options->autodetect)
227 return;
229 SourceLocation loc = range.getBegin();
230 DiagnosticsEngine &diag = PP.getDiagnostics();
231 DiagnosticBuilder B = diag.Report(loc, id) << range;
234 /* Report a diagnostic on "stmt", unless autodetect is set.
236 void PetScan::report(Stmt *stmt, unsigned id)
238 report(stmt->getSourceRange(), id);
241 /* Report a diagnostic on "decl", unless autodetect is set.
243 void PetScan::report(Decl *decl, unsigned id)
245 report(decl->getSourceRange(), id);
248 /* Called if we found something we (currently) cannot handle.
249 * We'll provide more informative warnings later.
251 * We only actually complain if autodetect is false.
253 void PetScan::unsupported(Stmt *stmt)
255 DiagnosticsEngine &diag = PP.getDiagnostics();
256 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
257 "unsupported");
258 report(stmt, id);
261 /* Report an unsupported unary operator, unless autodetect is set.
263 void PetScan::report_unsupported_unary_operator(Stmt *stmt)
265 DiagnosticsEngine &diag = PP.getDiagnostics();
266 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
267 "this type of unary operator is not supported");
268 report(stmt, id);
271 /* Report an unsupported statement type, unless autodetect is set.
273 void PetScan::report_unsupported_statement_type(Stmt *stmt)
275 DiagnosticsEngine &diag = PP.getDiagnostics();
276 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
277 "this type of statement is not supported");
278 report(stmt, id);
281 /* Report a missing prototype, unless autodetect is set.
283 void PetScan::report_prototype_required(Stmt *stmt)
285 DiagnosticsEngine &diag = PP.getDiagnostics();
286 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
287 "prototype required");
288 report(stmt, id);
291 /* Report a missing increment, unless autodetect is set.
293 void PetScan::report_missing_increment(Stmt *stmt)
295 DiagnosticsEngine &diag = PP.getDiagnostics();
296 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
297 "missing increment");
298 report(stmt, id);
301 /* Report a missing summary function, unless autodetect is set.
303 void PetScan::report_missing_summary_function(Stmt *stmt)
305 DiagnosticsEngine &diag = PP.getDiagnostics();
306 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
307 "missing summary function");
308 report(stmt, id);
311 /* Report a missing summary function body, unless autodetect is set.
313 void PetScan::report_missing_summary_function_body(Stmt *stmt)
315 DiagnosticsEngine &diag = PP.getDiagnostics();
316 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
317 "missing summary function body");
318 report(stmt, id);
321 /* Report an unsupported argument in a call to an inlined function,
322 * unless autodetect is set.
324 void PetScan::report_unsupported_inline_function_argument(Stmt *stmt)
326 DiagnosticsEngine &diag = PP.getDiagnostics();
327 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
328 "unsupported inline function call argument");
329 report(stmt, id);
332 /* Report an unsupported type of declaration, unless autodetect is set.
334 void PetScan::report_unsupported_declaration(Decl *decl)
336 DiagnosticsEngine &diag = PP.getDiagnostics();
337 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
338 "unsupported declaration");
339 report(decl, id);
342 /* Extract an integer from "val", which is assumed to be non-negative.
344 static __isl_give isl_val *extract_unsigned(isl_ctx *ctx,
345 const llvm::APInt &val)
347 unsigned n;
348 const uint64_t *data;
350 data = val.getRawData();
351 n = val.getNumWords();
352 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
355 /* Extract an integer from "val". If "is_signed" is set, then "val"
356 * is signed. Otherwise it it unsigned.
358 static __isl_give isl_val *extract_int(isl_ctx *ctx, bool is_signed,
359 llvm::APInt val)
361 int is_negative = is_signed && val.isNegative();
362 isl_val *v;
364 if (is_negative)
365 val = -val;
367 v = extract_unsigned(ctx, val);
369 if (is_negative)
370 v = isl_val_neg(v);
371 return v;
374 /* Extract an integer from "expr".
376 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
378 const Type *type = expr->getType().getTypePtr();
379 bool is_signed = type->hasSignedIntegerRepresentation();
381 return ::extract_int(ctx, is_signed, expr->getValue());
384 /* Extract an integer from "expr".
385 * Return NULL if "expr" does not (obviously) represent an integer.
387 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
389 return extract_int(expr->getSubExpr());
392 /* Extract an integer from "expr".
393 * Return NULL if "expr" does not (obviously) represent an integer.
395 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
397 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
398 return extract_int(ctx, cast<IntegerLiteral>(expr));
399 if (expr->getStmtClass() == Stmt::ParenExprClass)
400 return extract_int(cast<ParenExpr>(expr));
402 unsupported(expr);
403 return NULL;
406 /* Extract a pet_expr from the APInt "val", which is assumed
407 * to be non-negative.
409 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
411 return pet_expr_new_int(extract_unsigned(ctx, val));
414 /* Return the number of bits needed to represent the type of "decl",
415 * if it is an integer type. Otherwise return 0.
416 * If qt is signed then return the opposite of the number of bits.
418 static int get_type_size(ValueDecl *decl)
420 return pet_clang_get_type_size(decl->getType(), decl->getASTContext());
423 /* Bound parameter "pos" of "set" to the possible values of "decl".
425 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
426 unsigned pos, ValueDecl *decl)
428 int type_size;
429 isl_ctx *ctx;
430 isl_val *bound;
432 ctx = isl_set_get_ctx(set);
433 type_size = get_type_size(decl);
434 if (type_size == 0)
435 isl_die(ctx, isl_error_invalid, "not an integer type",
436 return isl_set_free(set));
437 if (type_size > 0) {
438 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
439 bound = isl_val_int_from_ui(ctx, type_size);
440 bound = isl_val_2exp(bound);
441 bound = isl_val_sub_ui(bound, 1);
442 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
443 } else {
444 bound = isl_val_int_from_ui(ctx, -type_size - 1);
445 bound = isl_val_2exp(bound);
446 bound = isl_val_sub_ui(bound, 1);
447 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
448 isl_val_copy(bound));
449 bound = isl_val_neg(bound);
450 bound = isl_val_sub_ui(bound, 1);
451 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
454 return set;
457 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
459 return extract_index_expr(expr->getSubExpr());
462 /* Return the depth of the array accessed by the index expression "index".
463 * If "index" is an affine expression, i.e., if it does not access
464 * any array, then return 1.
465 * If "index" represent a member access, i.e., if its range is a wrapped
466 * relation, then return the sum of the depth of the array of structures
467 * and that of the member inside the structure.
469 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
471 isl_id *id;
472 ValueDecl *decl;
474 if (!index)
475 return -1;
477 if (isl_multi_pw_aff_range_is_wrapping(index)) {
478 int domain_depth, range_depth;
479 isl_multi_pw_aff *domain, *range;
481 domain = isl_multi_pw_aff_copy(index);
482 domain = isl_multi_pw_aff_range_factor_domain(domain);
483 domain_depth = extract_depth(domain);
484 isl_multi_pw_aff_free(domain);
485 range = isl_multi_pw_aff_copy(index);
486 range = isl_multi_pw_aff_range_factor_range(range);
487 range_depth = extract_depth(range);
488 isl_multi_pw_aff_free(range);
490 return domain_depth + range_depth;
493 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
494 return 1;
496 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
497 if (!id)
498 return -1;
499 decl = pet_id_get_decl(id);
500 isl_id_free(id);
502 return pet_clang_array_depth(decl->getType());
505 /* Return the depth of the array accessed by the access expression "expr".
507 static int extract_depth(__isl_keep pet_expr *expr)
509 isl_multi_pw_aff *index;
510 int depth;
512 index = pet_expr_access_get_index(expr);
513 depth = extract_depth(index);
514 isl_multi_pw_aff_free(index);
516 return depth;
519 /* Construct a pet_expr representing an index expression for an access
520 * to the variable referenced by "expr".
522 * If "expr" references an enum constant, then return an integer expression
523 * instead, representing the value of the enum constant.
525 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
527 return extract_index_expr(expr->getDecl());
530 /* Construct a pet_expr representing an index expression for an access
531 * to the variable "decl".
533 * If "decl" is an enum constant, then we return an integer expression
534 * instead, representing the value of the enum constant.
536 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
538 isl_id *id;
540 if (isa<EnumConstantDecl>(decl))
541 return extract_expr(cast<EnumConstantDecl>(decl));
543 id = pet_id_from_decl(ctx, decl);
544 return pet_id_create_index_expr(id);
547 /* Construct a pet_expr representing the index expression "expr"
548 * Return NULL on error.
550 * If "expr" is a reference to an enum constant, then return
551 * an integer expression instead, representing the value of the enum constant.
553 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
555 switch (expr->getStmtClass()) {
556 case Stmt::ImplicitCastExprClass:
557 return extract_index_expr(cast<ImplicitCastExpr>(expr));
558 case Stmt::DeclRefExprClass:
559 return extract_index_expr(cast<DeclRefExpr>(expr));
560 case Stmt::ArraySubscriptExprClass:
561 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
562 case Stmt::IntegerLiteralClass:
563 return extract_expr(cast<IntegerLiteral>(expr));
564 case Stmt::MemberExprClass:
565 return extract_index_expr(cast<MemberExpr>(expr));
566 default:
567 unsupported(expr);
569 return NULL;
572 /* Extract an index expression from the given array subscript expression.
574 * We first extract an index expression from the base.
575 * This will result in an index expression with a range that corresponds
576 * to the earlier indices.
577 * We then extract the current index and let
578 * pet_expr_access_subscript combine the two.
580 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
582 Expr *base = expr->getBase();
583 Expr *idx = expr->getIdx();
584 pet_expr *index;
585 pet_expr *base_expr;
587 base_expr = extract_index_expr(base);
588 index = extract_expr(idx);
590 base_expr = pet_expr_access_subscript(base_expr, index);
592 return base_expr;
595 /* Extract an index expression from a member expression.
597 * If the base access (to the structure containing the member)
598 * is of the form
600 * A[..]
602 * and the member is called "f", then the member access is of
603 * the form
605 * A_f[A[..] -> f[]]
607 * If the member access is to an anonymous struct, then simply return
609 * A[..]
611 * If the member access in the source code is of the form
613 * A->f
615 * then it is treated as
617 * A[0].f
619 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
621 Expr *base = expr->getBase();
622 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
623 pet_expr *base_index;
624 isl_id *id;
626 base_index = extract_index_expr(base);
628 if (expr->isArrow()) {
629 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
630 base_index = pet_expr_access_subscript(base_index, index);
633 if (field->isAnonymousStructOrUnion())
634 return base_index;
636 id = pet_id_from_decl(ctx, field);
638 return pet_expr_access_member(base_index, id);
641 /* Mark the given access pet_expr as a write.
643 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
645 access = pet_expr_access_set_write(access, 1);
646 access = pet_expr_access_set_read(access, 0);
648 return access;
651 /* Mark the given (read) access pet_expr as also possibly being written.
652 * That is, initialize the may write access relation from the may read relation
653 * and initialize the must write access relation to the empty relation.
655 static __isl_give pet_expr *mark_may_write(__isl_take pet_expr *expr)
657 isl_union_map *access;
658 isl_union_map *empty;
660 access = pet_expr_access_get_dependent_access(expr,
661 pet_expr_access_may_read);
662 empty = isl_union_map_empty(isl_union_map_get_space(access));
663 expr = pet_expr_access_set_access(expr, pet_expr_access_may_write,
664 access);
665 expr = pet_expr_access_set_access(expr, pet_expr_access_must_write,
666 empty);
668 return expr;
671 /* Construct a pet_expr representing a unary operator expression.
673 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
675 int type_size;
676 pet_expr *arg;
677 enum pet_op_type op;
679 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
680 if (op == pet_op_last) {
681 report_unsupported_unary_operator(expr);
682 return NULL;
685 arg = extract_expr(expr->getSubExpr());
687 if (expr->isIncrementDecrementOp() &&
688 pet_expr_get_type(arg) == pet_expr_access) {
689 arg = mark_write(arg);
690 arg = pet_expr_access_set_read(arg, 1);
693 type_size = pet_clang_get_type_size(expr->getType(), ast_context);
694 return pet_expr_new_unary(type_size, op, arg);
697 /* Construct a pet_expr representing a binary operator expression.
699 * If the top level operator is an assignment and the LHS is an access,
700 * then we mark that access as a write. If the operator is a compound
701 * assignment, the access is marked as both a read and a write.
703 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
705 int type_size;
706 pet_expr *lhs, *rhs;
707 enum pet_op_type op;
709 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
710 if (op == pet_op_last) {
711 unsupported(expr);
712 return NULL;
715 lhs = extract_expr(expr->getLHS());
716 rhs = extract_expr(expr->getRHS());
718 if (expr->isAssignmentOp() &&
719 pet_expr_get_type(lhs) == pet_expr_access) {
720 lhs = mark_write(lhs);
721 if (expr->isCompoundAssignmentOp())
722 lhs = pet_expr_access_set_read(lhs, 1);
725 type_size = pet_clang_get_type_size(expr->getType(), ast_context);
726 return pet_expr_new_binary(type_size, op, lhs, rhs);
729 /* Construct a pet_tree for a variable declaration and
730 * add the declaration to the list of declarations
731 * inside the current compound statement.
733 __isl_give pet_tree *PetScan::extract(Decl *decl)
735 VarDecl *vd;
736 pet_expr *lhs, *rhs;
737 pet_tree *tree;
739 if (!isa<VarDecl>(decl)) {
740 report_unsupported_declaration(decl);
741 return NULL;
744 vd = cast<VarDecl>(decl);
745 declarations.push_back(vd);
747 lhs = extract_access_expr(vd);
748 lhs = mark_write(lhs);
749 if (!vd->getInit())
750 tree = pet_tree_new_decl(lhs);
751 else {
752 rhs = extract_expr(vd->getInit());
753 tree = pet_tree_new_decl_init(lhs, rhs);
756 return tree;
759 /* Construct a pet_tree for a variable declaration statement.
760 * If the declaration statement declares multiple variables,
761 * then return a group of pet_trees, one for each declared variable.
763 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
765 pet_tree *tree;
766 unsigned n;
768 if (!stmt->isSingleDecl()) {
769 const DeclGroup &group = stmt->getDeclGroup().getDeclGroup();
770 n = group.size();
771 tree = pet_tree_new_block(ctx, 0, n);
773 for (unsigned i = 0; i < n; ++i) {
774 pet_tree *tree_i;
775 pet_loc *loc;
777 tree_i = extract(group[i]);
778 loc = construct_pet_loc(group[i]->getSourceRange(),
779 false);
780 tree_i = pet_tree_set_loc(tree_i, loc);
781 tree = pet_tree_block_add_child(tree, tree_i);
784 return tree;
787 return extract(stmt->getSingleDecl());
790 /* Construct a pet_expr representing a conditional operation.
792 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
794 pet_expr *cond, *lhs, *rhs;
796 cond = extract_expr(expr->getCond());
797 lhs = extract_expr(expr->getTrueExpr());
798 rhs = extract_expr(expr->getFalseExpr());
800 return pet_expr_new_ternary(cond, lhs, rhs);
803 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
805 return extract_expr(expr->getSubExpr());
808 /* Construct a pet_expr representing a floating point value.
810 * If the floating point literal does not appear in a macro,
811 * then we use the original representation in the source code
812 * as the string representation. Otherwise, we use the pretty
813 * printer to produce a string representation.
815 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
817 double d;
818 string s;
819 const LangOptions &LO = PP.getLangOpts();
820 SourceLocation loc = expr->getLocation();
822 if (!loc.isMacroID()) {
823 SourceManager &SM = PP.getSourceManager();
824 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
825 s = string(SM.getCharacterData(loc), len);
826 } else {
827 llvm::raw_string_ostream S(s);
828 expr->printPretty(S, 0, PrintingPolicy(LO));
829 S.str();
831 d = expr->getValueAsApproximateDouble();
832 return pet_expr_new_double(ctx, d, s.c_str());
835 /* Convert the index expression "index" into an access pet_expr of type "qt".
837 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
838 __isl_take pet_expr *index)
840 int depth;
841 int type_size;
843 depth = extract_depth(index);
844 type_size = pet_clang_get_type_size(qt, ast_context);
846 index = pet_expr_set_type_size(index, type_size);
847 index = pet_expr_access_set_depth(index, depth);
849 return index;
852 /* Extract an index expression from "expr" and then convert it into
853 * an access pet_expr.
855 * If "expr" is a reference to an enum constant, then return
856 * an integer expression instead, representing the value of the enum constant.
858 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
860 pet_expr *index;
862 index = extract_index_expr(expr);
864 if (pet_expr_get_type(index) == pet_expr_int)
865 return index;
867 return extract_access_expr(expr->getType(), index);
870 /* Extract an index expression from "decl" and then convert it into
871 * an access pet_expr.
873 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
875 return extract_access_expr(decl->getType(), extract_index_expr(decl));
878 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
880 return extract_expr(expr->getSubExpr());
883 /* Extract an assume statement from the argument "expr"
884 * of a __pencil_assume statement.
886 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
888 return pet_expr_new_unary(0, pet_op_assume, extract_expr(expr));
891 /* If "expr" is an address-of operator, then return its argument.
892 * Otherwise, return NULL.
894 static Expr *extract_addr_of_arg(Expr *expr)
896 UnaryOperator *op;
898 if (expr->getStmtClass() != Stmt::UnaryOperatorClass)
899 return NULL;
900 op = cast<UnaryOperator>(expr);
901 if (op->getOpcode() != UO_AddrOf)
902 return NULL;
903 return op->getSubExpr();
906 /* Construct a pet_expr corresponding to the function call argument "expr".
907 * The argument appears in position "pos" of a call to function "fd".
909 * If we are passing along a pointer to an array element
910 * or an entire row or even higher dimensional slice of an array,
911 * then the function being called may write into the array.
913 * We assume here that if the function is declared to take a pointer
914 * to a const type, then the function may only perform a read
915 * and that otherwise, it may either perform a read or a write (or both).
916 * We only perform this check if "detect_writes" is set.
918 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
919 Expr *expr, bool detect_writes)
921 Expr *arg;
922 pet_expr *res;
923 int is_addr = 0, is_partial = 0;
925 expr = pet_clang_strip_casts(expr);
926 arg = extract_addr_of_arg(expr);
927 if (arg) {
928 is_addr = 1;
929 expr = arg;
931 res = extract_expr(expr);
932 if (!res)
933 return NULL;
934 if (pet_clang_array_depth(expr->getType()) > 0)
935 is_partial = 1;
936 if (detect_writes && (is_addr || is_partial) &&
937 pet_expr_get_type(res) == pet_expr_access) {
938 ParmVarDecl *parm;
939 if (!fd->hasPrototype()) {
940 report_prototype_required(expr);
941 return pet_expr_free(res);
943 parm = fd->getParamDecl(pos);
944 if (!const_base(parm->getType()))
945 res = mark_may_write(res);
948 if (is_addr)
949 res = pet_expr_new_unary(0, pet_op_address_of, res);
950 return res;
953 /* Find the first FunctionDecl with the given name.
954 * "call" is the corresponding call expression and is only used
955 * for reporting errors.
957 * Return NULL on error.
959 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
961 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
962 DeclContext::decl_iterator begin = tu->decls_begin();
963 DeclContext::decl_iterator end = tu->decls_end();
964 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
965 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
966 if (!fd)
967 continue;
968 if (fd->getName().str().compare(name) != 0)
969 continue;
970 if (fd->hasBody())
971 return fd;
972 report_missing_summary_function_body(call);
973 return NULL;
975 report_missing_summary_function(call);
976 return NULL;
979 /* Return the FunctionDecl for the summary function associated to the
980 * function called by "call".
982 * In particular, if the pencil option is set, then
983 * search for an annotate attribute formatted as
984 * "pencil_access(name)", where "name" is the name of the summary function.
986 * If no summary function was specified, then return the FunctionDecl
987 * that is actually being called.
989 * Return NULL on error.
991 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
993 FunctionDecl *decl = call->getDirectCallee();
994 if (!decl)
995 return NULL;
997 if (!options->pencil)
998 return decl;
1000 specific_attr_iterator<AnnotateAttr> begin, end, i;
1001 begin = decl->specific_attr_begin<AnnotateAttr>();
1002 end = decl->specific_attr_end<AnnotateAttr>();
1003 for (i = begin; i != end; ++i) {
1004 string attr = (*i)->getAnnotation().str();
1006 const char prefix[] = "pencil_access(";
1007 size_t start = attr.find(prefix);
1008 if (start == string::npos)
1009 continue;
1010 start += strlen(prefix);
1011 string name = attr.substr(start, attr.find(')') - start);
1013 return find_decl_from_name(call, name);
1016 return decl;
1019 /* Construct a pet_expr representing a function call.
1021 * In the special case of a "call" to __pencil_assume,
1022 * construct an assume expression instead.
1024 * In the case of a "call" to __pencil_kill, the arguments
1025 * are neither read nor written (only killed), so there
1026 * is no need to check for writes to these arguments.
1028 * __pencil_assume and __pencil_kill are only recognized
1029 * when the pencil option is set.
1031 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1033 pet_expr *res = NULL;
1034 FunctionDecl *fd;
1035 string name;
1036 unsigned n_arg;
1037 bool is_kill;
1039 fd = expr->getDirectCallee();
1040 if (!fd) {
1041 unsupported(expr);
1042 return NULL;
1045 name = fd->getDeclName().getAsString();
1046 n_arg = expr->getNumArgs();
1048 if (options->pencil && n_arg == 1 && name == "__pencil_assume")
1049 return extract_assume(expr->getArg(0));
1050 is_kill = options->pencil && name == "__pencil_kill";
1052 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1053 if (!res)
1054 return NULL;
1056 for (unsigned i = 0; i < n_arg; ++i) {
1057 Expr *arg = expr->getArg(i);
1058 res = pet_expr_set_arg(res, i,
1059 PetScan::extract_argument(fd, i, arg, !is_kill));
1062 fd = get_summary_function(expr);
1063 if (!fd)
1064 return pet_expr_free(res);
1066 res = set_summary(res, fd);
1068 return res;
1071 /* Construct a pet_expr representing a (C style) cast.
1073 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1075 pet_expr *arg;
1076 QualType type;
1078 arg = extract_expr(expr->getSubExpr());
1079 if (!arg)
1080 return NULL;
1082 type = expr->getTypeAsWritten();
1083 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1086 /* Construct a pet_expr representing an integer.
1088 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1090 return pet_expr_new_int(extract_int(expr));
1093 /* Construct a pet_expr representing the integer enum constant "ecd".
1095 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
1097 isl_val *v;
1098 const llvm::APSInt &init = ecd->getInitVal();
1099 v = ::extract_int(ctx, init.isSigned(), init);
1100 return pet_expr_new_int(v);
1103 /* Try and construct a pet_expr representing "expr".
1105 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1107 switch (expr->getStmtClass()) {
1108 case Stmt::UnaryOperatorClass:
1109 return extract_expr(cast<UnaryOperator>(expr));
1110 case Stmt::CompoundAssignOperatorClass:
1111 case Stmt::BinaryOperatorClass:
1112 return extract_expr(cast<BinaryOperator>(expr));
1113 case Stmt::ImplicitCastExprClass:
1114 return extract_expr(cast<ImplicitCastExpr>(expr));
1115 case Stmt::ArraySubscriptExprClass:
1116 case Stmt::DeclRefExprClass:
1117 case Stmt::MemberExprClass:
1118 return extract_access_expr(expr);
1119 case Stmt::IntegerLiteralClass:
1120 return extract_expr(cast<IntegerLiteral>(expr));
1121 case Stmt::FloatingLiteralClass:
1122 return extract_expr(cast<FloatingLiteral>(expr));
1123 case Stmt::ParenExprClass:
1124 return extract_expr(cast<ParenExpr>(expr));
1125 case Stmt::ConditionalOperatorClass:
1126 return extract_expr(cast<ConditionalOperator>(expr));
1127 case Stmt::CallExprClass:
1128 return extract_expr(cast<CallExpr>(expr));
1129 case Stmt::CStyleCastExprClass:
1130 return extract_expr(cast<CStyleCastExpr>(expr));
1131 default:
1132 unsupported(expr);
1134 return NULL;
1137 /* Check if the given initialization statement is an assignment.
1138 * If so, return that assignment. Otherwise return NULL.
1140 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1142 BinaryOperator *ass;
1144 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1145 return NULL;
1147 ass = cast<BinaryOperator>(init);
1148 if (ass->getOpcode() != BO_Assign)
1149 return NULL;
1151 return ass;
1154 /* Check if the given initialization statement is a declaration
1155 * of a single variable.
1156 * If so, return that declaration. Otherwise return NULL.
1158 Decl *PetScan::initialization_declaration(Stmt *init)
1160 DeclStmt *decl;
1162 if (init->getStmtClass() != Stmt::DeclStmtClass)
1163 return NULL;
1165 decl = cast<DeclStmt>(init);
1167 if (!decl->isSingleDecl())
1168 return NULL;
1170 return decl->getSingleDecl();
1173 /* Given the assignment operator in the initialization of a for loop,
1174 * extract the induction variable, i.e., the (integer)variable being
1175 * assigned.
1177 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1179 Expr *lhs;
1180 DeclRefExpr *ref;
1181 ValueDecl *decl;
1182 const Type *type;
1184 lhs = init->getLHS();
1185 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1186 unsupported(init);
1187 return NULL;
1190 ref = cast<DeclRefExpr>(lhs);
1191 decl = ref->getDecl();
1192 type = decl->getType().getTypePtr();
1194 if (!type->isIntegerType()) {
1195 unsupported(lhs);
1196 return NULL;
1199 return decl;
1202 /* Given the initialization statement of a for loop and the single
1203 * declaration in this initialization statement,
1204 * extract the induction variable, i.e., the (integer) variable being
1205 * declared.
1207 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1209 VarDecl *vd;
1211 vd = cast<VarDecl>(decl);
1213 const QualType type = vd->getType();
1214 if (!type->isIntegerType()) {
1215 unsupported(init);
1216 return NULL;
1219 if (!vd->getInit()) {
1220 unsupported(init);
1221 return NULL;
1224 return vd;
1227 /* Check that op is of the form iv++ or iv--.
1228 * Return a pet_expr representing "1" or "-1" accordingly.
1230 __isl_give pet_expr *PetScan::extract_unary_increment(
1231 clang::UnaryOperator *op, clang::ValueDecl *iv)
1233 Expr *sub;
1234 DeclRefExpr *ref;
1235 isl_val *v;
1237 if (!op->isIncrementDecrementOp()) {
1238 unsupported(op);
1239 return NULL;
1242 sub = op->getSubExpr();
1243 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1244 unsupported(op);
1245 return NULL;
1248 ref = cast<DeclRefExpr>(sub);
1249 if (ref->getDecl() != iv) {
1250 unsupported(op);
1251 return NULL;
1254 if (op->isIncrementOp())
1255 v = isl_val_one(ctx);
1256 else
1257 v = isl_val_negone(ctx);
1259 return pet_expr_new_int(v);
1262 /* Check if op is of the form
1264 * iv = expr
1266 * and return the increment "expr - iv" as a pet_expr.
1268 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1269 clang::ValueDecl *iv)
1271 int type_size;
1272 Expr *lhs;
1273 DeclRefExpr *ref;
1274 pet_expr *expr, *expr_iv;
1276 if (op->getOpcode() != BO_Assign) {
1277 unsupported(op);
1278 return NULL;
1281 lhs = op->getLHS();
1282 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1283 unsupported(op);
1284 return NULL;
1287 ref = cast<DeclRefExpr>(lhs);
1288 if (ref->getDecl() != iv) {
1289 unsupported(op);
1290 return NULL;
1293 expr = extract_expr(op->getRHS());
1294 expr_iv = extract_expr(lhs);
1296 type_size = pet_clang_get_type_size(iv->getType(), ast_context);
1297 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1300 /* Check that op is of the form iv += cst or iv -= cst
1301 * and return a pet_expr corresponding to cst or -cst accordingly.
1303 __isl_give pet_expr *PetScan::extract_compound_increment(
1304 CompoundAssignOperator *op, clang::ValueDecl *iv)
1306 Expr *lhs;
1307 DeclRefExpr *ref;
1308 bool neg = false;
1309 pet_expr *expr;
1310 BinaryOperatorKind opcode;
1312 opcode = op->getOpcode();
1313 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1314 unsupported(op);
1315 return NULL;
1317 if (opcode == BO_SubAssign)
1318 neg = true;
1320 lhs = op->getLHS();
1321 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1322 unsupported(op);
1323 return NULL;
1326 ref = cast<DeclRefExpr>(lhs);
1327 if (ref->getDecl() != iv) {
1328 unsupported(op);
1329 return NULL;
1332 expr = extract_expr(op->getRHS());
1333 if (neg) {
1334 int type_size;
1335 type_size = pet_clang_get_type_size(op->getType(), ast_context);
1336 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1339 return expr;
1342 /* Check that the increment of the given for loop increments
1343 * (or decrements) the induction variable "iv" and return
1344 * the increment as a pet_expr if successful.
1346 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1347 ValueDecl *iv)
1349 Stmt *inc = stmt->getInc();
1351 if (!inc) {
1352 report_missing_increment(stmt);
1353 return NULL;
1356 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1357 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1358 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1359 return extract_compound_increment(
1360 cast<CompoundAssignOperator>(inc), iv);
1361 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1362 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1364 unsupported(inc);
1365 return NULL;
1368 /* Construct a pet_tree for a while loop.
1370 * If we were only able to extract part of the body, then simply
1371 * return that part.
1373 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1375 pet_expr *pe_cond;
1376 pet_tree *tree;
1378 tree = extract(stmt->getBody());
1379 if (partial)
1380 return tree;
1381 pe_cond = extract_expr(stmt->getCond());
1382 tree = pet_tree_new_while(pe_cond, tree);
1384 return tree;
1387 /* Construct a pet_tree for a for statement.
1388 * The for loop is required to be of one of the following forms
1390 * for (i = init; condition; ++i)
1391 * for (i = init; condition; --i)
1392 * for (i = init; condition; i += constant)
1393 * for (i = init; condition; i -= constant)
1395 * We extract a pet_tree for the body and then include it in a pet_tree
1396 * of type pet_tree_for.
1398 * As a special case, we also allow a for loop of the form
1400 * for (;;)
1402 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1404 * If we were only able to extract part of the body, then simply
1405 * return that part.
1407 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1409 BinaryOperator *ass;
1410 Decl *decl;
1411 Stmt *init;
1412 Expr *lhs, *rhs;
1413 ValueDecl *iv;
1414 pet_tree *tree;
1415 int independent;
1416 int declared;
1417 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1419 independent = is_current_stmt_marked_independent();
1421 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1422 tree = extract(stmt->getBody());
1423 if (partial)
1424 return tree;
1425 tree = pet_tree_new_infinite_loop(tree);
1426 return tree;
1429 init = stmt->getInit();
1430 if (!init) {
1431 unsupported(stmt);
1432 return NULL;
1434 if ((ass = initialization_assignment(init)) != NULL) {
1435 iv = extract_induction_variable(ass);
1436 if (!iv)
1437 return NULL;
1438 lhs = ass->getLHS();
1439 rhs = ass->getRHS();
1440 } else if ((decl = initialization_declaration(init)) != NULL) {
1441 VarDecl *var = extract_induction_variable(init, decl);
1442 if (!var)
1443 return NULL;
1444 iv = var;
1445 rhs = var->getInit();
1446 lhs = create_DeclRefExpr(var);
1447 } else {
1448 unsupported(stmt->getInit());
1449 return NULL;
1452 declared = !initialization_assignment(stmt->getInit());
1453 tree = extract(stmt->getBody());
1454 if (partial)
1455 return tree;
1456 pe_iv = extract_access_expr(iv);
1457 pe_iv = mark_write(pe_iv);
1458 pe_init = extract_expr(rhs);
1459 if (!stmt->getCond())
1460 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1461 else
1462 pe_cond = extract_expr(stmt->getCond());
1463 pe_inc = extract_increment(stmt, iv);
1464 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1465 pe_inc, tree);
1466 return tree;
1469 /* Store the names of the variables declared in decl_context
1470 * in the set declared_names. Make sure to only do this once by
1471 * setting declared_names_collected.
1473 void PetScan::collect_declared_names()
1475 DeclContext *DC = decl_context;
1476 DeclContext::decl_iterator it;
1478 if (declared_names_collected)
1479 return;
1481 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1482 Decl *D = *it;
1483 NamedDecl *named;
1485 if (!isa<NamedDecl>(D))
1486 continue;
1487 named = cast<NamedDecl>(D);
1488 declared_names.insert(named->getName().str());
1491 declared_names_collected = true;
1494 /* Add the names in "names" that are not also in this->declared_names
1495 * to this->used_names.
1496 * It is up to the caller to make sure that declared_names has been
1497 * populated, if needed.
1499 void PetScan::add_new_used_names(const std::set<std::string> &names)
1501 std::set<std::string>::const_iterator it;
1503 for (it = names.begin(); it != names.end(); ++it) {
1504 if (declared_names.find(*it) != declared_names.end())
1505 continue;
1506 used_names.insert(*it);
1510 /* Is the name "name" used in any declaration other than "decl"?
1512 * If the name was found to be in use before, the consider it to be in use.
1513 * Otherwise, check the DeclContext of the function containing the scop
1514 * as well as all ancestors of this DeclContext for declarations
1515 * other than "decl" that declare something called "name".
1517 bool PetScan::name_in_use(const string &name, Decl *decl)
1519 DeclContext *DC;
1520 DeclContext::decl_iterator it;
1522 if (used_names.find(name) != used_names.end())
1523 return true;
1525 for (DC = decl_context; DC; DC = DC->getParent()) {
1526 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1527 Decl *D = *it;
1528 NamedDecl *named;
1530 if (D == decl)
1531 continue;
1532 if (!isa<NamedDecl>(D))
1533 continue;
1534 named = cast<NamedDecl>(D);
1535 if (named->getName().str() == name)
1536 return true;
1540 return false;
1543 /* Generate a new name based on "name" that is not in use.
1544 * Do so by adding a suffix _i, with i an integer.
1546 string PetScan::generate_new_name(const string &name)
1548 string new_name;
1550 do {
1551 std::ostringstream oss;
1552 oss << name << "_" << n_rename++;
1553 new_name = oss.str();
1554 } while (name_in_use(new_name, NULL));
1556 return new_name;
1559 /* Try and construct a pet_tree corresponding to a compound statement.
1561 * "skip_declarations" is set if we should skip initial declarations
1562 * in the children of the compound statements.
1564 * Collect a new set of declarations for the current compound statement.
1565 * If any of the names in these declarations is also used by another
1566 * declaration reachable from the current function, then rename it
1567 * to a name that is not already in use.
1568 * In particular, keep track of the old and new names in a pet_substituter
1569 * and apply the substitutions to the pet_tree corresponding to the
1570 * compound statement.
1572 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1573 bool skip_declarations)
1575 pet_tree *tree;
1576 std::vector<VarDecl *> saved_declarations;
1577 std::vector<VarDecl *>::iterator it;
1578 pet_substituter substituter;
1580 saved_declarations = declarations;
1581 declarations.clear();
1582 tree = extract(stmt->children(), true, skip_declarations, stmt);
1583 for (it = declarations.begin(); it != declarations.end(); ++it) {
1584 isl_id *id;
1585 pet_expr *expr;
1586 VarDecl *decl = *it;
1587 string name = decl->getName().str();
1588 bool in_use = name_in_use(name, decl);
1590 used_names.insert(name);
1591 if (!in_use)
1592 continue;
1594 name = generate_new_name(name);
1595 id = pet_id_from_name_and_decl(ctx, name.c_str(), decl);
1596 expr = pet_id_create_index_expr(id);
1597 expr = extract_access_expr(decl->getType(), expr);
1598 id = pet_id_from_decl(ctx, decl);
1599 substituter.add_sub(id, expr);
1600 used_names.insert(name);
1602 tree = substituter.substitute(tree);
1603 declarations = saved_declarations;
1605 return tree;
1608 /* Return the file offset of the expansion location of "Loc".
1610 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1612 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1615 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1617 /* Return a SourceLocation for the location after the first semicolon
1618 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1619 * call it and also skip trailing spaces and newline.
1621 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1622 const LangOptions &LO)
1624 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1627 #else
1629 /* Return a SourceLocation for the location after the first semicolon
1630 * after "loc". If Lexer::findLocationAfterToken is not available,
1631 * we look in the underlying character data for the first semicolon.
1633 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1634 const LangOptions &LO)
1636 const char *semi;
1637 const char *s = SM.getCharacterData(loc);
1639 semi = strchr(s, ';');
1640 if (!semi)
1641 return SourceLocation();
1642 return loc.getFileLocWithOffset(semi + 1 - s);
1645 #endif
1647 /* If the token at "loc" is the first token on the line, then return
1648 * a location referring to the start of the line and set *indent
1649 * to the indentation of "loc"
1650 * Otherwise, return "loc" and set *indent to "".
1652 * This function is used to extend a scop to the start of the line
1653 * if the first token of the scop is also the first token on the line.
1655 * We look for the first token on the line. If its location is equal to "loc",
1656 * then the latter is the location of the first token on the line.
1658 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1659 SourceManager &SM, const LangOptions &LO, char **indent)
1661 std::pair<FileID, unsigned> file_offset_pair;
1662 llvm::StringRef file;
1663 const char *pos;
1664 Token tok;
1665 SourceLocation token_loc, line_loc;
1666 int col;
1667 const char *s;
1669 loc = SM.getExpansionLoc(loc);
1670 col = SM.getExpansionColumnNumber(loc);
1671 line_loc = loc.getLocWithOffset(1 - col);
1672 file_offset_pair = SM.getDecomposedLoc(line_loc);
1673 file = SM.getBufferData(file_offset_pair.first, NULL);
1674 pos = file.data() + file_offset_pair.second;
1676 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1677 file.begin(), pos, file.end());
1678 lexer.LexFromRawLexer(tok);
1679 token_loc = tok.getLocation();
1681 s = SM.getCharacterData(line_loc);
1682 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1684 if (token_loc == loc)
1685 return line_loc;
1686 else
1687 return loc;
1690 /* Construct a pet_loc corresponding to the region covered by "range".
1691 * If "skip_semi" is set, then we assume "range" is followed by
1692 * a semicolon and also include this semicolon.
1694 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1695 bool skip_semi)
1697 SourceLocation loc = range.getBegin();
1698 SourceManager &SM = PP.getSourceManager();
1699 const LangOptions &LO = PP.getLangOpts();
1700 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1701 unsigned start, end;
1702 char *indent;
1704 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1705 start = getExpansionOffset(SM, loc);
1706 loc = range.getEnd();
1707 if (skip_semi)
1708 loc = location_after_semi(loc, SM, LO);
1709 else
1710 loc = PP.getLocForEndOfToken(loc);
1711 end = getExpansionOffset(SM, loc);
1713 return pet_loc_alloc(ctx, start, end, line, indent);
1716 /* Convert a top-level pet_expr to an expression pet_tree.
1718 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1719 SourceRange range, bool skip_semi)
1721 pet_loc *loc;
1722 pet_tree *tree;
1724 tree = pet_tree_new_expr(expr);
1725 loc = construct_pet_loc(range, skip_semi);
1726 tree = pet_tree_set_loc(tree, loc);
1728 return tree;
1731 /* Construct a pet_tree for an if statement.
1733 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1735 pet_expr *pe_cond;
1736 pet_tree *tree, *tree_else;
1738 pe_cond = extract_expr(stmt->getCond());
1739 tree = extract(stmt->getThen());
1740 if (stmt->getElse()) {
1741 tree_else = extract(stmt->getElse());
1742 if (options->autodetect) {
1743 if (tree && !tree_else) {
1744 partial = true;
1745 pet_expr_free(pe_cond);
1746 return tree;
1748 if (!tree && tree_else) {
1749 partial = true;
1750 pet_expr_free(pe_cond);
1751 return tree_else;
1754 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1755 } else
1756 tree = pet_tree_new_if(pe_cond, tree);
1757 return tree;
1760 /* Try and construct a pet_tree for a label statement.
1762 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1764 isl_id *label;
1765 pet_tree *tree;
1767 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1769 tree = extract(stmt->getSubStmt());
1770 tree = pet_tree_set_label(tree, label);
1771 return tree;
1774 /* Update the location of "tree" to include the source range of "stmt".
1776 * Actually, we create a new location based on the source range of "stmt" and
1777 * then extend this new location to include the region of the original location.
1778 * This ensures that the line number of the final location refers to "stmt".
1780 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1782 pet_loc *loc, *tree_loc;
1784 tree_loc = pet_tree_get_loc(tree);
1785 loc = construct_pet_loc(stmt->getSourceRange(), false);
1786 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1787 pet_loc_free(tree_loc);
1789 tree = pet_tree_set_loc(tree, loc);
1790 return tree;
1793 /* Is "expr" of a type that can be converted to an access expression?
1795 static bool is_access_expr_type(Expr *expr)
1797 switch (expr->getStmtClass()) {
1798 case Stmt::ArraySubscriptExprClass:
1799 case Stmt::DeclRefExprClass:
1800 case Stmt::MemberExprClass:
1801 return true;
1802 default:
1803 return false;
1807 /* Tell the pet_inliner "inliner" about the formal arguments
1808 * in "fd" and the corresponding actual arguments in "call".
1809 * Return 0 if this was successful and -1 otherwise.
1811 * Any pointer argument is treated as an array.
1812 * The other arguments are treated as scalars.
1814 * In case of scalars, there is no restriction on the actual argument.
1815 * This actual argument is assigned to a variable with a name
1816 * that is derived from the name of the corresponding formal argument,
1817 * but made not to conflict with any variable names that are
1818 * already in use.
1820 * In case of arrays, the actual argument needs to be an expression
1821 * of a type that can be converted to an access expression or the address
1822 * of such an expression, ignoring implicit and redundant casts.
1824 int PetScan::set_inliner_arguments(pet_inliner &inliner, CallExpr *call,
1825 FunctionDecl *fd)
1827 unsigned n;
1829 n = fd->getNumParams();
1830 for (unsigned i = 0; i < n; ++i) {
1831 ParmVarDecl *parm = fd->getParamDecl(i);
1832 QualType type = parm->getType();
1833 Expr *arg, *sub;
1834 pet_expr *expr;
1835 int is_addr = 0;
1837 arg = call->getArg(i);
1838 if (pet_clang_array_depth(type) == 0) {
1839 string name = parm->getName().str();
1840 if (name_in_use(name, NULL))
1841 name = generate_new_name(name);
1842 inliner.add_scalar_arg(parm, name, extract_expr(arg));
1843 continue;
1845 arg = pet_clang_strip_casts(arg);
1846 sub = extract_addr_of_arg(arg);
1847 if (sub) {
1848 is_addr = 1;
1849 arg = pet_clang_strip_casts(sub);
1851 if (!is_access_expr_type(arg)) {
1852 report_unsupported_inline_function_argument(arg);
1853 return -1;
1855 expr = extract_access_expr(arg);
1856 if (!expr)
1857 return -1;
1858 inliner.add_array_arg(parm, expr, is_addr);
1861 return 0;
1864 /* Try and construct a pet_tree from the body of "fd" using the actual
1865 * arguments in "call" in place of the formal arguments.
1866 * "fd" is assumed to point to the declaration with a function body.
1867 * In particular, construct a block that consists of assignments
1868 * of (parts of) the actual arguments to temporary variables
1869 * followed by the inlined function body with the formal arguments
1870 * replaced by (expressions containing) these temporary variables.
1872 * The actual inlining is taken care of by the pet_inliner function.
1873 * This function merely calls set_inliner_arguments to tell
1874 * the pet_inliner about the actual arguments, extracts a pet_tree
1875 * from the body of the called function and then passes this pet_tree
1876 * to the pet_inliner.
1878 * During the extraction of the function body, all variables names
1879 * that are declared in the calling function as well all variable
1880 * names that are known to be in use are considered to be in use
1881 * in the called function to ensure that there is no naming conflict.
1882 * Similarly, the additional names that are in use in the called function
1883 * are considered to be in use in the calling function as well.
1885 * The location of the pet_tree is reset to the call site to ensure
1886 * that the extent of the scop does not include the body of the called
1887 * function.
1889 __isl_give pet_tree *PetScan::extract_inlined_call(CallExpr *call,
1890 FunctionDecl *fd)
1892 int save_autodetect;
1893 pet_tree *tree;
1894 pet_loc *tree_loc;
1895 pet_inliner inliner(ctx, n_arg, ast_context);
1897 if (set_inliner_arguments(inliner, call, fd) < 0)
1898 return NULL;
1900 save_autodetect = options->autodetect;
1901 options->autodetect = 0;
1902 PetScan body_scan(PP, ast_context, fd, loc, options,
1903 isl_union_map_copy(value_bounds), independent);
1904 collect_declared_names();
1905 body_scan.add_new_used_names(declared_names);
1906 body_scan.add_new_used_names(used_names);
1907 tree = body_scan.extract(fd->getBody(), false);
1908 add_new_used_names(body_scan.used_names);
1909 options->autodetect = save_autodetect;
1911 tree_loc = construct_pet_loc(call->getSourceRange(), true);
1912 tree = pet_tree_set_loc(tree, tree_loc);
1914 return inliner.inline_tree(tree);
1917 /* Try and construct a pet_tree corresponding
1918 * to the expression statement "stmt".
1920 * If the outer expression is a function call and if the corresponding
1921 * function body is marked "inline", then return a pet_tree
1922 * corresponding to the inlined function.
1924 __isl_give pet_tree *PetScan::extract_expr_stmt(Stmt *stmt)
1926 pet_expr *expr;
1928 if (stmt->getStmtClass() == Stmt::CallExprClass) {
1929 CallExpr *call = cast<CallExpr>(stmt);
1930 FunctionDecl *fd = call->getDirectCallee();
1931 fd = pet_clang_find_function_decl_with_body(fd);
1932 if (fd && fd->isInlineSpecified())
1933 return extract_inlined_call(call, fd);
1936 expr = extract_expr(cast<Expr>(stmt));
1937 return extract(expr, stmt->getSourceRange(), true);
1940 /* Try and construct a pet_tree corresponding to "stmt".
1942 * If "stmt" is a compound statement, then "skip_declarations"
1943 * indicates whether we should skip initial declarations in the
1944 * compound statement.
1946 * If the constructed pet_tree is not a (possibly) partial representation
1947 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1948 * In particular, if skip_declarations is set, then we may have skipped
1949 * declarations inside "stmt" and so the pet_scop may not represent
1950 * the entire "stmt".
1951 * Note that this function may be called with "stmt" referring to the entire
1952 * body of the function, including the outer braces. In such cases,
1953 * skip_declarations will be set and the braces will not be taken into
1954 * account in tree->loc.
1956 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
1958 pet_tree *tree;
1960 set_current_stmt(stmt);
1962 if (isa<Expr>(stmt))
1963 return extract_expr_stmt(cast<Expr>(stmt));
1965 switch (stmt->getStmtClass()) {
1966 case Stmt::WhileStmtClass:
1967 tree = extract(cast<WhileStmt>(stmt));
1968 break;
1969 case Stmt::ForStmtClass:
1970 tree = extract_for(cast<ForStmt>(stmt));
1971 break;
1972 case Stmt::IfStmtClass:
1973 tree = extract(cast<IfStmt>(stmt));
1974 break;
1975 case Stmt::CompoundStmtClass:
1976 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
1977 break;
1978 case Stmt::LabelStmtClass:
1979 tree = extract(cast<LabelStmt>(stmt));
1980 break;
1981 case Stmt::ContinueStmtClass:
1982 tree = pet_tree_new_continue(ctx);
1983 break;
1984 case Stmt::BreakStmtClass:
1985 tree = pet_tree_new_break(ctx);
1986 break;
1987 case Stmt::DeclStmtClass:
1988 tree = extract(cast<DeclStmt>(stmt));
1989 break;
1990 default:
1991 report_unsupported_statement_type(stmt);
1992 return NULL;
1995 if (partial || skip_declarations)
1996 return tree;
1998 return update_loc(tree, stmt);
2001 /* Given a sequence of statements "stmt_range" of which the first "n_decl"
2002 * are declarations and of which the remaining statements are represented
2003 * by "tree", try and extend "tree" to include the last sequence of
2004 * the initial declarations that can be completely extracted.
2006 * We start collecting the initial declarations and start over
2007 * whenever we come across a declaration that we cannot extract.
2008 * If we have been able to extract any declarations, then we
2009 * copy over the contents of "tree" at the end of the declarations.
2010 * Otherwise, we simply return the original "tree".
2012 __isl_give pet_tree *PetScan::insert_initial_declarations(
2013 __isl_take pet_tree *tree, int n_decl, StmtRange stmt_range)
2015 StmtIterator i;
2016 pet_tree *res;
2017 int n_stmt;
2018 int is_block;
2019 int j;
2021 n_stmt = pet_tree_block_n_child(tree);
2022 is_block = pet_tree_block_get_block(tree);
2023 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2025 for (i = stmt_range.first; n_decl; ++i, --n_decl) {
2026 Stmt *child = *i;
2027 pet_tree *tree_i;
2029 tree_i = extract(child);
2030 if (tree_i && !partial) {
2031 res = pet_tree_block_add_child(res, tree_i);
2032 continue;
2034 pet_tree_free(tree_i);
2035 partial = false;
2036 if (pet_tree_block_n_child(res) == 0)
2037 continue;
2038 pet_tree_free(res);
2039 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2042 if (pet_tree_block_n_child(res) == 0) {
2043 pet_tree_free(res);
2044 return tree;
2047 for (j = 0; j < n_stmt; ++j) {
2048 pet_tree *tree_i;
2050 tree_i = pet_tree_block_get_child(tree, j);
2051 res = pet_tree_block_add_child(res, tree_i);
2053 pet_tree_free(tree);
2055 return res;
2058 /* Try and construct a pet_tree corresponding to (part of)
2059 * a sequence of statements.
2061 * "block" is set if the sequence represents the children of
2062 * a compound statement.
2063 * "skip_declarations" is set if we should skip initial declarations
2064 * in the sequence of statements.
2065 * "parent" is the statement that has stmt_range as (some of) its children.
2067 * If autodetect is set, then we allow the extraction of only a subrange
2068 * of the sequence of statements. However, if there is at least one
2069 * kill and there is some subsequent statement for which we could not
2070 * construct a tree, then turn off the "block" property of the tree
2071 * such that no extra kill will be introduced at the end of the (partial)
2072 * block. If, on the other hand, the final range contains
2073 * no statements, then we discard the entire range.
2074 * If only a subrange of the sequence was extracted, but each statement
2075 * in the sequence was extracted completely, and if there are some
2076 * variable declarations in the sequence before or inside
2077 * the extracted subrange, then check if any of these variables are
2078 * not used after the extracted subrange. If so, add kills to these
2079 * variables.
2081 * If the entire range was extracted, apart from some initial declarations,
2082 * then we try and extend the range with the latest of those initial
2083 * declarations.
2085 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
2086 bool skip_declarations, Stmt *parent)
2088 StmtIterator i;
2089 int j, skip;
2090 bool has_kills = false;
2091 bool partial_range = false;
2092 bool outer_partial = false;
2093 pet_tree *tree;
2094 SourceManager &SM = PP.getSourceManager();
2095 pet_killed_locals kl(SM);
2096 unsigned range_start, range_end;
2098 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
2101 tree = pet_tree_new_block(ctx, block, j);
2103 skip = 0;
2104 i = stmt_range.first;
2105 if (skip_declarations)
2106 for (; i != stmt_range.second; ++i) {
2107 if ((*i)->getStmtClass() != Stmt::DeclStmtClass)
2108 break;
2109 if (options->autodetect)
2110 kl.add_locals(cast<DeclStmt>(*i));
2111 ++skip;
2114 for (; i != stmt_range.second; ++i) {
2115 Stmt *child = *i;
2116 pet_tree *tree_i;
2118 tree_i = extract(child);
2119 if (pet_tree_block_n_child(tree) != 0 && partial) {
2120 pet_tree_free(tree_i);
2121 break;
2123 if (child->getStmtClass() == Stmt::DeclStmtClass) {
2124 if (options->autodetect)
2125 kl.add_locals(cast<DeclStmt>(child));
2126 if (tree_i && block)
2127 has_kills = true;
2129 if (options->autodetect) {
2130 if (tree_i) {
2131 range_end = getExpansionOffset(SM,
2132 child->getLocEnd());
2133 if (pet_tree_block_n_child(tree) == 0)
2134 range_start = getExpansionOffset(SM,
2135 child->getLocStart());
2136 tree = pet_tree_block_add_child(tree, tree_i);
2137 } else {
2138 partial_range = true;
2140 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
2141 outer_partial = partial = true;
2142 } else {
2143 tree = pet_tree_block_add_child(tree, tree_i);
2146 if (partial || !tree)
2147 break;
2150 if (!tree)
2151 return NULL;
2153 if (partial) {
2154 if (has_kills)
2155 tree = pet_tree_block_set_block(tree, 0);
2156 if (outer_partial) {
2157 kl.remove_accessed_after(parent,
2158 range_start, range_end);
2159 tree = add_kills(tree, kl.locals);
2161 } else if (partial_range) {
2162 if (pet_tree_block_n_child(tree) == 0) {
2163 pet_tree_free(tree);
2164 return NULL;
2166 partial = true;
2167 } else if (skip > 0)
2168 tree = insert_initial_declarations(tree, skip, stmt_range);
2170 return tree;
2173 extern "C" {
2174 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2175 void *user);
2176 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2177 __isl_keep pet_context *pc, void *user);
2180 /* Construct a pet_expr that holds the sizes of the array accessed
2181 * by "access".
2182 * This function is used as a callback to pet_context_add_parameters,
2183 * which is also passed a pointer to the PetScan object.
2185 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2186 void *user)
2188 PetScan *ps = (PetScan *) user;
2189 isl_id *id;
2190 QualType qt;
2192 id = pet_expr_access_get_id(access);
2193 qt = pet_id_get_array_type(id);
2194 isl_id_free(id);
2195 return ps->get_array_size(qt);
2198 /* Construct and return a pet_array corresponding to the variable
2199 * accessed by "access".
2200 * This function is used as a callback to pet_scop_from_pet_tree,
2201 * which is also passed a pointer to the PetScan object.
2203 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2204 __isl_keep pet_context *pc, void *user)
2206 PetScan *ps = (PetScan *) user;
2207 isl_ctx *ctx;
2208 isl_id *id;
2209 pet_array *array;
2211 ctx = pet_expr_get_ctx(access);
2212 id = pet_expr_access_get_id(access);
2213 array = ps->extract_array(id, NULL, pc);
2214 isl_id_free(id);
2216 return array;
2219 /* Extract a function summary from the body of "fd".
2221 * We extract a scop from the function body in a context with as
2222 * parameters the integer arguments of the function.
2223 * We turn off autodetection (in case it was set) to ensure that
2224 * the entire function body is considered.
2225 * We then collect the accessed array elements and attach them
2226 * to the corresponding array arguments, taking into account
2227 * that the function body may access members of array elements.
2229 * The reason for representing the integer arguments as parameters in
2230 * the context is that if we were to instead start with a context
2231 * with the function arguments as initial dimensions, then we would not
2232 * be able to refer to them from the array extents, without turning
2233 * array extents into maps.
2235 * The result is stored in the summary_cache cache so that we can reuse
2236 * it if this method gets called on the same function again later on.
2238 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
2240 isl_space *space;
2241 isl_set *domain;
2242 pet_context *pc;
2243 pet_tree *tree;
2244 pet_function_summary *summary;
2245 unsigned n;
2246 ScopLoc loc;
2247 int save_autodetect;
2248 struct pet_scop *scop;
2249 int int_size;
2250 isl_union_set *may_read, *may_write, *must_write;
2251 isl_union_map *to_inner;
2253 if (summary_cache.find(fd) != summary_cache.end())
2254 return pet_function_summary_copy(summary_cache[fd]);
2256 space = isl_space_set_alloc(ctx, 0, 0);
2258 n = fd->getNumParams();
2259 summary = pet_function_summary_alloc(ctx, n);
2260 for (unsigned i = 0; i < n; ++i) {
2261 ParmVarDecl *parm = fd->getParamDecl(i);
2262 QualType type = parm->getType();
2263 isl_id *id;
2265 if (!type->isIntegerType())
2266 continue;
2267 id = pet_id_from_decl(ctx, parm);
2268 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
2269 space = isl_space_set_dim_id(space, isl_dim_param, 0,
2270 isl_id_copy(id));
2271 summary = pet_function_summary_set_int(summary, i, id);
2274 save_autodetect = options->autodetect;
2275 options->autodetect = 0;
2276 PetScan body_scan(PP, ast_context, fd, loc, options,
2277 isl_union_map_copy(value_bounds), independent);
2279 tree = body_scan.extract(fd->getBody(), false);
2281 domain = isl_set_universe(space);
2282 pc = pet_context_alloc(domain);
2283 pc = pet_context_add_parameters(pc, tree,
2284 &::get_array_size, &body_scan);
2285 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2286 scop = pet_scop_from_pet_tree(tree, int_size,
2287 &::extract_array, &body_scan, pc);
2288 scop = scan_arrays(scop, pc);
2289 may_read = isl_union_map_range(pet_scop_get_may_reads(scop));
2290 may_write = isl_union_map_range(pet_scop_get_may_writes(scop));
2291 must_write = isl_union_map_range(pet_scop_get_must_writes(scop));
2292 to_inner = pet_scop_compute_outer_to_inner(scop);
2293 pet_scop_free(scop);
2295 for (unsigned i = 0; i < n; ++i) {
2296 ParmVarDecl *parm = fd->getParamDecl(i);
2297 QualType type = parm->getType();
2298 struct pet_array *array;
2299 isl_space *space;
2300 isl_union_set *data_set;
2301 isl_union_set *may_read_i, *may_write_i, *must_write_i;
2303 if (pet_clang_array_depth(type) == 0)
2304 continue;
2306 array = body_scan.extract_array(parm, NULL, pc);
2307 space = array ? isl_set_get_space(array->extent) : NULL;
2308 pet_array_free(array);
2309 data_set = isl_union_set_from_set(isl_set_universe(space));
2310 data_set = isl_union_set_apply(data_set,
2311 isl_union_map_copy(to_inner));
2312 may_read_i = isl_union_set_intersect(
2313 isl_union_set_copy(may_read),
2314 isl_union_set_copy(data_set));
2315 may_write_i = isl_union_set_intersect(
2316 isl_union_set_copy(may_write),
2317 isl_union_set_copy(data_set));
2318 must_write_i = isl_union_set_intersect(
2319 isl_union_set_copy(must_write), data_set);
2320 summary = pet_function_summary_set_array(summary, i,
2321 may_read_i, may_write_i, must_write_i);
2324 isl_union_set_free(may_read);
2325 isl_union_set_free(may_write);
2326 isl_union_set_free(must_write);
2327 isl_union_map_free(to_inner);
2329 options->autodetect = save_autodetect;
2330 pet_context_free(pc);
2332 summary_cache[fd] = pet_function_summary_copy(summary);
2334 return summary;
2337 /* If "fd" has a function body, then extract a function summary from
2338 * this body and attach it to the call expression "expr".
2340 * Even if a function body is available, "fd" itself may point
2341 * to a declaration without function body. We therefore first
2342 * replace it by the declaration that comes with a body (if any).
2344 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
2345 FunctionDecl *fd)
2347 pet_function_summary *summary;
2349 if (!expr)
2350 return NULL;
2351 fd = pet_clang_find_function_decl_with_body(fd);
2352 if (!fd)
2353 return expr;
2355 summary = get_summary(fd);
2357 expr = pet_expr_call_set_summary(expr, summary);
2359 return expr;
2362 /* Extract a pet_scop from "tree".
2364 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
2365 * then add pet_arrays for all accessed arrays.
2366 * We populate the pet_context with assignments for all parameters used
2367 * inside "tree" or any of the size expressions for the arrays accessed
2368 * by "tree" so that they can be used in affine expressions.
2370 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
2372 int int_size;
2373 isl_set *domain;
2374 pet_context *pc;
2375 pet_scop *scop;
2377 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2379 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2380 pc = pet_context_alloc(domain);
2381 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
2382 scop = pet_scop_from_pet_tree(tree, int_size,
2383 &::extract_array, this, pc);
2384 scop = scan_arrays(scop, pc);
2385 pet_context_free(pc);
2387 return scop;
2390 /* Add a call to __pencil_kill to the end of "tree" that kills
2391 * all the variables in "locals" and return the result.
2393 * No location is added to the kill because the most natural
2394 * location would lie outside the scop. Attaching such a location
2395 * to this tree would extend the scope of the final result
2396 * to include the location.
2398 __isl_give pet_tree *PetScan::add_kills(__isl_take pet_tree *tree,
2399 set<ValueDecl *> locals)
2401 int i;
2402 pet_expr *expr;
2403 pet_tree *kill, *block;
2404 set<ValueDecl *>::iterator it;
2406 if (locals.size() == 0)
2407 return tree;
2408 expr = pet_expr_new_call(ctx, "__pencil_kill", locals.size());
2409 i = 0;
2410 for (it = locals.begin(); it != locals.end(); ++it) {
2411 pet_expr *arg;
2412 arg = extract_access_expr(*it);
2413 expr = pet_expr_set_arg(expr, i++, arg);
2415 kill = pet_tree_new_expr(expr);
2416 block = pet_tree_new_block(ctx, 0, 2);
2417 block = pet_tree_block_add_child(block, tree);
2418 block = pet_tree_block_add_child(block, kill);
2420 return block;
2423 /* Check if the scop marked by the user is exactly this Stmt
2424 * or part of this Stmt.
2425 * If so, return a pet_scop corresponding to the marked region.
2426 * Otherwise, return NULL.
2428 * If the scop is not further nested inside a child of "stmt",
2429 * then check if there are any variable declarations before the scop
2430 * inside "stmt". If so, and if these variables are not used
2431 * after the scop, then add kills to the variables.
2433 struct pet_scop *PetScan::scan(Stmt *stmt)
2435 SourceManager &SM = PP.getSourceManager();
2436 unsigned start_off, end_off;
2437 pet_tree *tree;
2439 start_off = getExpansionOffset(SM, stmt->getLocStart());
2440 end_off = getExpansionOffset(SM, stmt->getLocEnd());
2442 if (start_off > loc.end)
2443 return NULL;
2444 if (end_off < loc.start)
2445 return NULL;
2447 if (start_off >= loc.start && end_off <= loc.end)
2448 return extract_scop(extract(stmt));
2450 pet_killed_locals kl(SM);
2451 StmtIterator start;
2452 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
2453 Stmt *child = *start;
2454 if (!child)
2455 continue;
2456 start_off = getExpansionOffset(SM, child->getLocStart());
2457 end_off = getExpansionOffset(SM, child->getLocEnd());
2458 if (start_off < loc.start && end_off >= loc.end)
2459 return scan(child);
2460 if (start_off >= loc.start)
2461 break;
2462 if (isa<DeclStmt>(child))
2463 kl.add_locals(cast<DeclStmt>(child));
2466 StmtIterator end;
2467 for (end = start; end != stmt->child_end(); ++end) {
2468 Stmt *child = *end;
2469 start_off = SM.getFileOffset(child->getLocStart());
2470 if (start_off >= loc.end)
2471 break;
2474 kl.remove_accessed_after(stmt, loc.start, loc.end);
2476 tree = extract(StmtRange(start, end), false, false, stmt);
2477 tree = add_kills(tree, kl.locals);
2478 return extract_scop(tree);
2481 /* Set the size of index "pos" of "array" to "size".
2482 * In particular, add a constraint of the form
2484 * i_pos < size
2486 * to array->extent and a constraint of the form
2488 * size >= 0
2490 * to array->context.
2492 * The domain of "size" is assumed to be zero-dimensional.
2494 static struct pet_array *update_size(struct pet_array *array, int pos,
2495 __isl_take isl_pw_aff *size)
2497 isl_set *valid;
2498 isl_set *univ;
2499 isl_set *bound;
2500 isl_space *dim;
2501 isl_aff *aff;
2502 isl_pw_aff *index;
2503 isl_id *id;
2505 if (!array)
2506 goto error;
2508 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2509 array->context = isl_set_intersect(array->context, valid);
2511 dim = isl_set_get_space(array->extent);
2512 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2513 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2514 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2515 index = isl_pw_aff_alloc(univ, aff);
2517 size = isl_pw_aff_add_dims(size, isl_dim_in,
2518 isl_set_dim(array->extent, isl_dim_set));
2519 id = isl_set_get_tuple_id(array->extent);
2520 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2521 bound = isl_pw_aff_lt_set(index, size);
2523 array->extent = isl_set_intersect(array->extent, bound);
2525 if (!array->context || !array->extent)
2526 return pet_array_free(array);
2528 return array;
2529 error:
2530 isl_pw_aff_free(size);
2531 return NULL;
2534 #ifdef HAVE_DECAYEDTYPE
2536 /* If "qt" is a decayed type, then set *decayed to true and
2537 * return the original type.
2539 static QualType undecay(QualType qt, bool *decayed)
2541 const Type *type = qt.getTypePtr();
2543 *decayed = isa<DecayedType>(type);
2544 if (*decayed)
2545 qt = cast<DecayedType>(type)->getOriginalType();
2546 return qt;
2549 #else
2551 /* If "qt" is a decayed type, then set *decayed to true and
2552 * return the original type.
2553 * Since this version of clang does not define a DecayedType,
2554 * we cannot obtain the original type even if it had been decayed and
2555 * we set *decayed to false.
2557 static QualType undecay(QualType qt, bool *decayed)
2559 *decayed = false;
2560 return qt;
2563 #endif
2565 /* Figure out the size of the array at position "pos" and all
2566 * subsequent positions from "qt" and update the corresponding
2567 * argument of "expr" accordingly.
2569 * The initial type (when pos is zero) may be a pointer type decayed
2570 * from an array type, if this initial type is the type of a function
2571 * argument. This only happens if the original array type has
2572 * a constant size in the outer dimension as otherwise we get
2573 * a VariableArrayType. Try and obtain this original type (if available) and
2574 * take the outer array size into account if it was marked static.
2576 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2577 QualType qt, int pos)
2579 const ArrayType *atype;
2580 pet_expr *size;
2581 bool decayed = false;
2583 if (!expr)
2584 return NULL;
2586 if (pos == 0)
2587 qt = undecay(qt, &decayed);
2589 if (qt->isPointerType()) {
2590 qt = qt->getPointeeType();
2591 return set_upper_bounds(expr, qt, pos + 1);
2593 if (!qt->isArrayType())
2594 return expr;
2596 qt = qt->getCanonicalTypeInternal();
2597 atype = cast<ArrayType>(qt.getTypePtr());
2599 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2600 qt = atype->getElementType();
2601 return set_upper_bounds(expr, qt, pos + 1);
2604 if (qt->isConstantArrayType()) {
2605 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2606 size = extract_expr(ca->getSize());
2607 expr = pet_expr_set_arg(expr, pos, size);
2608 } else if (qt->isVariableArrayType()) {
2609 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2610 size = extract_expr(vla->getSizeExpr());
2611 expr = pet_expr_set_arg(expr, pos, size);
2614 qt = atype->getElementType();
2616 return set_upper_bounds(expr, qt, pos + 1);
2619 /* Construct a pet_expr that holds the sizes of an array of the given type.
2620 * The returned expression is a call expression with as arguments
2621 * the sizes in each dimension. If we are unable to derive the size
2622 * in a given dimension, then the corresponding argument is set to infinity.
2623 * In fact, we initialize all arguments to infinity and then update
2624 * them if we are able to figure out the size.
2626 * The result is stored in the type_size cache so that we can reuse
2627 * it if this method gets called on the same type again later on.
2629 __isl_give pet_expr *PetScan::get_array_size(QualType qt)
2631 int depth;
2632 pet_expr *expr, *inf;
2633 const Type *type = qt.getTypePtr();
2635 if (type_size.find(type) != type_size.end())
2636 return pet_expr_copy(type_size[type]);
2638 depth = pet_clang_array_depth(qt);
2639 inf = pet_expr_new_int(isl_val_infty(ctx));
2640 expr = pet_expr_new_call(ctx, "bounds", depth);
2641 for (int i = 0; i < depth; ++i)
2642 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2643 pet_expr_free(inf);
2645 expr = set_upper_bounds(expr, qt, 0);
2646 type_size[type] = pet_expr_copy(expr);
2648 return expr;
2651 /* Does "expr" represent the "integer" infinity?
2653 static int is_infty(__isl_keep pet_expr *expr)
2655 isl_val *v;
2656 int res;
2658 if (pet_expr_get_type(expr) != pet_expr_int)
2659 return 0;
2660 v = pet_expr_int_get_val(expr);
2661 res = isl_val_is_infty(v);
2662 isl_val_free(v);
2664 return res;
2667 /* Figure out the dimensions of an array "array" based on its type
2668 * "qt" and update "array" accordingly.
2670 * We first construct a pet_expr that holds the sizes of the array
2671 * in each dimension. The resulting expression may containing
2672 * infinity values for dimension where we are unable to derive
2673 * a size expression.
2675 * The arguments of the size expression that have a value different from
2676 * infinity are then converted to an affine expression
2677 * within the context "pc" and incorporated into the size of "array".
2678 * If we are unable to convert a size expression to an affine expression or
2679 * if the size is not a (symbolic) constant,
2680 * then we leave the corresponding size of "array" untouched.
2682 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2683 QualType qt, __isl_keep pet_context *pc)
2685 int n;
2686 pet_expr *expr;
2688 if (!array)
2689 return NULL;
2691 expr = get_array_size(qt);
2693 n = pet_expr_get_n_arg(expr);
2694 for (int i = 0; i < n; ++i) {
2695 pet_expr *arg;
2696 isl_pw_aff *size;
2698 arg = pet_expr_get_arg(expr, i);
2699 if (!is_infty(arg)) {
2700 int dim;
2702 size = pet_expr_extract_affine(arg, pc);
2703 dim = isl_pw_aff_dim(size, isl_dim_in);
2704 if (!size)
2705 array = pet_array_free(array);
2706 else if (isl_pw_aff_involves_nan(size) ||
2707 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2708 isl_pw_aff_free(size);
2709 else {
2710 size = isl_pw_aff_drop_dims(size,
2711 isl_dim_in, 0, dim);
2712 array = update_size(array, i, size);
2715 pet_expr_free(arg);
2717 pet_expr_free(expr);
2719 return array;
2722 /* Does "decl" have a definition that we can keep track of in a pet_type?
2724 static bool has_printable_definition(RecordDecl *decl)
2726 if (!decl->getDeclName())
2727 return false;
2728 return decl->getLexicalDeclContext() == decl->getDeclContext();
2731 /* Construct and return a pet_array corresponding to the variable
2732 * represented by "id".
2733 * In particular, initialize array->extent to
2735 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2737 * and then call set_upper_bounds to set the upper bounds on the indices
2738 * based on the type of the variable. The upper bounds are converted
2739 * to affine expressions within the context "pc".
2741 * If the base type is that of a record with a top-level definition or
2742 * of a typedef and if "types" is not null, then the RecordDecl or
2743 * TypedefType corresponding to the type
2744 * is added to "types".
2746 * If the base type is that of a record with no top-level definition,
2747 * then we replace it by "<subfield>".
2749 struct pet_array *PetScan::extract_array(__isl_keep isl_id *id,
2750 PetTypes *types, __isl_keep pet_context *pc)
2752 struct pet_array *array;
2753 QualType qt = pet_id_get_array_type(id);
2754 int depth = pet_clang_array_depth(qt);
2755 QualType base = pet_clang_base_type(qt);
2756 string name;
2757 isl_space *space;
2759 array = isl_calloc_type(ctx, struct pet_array);
2760 if (!array)
2761 return NULL;
2763 space = isl_space_set_alloc(ctx, 0, depth);
2764 space = isl_space_set_tuple_id(space, isl_dim_set, isl_id_copy(id));
2766 array->extent = isl_set_nat_universe(space);
2768 space = isl_space_params_alloc(ctx, 0);
2769 array->context = isl_set_universe(space);
2771 array = set_upper_bounds(array, qt, pc);
2772 if (!array)
2773 return NULL;
2775 name = base.getAsString();
2777 if (types) {
2778 if (isa<TypedefType>(base)) {
2779 types->insert(cast<TypedefType>(base)->getDecl());
2780 } else if (base->isRecordType()) {
2781 RecordDecl *decl = pet_clang_record_decl(base);
2782 TypedefNameDecl *typedecl;
2783 typedecl = decl->getTypedefNameForAnonDecl();
2784 if (typedecl)
2785 types->insert(typedecl);
2786 else if (has_printable_definition(decl))
2787 types->insert(decl);
2788 else
2789 name = "<subfield>";
2793 array->element_type = strdup(name.c_str());
2794 array->element_is_record = base->isRecordType();
2795 array->element_size = size_in_bytes(ast_context, base);
2797 return array;
2800 /* Construct and return a pet_array corresponding to the variable "decl".
2802 struct pet_array *PetScan::extract_array(ValueDecl *decl,
2803 PetTypes *types, __isl_keep pet_context *pc)
2805 isl_id *id;
2806 pet_array *array;
2808 id = pet_id_from_decl(ctx, decl);
2809 array = extract_array(id, types, pc);
2810 isl_id_free(id);
2812 return array;
2815 /* Construct and return a pet_array corresponding to the sequence
2816 * of declarations represented by "decls".
2817 * The upper bounds of the array are converted to affine expressions
2818 * within the context "pc".
2819 * If the sequence contains a single declaration, then it corresponds
2820 * to a simple array access. Otherwise, it corresponds to a member access,
2821 * with the declaration for the substructure following that of the containing
2822 * structure in the sequence of declarations.
2823 * We start with the outermost substructure and then combine it with
2824 * information from the inner structures.
2826 * Additionally, keep track of all required types in "types".
2828 struct pet_array *PetScan::extract_array(__isl_keep isl_id_list *decls,
2829 PetTypes *types, __isl_keep pet_context *pc)
2831 int i, n;
2832 isl_id *id;
2833 struct pet_array *array;
2835 id = isl_id_list_get_id(decls, 0);
2836 array = extract_array(id, types, pc);
2837 isl_id_free(id);
2839 n = isl_id_list_n_id(decls);
2840 for (i = 1; i < n; ++i) {
2841 struct pet_array *parent;
2842 const char *base_name, *field_name;
2843 char *product_name;
2845 parent = array;
2846 id = isl_id_list_get_id(decls, i);
2847 array = extract_array(id, types, pc);
2848 isl_id_free(id);
2849 if (!array)
2850 return pet_array_free(parent);
2852 base_name = isl_set_get_tuple_name(parent->extent);
2853 field_name = isl_set_get_tuple_name(array->extent);
2854 product_name = pet_array_member_access_name(ctx,
2855 base_name, field_name);
2857 array->extent = isl_set_product(isl_set_copy(parent->extent),
2858 array->extent);
2859 if (product_name)
2860 array->extent = isl_set_set_tuple_name(array->extent,
2861 product_name);
2862 array->context = isl_set_intersect(array->context,
2863 isl_set_copy(parent->context));
2865 pet_array_free(parent);
2866 free(product_name);
2868 if (!array->extent || !array->context || !product_name)
2869 return pet_array_free(array);
2872 return array;
2875 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2876 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2877 std::set<TypeDecl *> &types_done);
2878 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2879 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2880 std::set<TypeDecl *> &types_done);
2882 /* For each of the fields of "decl" that is itself a record type
2883 * or a typedef, add a corresponding pet_type to "scop".
2885 static struct pet_scop *add_field_types(isl_ctx *ctx, struct pet_scop *scop,
2886 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2887 std::set<TypeDecl *> &types_done)
2889 RecordDecl::field_iterator it;
2891 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
2892 QualType type = it->getType();
2894 if (isa<TypedefType>(type)) {
2895 TypedefNameDecl *typedefdecl;
2897 typedefdecl = cast<TypedefType>(type)->getDecl();
2898 scop = add_type(ctx, scop, typedefdecl,
2899 PP, types, types_done);
2900 } else if (type->isRecordType()) {
2901 RecordDecl *record;
2903 record = pet_clang_record_decl(type);
2904 scop = add_type(ctx, scop, record,
2905 PP, types, types_done);
2909 return scop;
2912 /* Add a pet_type corresponding to "decl" to "scop", provided
2913 * it is a member of types.records and it has not been added before
2914 * (i.e., it is not a member of "types_done").
2916 * Since we want the user to be able to print the types
2917 * in the order in which they appear in the scop, we need to
2918 * make sure that types of fields in a structure appear before
2919 * that structure. We therefore call ourselves recursively
2920 * through add_field_types on the types of all record subfields.
2922 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2923 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2924 std::set<TypeDecl *> &types_done)
2926 string s;
2927 llvm::raw_string_ostream S(s);
2929 if (types.records.find(decl) == types.records.end())
2930 return scop;
2931 if (types_done.find(decl) != types_done.end())
2932 return scop;
2934 add_field_types(ctx, scop, decl, PP, types, types_done);
2936 if (strlen(decl->getName().str().c_str()) == 0)
2937 return scop;
2939 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2940 S.str();
2942 scop->types[scop->n_type] = pet_type_alloc(ctx,
2943 decl->getName().str().c_str(), s.c_str());
2944 if (!scop->types[scop->n_type])
2945 return pet_scop_free(scop);
2947 types_done.insert(decl);
2949 scop->n_type++;
2951 return scop;
2954 /* Add a pet_type corresponding to "decl" to "scop", provided
2955 * it is a member of types.typedefs and it has not been added before
2956 * (i.e., it is not a member of "types_done").
2958 * If the underlying type is a structure, then we print the typedef
2959 * ourselves since clang does not print the definition of the structure
2960 * in the typedef. We also make sure in this case that the types of
2961 * the fields in the structure are added first.
2963 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2964 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2965 std::set<TypeDecl *> &types_done)
2967 string s;
2968 llvm::raw_string_ostream S(s);
2969 QualType qt = decl->getUnderlyingType();
2971 if (types.typedefs.find(decl) == types.typedefs.end())
2972 return scop;
2973 if (types_done.find(decl) != types_done.end())
2974 return scop;
2976 if (qt->isRecordType()) {
2977 RecordDecl *rec = pet_clang_record_decl(qt);
2979 add_field_types(ctx, scop, rec, PP, types, types_done);
2980 S << "typedef ";
2981 rec->print(S, PrintingPolicy(PP.getLangOpts()));
2982 S << " ";
2983 S << decl->getName();
2984 } else {
2985 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2987 S.str();
2989 scop->types[scop->n_type] = pet_type_alloc(ctx,
2990 decl->getName().str().c_str(), s.c_str());
2991 if (!scop->types[scop->n_type])
2992 return pet_scop_free(scop);
2994 types_done.insert(decl);
2996 scop->n_type++;
2998 return scop;
3001 /* Construct a list of pet_arrays, one for each array (or scalar)
3002 * accessed inside "scop", add this list to "scop" and return the result.
3003 * The upper bounds of the arrays are converted to affine expressions
3004 * within the context "pc".
3006 * The context of "scop" is updated with the intersection of
3007 * the contexts of all arrays, i.e., constraints on the parameters
3008 * that ensure that the arrays have a valid (non-negative) size.
3010 * If any of the extracted arrays refers to a member access or
3011 * has a typedef'd type as base type,
3012 * then also add the required types to "scop".
3014 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
3015 __isl_keep pet_context *pc)
3017 int i, n;
3018 array_desc_set arrays;
3019 array_desc_set::iterator it;
3020 PetTypes types;
3021 std::set<TypeDecl *> types_done;
3022 std::set<clang::RecordDecl *, less_name>::iterator records_it;
3023 std::set<clang::TypedefNameDecl *, less_name>::iterator typedefs_it;
3024 int n_array;
3025 struct pet_array **scop_arrays;
3027 if (!scop)
3028 return NULL;
3030 pet_scop_collect_arrays(scop, arrays);
3031 if (arrays.size() == 0)
3032 return scop;
3034 n_array = scop->n_array;
3036 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3037 n_array + arrays.size());
3038 if (!scop_arrays)
3039 goto error;
3040 scop->arrays = scop_arrays;
3042 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3043 struct pet_array *array;
3044 array = extract_array(*it, &types, pc);
3045 scop->arrays[n_array + i] = array;
3046 if (!scop->arrays[n_array + i])
3047 goto error;
3048 scop->n_array++;
3049 scop->context = isl_set_intersect(scop->context,
3050 isl_set_copy(array->context));
3051 if (!scop->context)
3052 goto error;
3055 n = types.records.size() + types.typedefs.size();
3056 if (n == 0)
3057 return scop;
3059 scop->types = isl_alloc_array(ctx, struct pet_type *, n);
3060 if (!scop->types)
3061 goto error;
3063 for (records_it = types.records.begin();
3064 records_it != types.records.end(); ++records_it)
3065 scop = add_type(ctx, scop, *records_it, PP, types, types_done);
3067 for (typedefs_it = types.typedefs.begin();
3068 typedefs_it != types.typedefs.end(); ++typedefs_it)
3069 scop = add_type(ctx, scop, *typedefs_it, PP, types, types_done);
3071 return scop;
3072 error:
3073 pet_scop_free(scop);
3074 return NULL;
3077 /* Bound all parameters in scop->context to the possible values
3078 * of the corresponding C variable.
3080 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
3082 int n;
3084 if (!scop)
3085 return NULL;
3087 n = isl_set_dim(scop->context, isl_dim_param);
3088 for (int i = 0; i < n; ++i) {
3089 isl_id *id;
3090 ValueDecl *decl;
3092 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
3093 if (pet_nested_in_id(id)) {
3094 isl_id_free(id);
3095 isl_die(isl_set_get_ctx(scop->context),
3096 isl_error_internal,
3097 "unresolved nested parameter", goto error);
3099 decl = pet_id_get_decl(id);
3100 isl_id_free(id);
3102 scop->context = set_parameter_bounds(scop->context, i, decl);
3104 if (!scop->context)
3105 goto error;
3108 return scop;
3109 error:
3110 pet_scop_free(scop);
3111 return NULL;
3114 /* Construct a pet_scop from the given function.
3116 * If the scop was delimited by scop and endscop pragmas, then we override
3117 * the file offsets by those derived from the pragmas.
3119 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3121 pet_scop *scop;
3122 Stmt *stmt;
3124 stmt = fd->getBody();
3126 if (options->autodetect) {
3127 set_current_stmt(stmt);
3128 scop = extract_scop(extract(stmt, true));
3129 } else {
3130 current_line = loc.start_line;
3131 scop = scan(stmt);
3132 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
3134 scop = add_parameter_bounds(scop);
3135 scop = pet_scop_gist(scop, value_bounds);
3137 return scop;
3140 /* Update this->last_line and this->current_line based on the fact
3141 * that we are about to consider "stmt".
3143 void PetScan::set_current_stmt(Stmt *stmt)
3145 SourceLocation loc = stmt->getLocStart();
3146 SourceManager &SM = PP.getSourceManager();
3148 last_line = current_line;
3149 current_line = SM.getExpansionLineNumber(loc);
3152 /* Is the current statement marked by an independent pragma?
3153 * That is, is there an independent pragma on a line between
3154 * the line of the current statement and the line of the previous statement.
3155 * The search is not implemented very efficiently. We currently
3156 * assume that there are only a few independent pragmas, if any.
3158 bool PetScan::is_current_stmt_marked_independent()
3160 for (unsigned i = 0; i < independent.size(); ++i) {
3161 unsigned line = independent[i].line;
3163 if (last_line < line && line < current_line)
3164 return true;
3167 return false;