PetScan::scan: detect and report unbalanced pairs of scop/endscop pragmas
[pet.git] / scan.cc
blob91b948ba89280e7a9b7774e1fa8cf5d4b50a5cf7
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 #ifdef GETTYPEINFORETURNSTYPEINFO
154 static int size_in_bytes(ASTContext &context, QualType type)
156 return context.getTypeInfo(type).Width / 8;
159 #else
161 static int size_in_bytes(ASTContext &context, QualType type)
163 return context.getTypeInfo(type).first / 8;
166 #endif
168 /* Check if the element type corresponding to the given array type
169 * has a const qualifier.
171 static bool const_base(QualType qt)
173 const Type *type = qt.getTypePtr();
175 if (type->isPointerType())
176 return const_base(type->getPointeeType());
177 if (type->isArrayType()) {
178 const ArrayType *atype;
179 type = type->getCanonicalTypeInternal().getTypePtr();
180 atype = cast<ArrayType>(type);
181 return const_base(atype->getElementType());
184 return qt.isConstQualified();
187 PetScan::~PetScan()
189 std::map<const Type *, pet_expr *>::iterator it;
190 std::map<FunctionDecl *, pet_function_summary *>::iterator it_s;
192 for (it = type_size.begin(); it != type_size.end(); ++it)
193 pet_expr_free(it->second);
194 for (it_s = summary_cache.begin(); it_s != summary_cache.end(); ++it_s)
195 pet_function_summary_free(it_s->second);
197 isl_id_to_pet_expr_free(id_size);
198 isl_union_map_free(value_bounds);
201 /* Report a diagnostic on the range "range", unless autodetect is set.
203 void PetScan::report(SourceRange range, unsigned id)
205 if (options->autodetect)
206 return;
208 SourceLocation loc = range.getBegin();
209 DiagnosticsEngine &diag = PP.getDiagnostics();
210 DiagnosticBuilder B = diag.Report(loc, id) << range;
213 /* Report a diagnostic on "stmt", unless autodetect is set.
215 void PetScan::report(Stmt *stmt, unsigned id)
217 report(stmt->getSourceRange(), id);
220 /* Report a diagnostic on "decl", unless autodetect is set.
222 void PetScan::report(Decl *decl, unsigned id)
224 report(decl->getSourceRange(), id);
227 /* Called if we found something we (currently) cannot handle.
228 * We'll provide more informative warnings later.
230 * We only actually complain if autodetect is false.
232 void PetScan::unsupported(Stmt *stmt)
234 DiagnosticsEngine &diag = PP.getDiagnostics();
235 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
236 "unsupported");
237 report(stmt, id);
240 /* Report an unsupported unary operator, unless autodetect is set.
242 void PetScan::report_unsupported_unary_operator(Stmt *stmt)
244 DiagnosticsEngine &diag = PP.getDiagnostics();
245 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
246 "this type of unary operator is not supported");
247 report(stmt, id);
250 /* Report an unsupported statement type, unless autodetect is set.
252 void PetScan::report_unsupported_statement_type(Stmt *stmt)
254 DiagnosticsEngine &diag = PP.getDiagnostics();
255 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
256 "this type of statement is not supported");
257 report(stmt, id);
260 /* Report a missing prototype, unless autodetect is set.
262 void PetScan::report_prototype_required(Stmt *stmt)
264 DiagnosticsEngine &diag = PP.getDiagnostics();
265 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
266 "prototype required");
267 report(stmt, id);
270 /* Report a missing increment, unless autodetect is set.
272 void PetScan::report_missing_increment(Stmt *stmt)
274 DiagnosticsEngine &diag = PP.getDiagnostics();
275 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
276 "missing increment");
277 report(stmt, id);
280 /* Report a missing summary function, unless autodetect is set.
282 void PetScan::report_missing_summary_function(Stmt *stmt)
284 DiagnosticsEngine &diag = PP.getDiagnostics();
285 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
286 "missing summary function");
287 report(stmt, id);
290 /* Report a missing summary function body, unless autodetect is set.
292 void PetScan::report_missing_summary_function_body(Stmt *stmt)
294 DiagnosticsEngine &diag = PP.getDiagnostics();
295 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
296 "missing summary function body");
297 report(stmt, id);
300 /* Report an unsupported argument in a call to an inlined function,
301 * unless autodetect is set.
303 void PetScan::report_unsupported_inline_function_argument(Stmt *stmt)
305 DiagnosticsEngine &diag = PP.getDiagnostics();
306 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
307 "unsupported inline function call argument");
308 report(stmt, id);
311 /* Report an unsupported type of declaration, unless autodetect is set.
313 void PetScan::report_unsupported_declaration(Decl *decl)
315 DiagnosticsEngine &diag = PP.getDiagnostics();
316 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
317 "unsupported declaration");
318 report(decl, id);
321 /* Report an unbalanced pair of scop/endscop pragmas, unless autodetect is set.
323 void PetScan::report_unbalanced_pragmas(SourceLocation scop,
324 SourceLocation endscop)
326 if (options->autodetect)
327 return;
329 DiagnosticsEngine &diag = PP.getDiagnostics();
331 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
332 "unbalanced endscop pragma");
333 DiagnosticBuilder B2 = diag.Report(endscop, id);
336 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Note,
337 "corresponding scop pragma");
338 DiagnosticBuilder B = diag.Report(scop, 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 __builtin_assume or __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 /* Is "name" the name of an assume statement?
1020 * "pencil" indicates whether pencil builtins and pragmas should be supported.
1021 * "__builtin_assume" is always accepted.
1022 * If "pencil" is set, then "__pencil_assume" is also accepted.
1024 static bool is_assume(int pencil, const string &name)
1026 if (name == "__builtin_assume")
1027 return true;
1028 return pencil && name == "__pencil_assume";
1031 /* Construct a pet_expr representing a function call.
1033 * In the special case of a "call" to __builtin_assume or __pencil_assume,
1034 * construct an assume expression instead.
1036 * In the case of a "call" to __pencil_kill, the arguments
1037 * are neither read nor written (only killed), so there
1038 * is no need to check for writes to these arguments.
1040 * __pencil_assume and __pencil_kill are only recognized
1041 * when the pencil option is set.
1043 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1045 pet_expr *res = NULL;
1046 FunctionDecl *fd;
1047 string name;
1048 unsigned n_arg;
1049 bool is_kill;
1051 fd = expr->getDirectCallee();
1052 if (!fd) {
1053 unsupported(expr);
1054 return NULL;
1057 name = fd->getDeclName().getAsString();
1058 n_arg = expr->getNumArgs();
1060 if (n_arg == 1 && is_assume(options->pencil, name))
1061 return extract_assume(expr->getArg(0));
1062 is_kill = options->pencil && name == "__pencil_kill";
1064 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1065 if (!res)
1066 return NULL;
1068 for (unsigned i = 0; i < n_arg; ++i) {
1069 Expr *arg = expr->getArg(i);
1070 res = pet_expr_set_arg(res, i,
1071 PetScan::extract_argument(fd, i, arg, !is_kill));
1074 fd = get_summary_function(expr);
1075 if (!fd)
1076 return pet_expr_free(res);
1078 res = set_summary(res, fd);
1080 return res;
1083 /* Construct a pet_expr representing a (C style) cast.
1085 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1087 pet_expr *arg;
1088 QualType type;
1090 arg = extract_expr(expr->getSubExpr());
1091 if (!arg)
1092 return NULL;
1094 type = expr->getTypeAsWritten();
1095 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1098 /* Construct a pet_expr representing an integer.
1100 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1102 return pet_expr_new_int(extract_int(expr));
1105 /* Construct a pet_expr representing the integer enum constant "ecd".
1107 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
1109 isl_val *v;
1110 const llvm::APSInt &init = ecd->getInitVal();
1111 v = ::extract_int(ctx, init.isSigned(), init);
1112 return pet_expr_new_int(v);
1115 /* Try and construct a pet_expr representing "expr".
1117 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1119 switch (expr->getStmtClass()) {
1120 case Stmt::UnaryOperatorClass:
1121 return extract_expr(cast<UnaryOperator>(expr));
1122 case Stmt::CompoundAssignOperatorClass:
1123 case Stmt::BinaryOperatorClass:
1124 return extract_expr(cast<BinaryOperator>(expr));
1125 case Stmt::ImplicitCastExprClass:
1126 return extract_expr(cast<ImplicitCastExpr>(expr));
1127 case Stmt::ArraySubscriptExprClass:
1128 case Stmt::DeclRefExprClass:
1129 case Stmt::MemberExprClass:
1130 return extract_access_expr(expr);
1131 case Stmt::IntegerLiteralClass:
1132 return extract_expr(cast<IntegerLiteral>(expr));
1133 case Stmt::FloatingLiteralClass:
1134 return extract_expr(cast<FloatingLiteral>(expr));
1135 case Stmt::ParenExprClass:
1136 return extract_expr(cast<ParenExpr>(expr));
1137 case Stmt::ConditionalOperatorClass:
1138 return extract_expr(cast<ConditionalOperator>(expr));
1139 case Stmt::CallExprClass:
1140 return extract_expr(cast<CallExpr>(expr));
1141 case Stmt::CStyleCastExprClass:
1142 return extract_expr(cast<CStyleCastExpr>(expr));
1143 default:
1144 unsupported(expr);
1146 return NULL;
1149 /* Check if the given initialization statement is an assignment.
1150 * If so, return that assignment. Otherwise return NULL.
1152 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1154 BinaryOperator *ass;
1156 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1157 return NULL;
1159 ass = cast<BinaryOperator>(init);
1160 if (ass->getOpcode() != BO_Assign)
1161 return NULL;
1163 return ass;
1166 /* Check if the given initialization statement is a declaration
1167 * of a single variable.
1168 * If so, return that declaration. Otherwise return NULL.
1170 Decl *PetScan::initialization_declaration(Stmt *init)
1172 DeclStmt *decl;
1174 if (init->getStmtClass() != Stmt::DeclStmtClass)
1175 return NULL;
1177 decl = cast<DeclStmt>(init);
1179 if (!decl->isSingleDecl())
1180 return NULL;
1182 return decl->getSingleDecl();
1185 /* Given the assignment operator in the initialization of a for loop,
1186 * extract the induction variable, i.e., the (integer)variable being
1187 * assigned.
1189 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1191 Expr *lhs;
1192 DeclRefExpr *ref;
1193 ValueDecl *decl;
1194 const Type *type;
1196 lhs = init->getLHS();
1197 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1198 unsupported(init);
1199 return NULL;
1202 ref = cast<DeclRefExpr>(lhs);
1203 decl = ref->getDecl();
1204 type = decl->getType().getTypePtr();
1206 if (!type->isIntegerType()) {
1207 unsupported(lhs);
1208 return NULL;
1211 return decl;
1214 /* Given the initialization statement of a for loop and the single
1215 * declaration in this initialization statement,
1216 * extract the induction variable, i.e., the (integer) variable being
1217 * declared.
1219 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1221 VarDecl *vd;
1223 vd = cast<VarDecl>(decl);
1225 const QualType type = vd->getType();
1226 if (!type->isIntegerType()) {
1227 unsupported(init);
1228 return NULL;
1231 if (!vd->getInit()) {
1232 unsupported(init);
1233 return NULL;
1236 return vd;
1239 /* Check that op is of the form iv++ or iv--.
1240 * Return a pet_expr representing "1" or "-1" accordingly.
1242 __isl_give pet_expr *PetScan::extract_unary_increment(
1243 clang::UnaryOperator *op, clang::ValueDecl *iv)
1245 Expr *sub;
1246 DeclRefExpr *ref;
1247 isl_val *v;
1249 if (!op->isIncrementDecrementOp()) {
1250 unsupported(op);
1251 return NULL;
1254 sub = op->getSubExpr();
1255 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1256 unsupported(op);
1257 return NULL;
1260 ref = cast<DeclRefExpr>(sub);
1261 if (ref->getDecl() != iv) {
1262 unsupported(op);
1263 return NULL;
1266 if (op->isIncrementOp())
1267 v = isl_val_one(ctx);
1268 else
1269 v = isl_val_negone(ctx);
1271 return pet_expr_new_int(v);
1274 /* Check if op is of the form
1276 * iv = expr
1278 * and return the increment "expr - iv" as a pet_expr.
1280 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1281 clang::ValueDecl *iv)
1283 int type_size;
1284 Expr *lhs;
1285 DeclRefExpr *ref;
1286 pet_expr *expr, *expr_iv;
1288 if (op->getOpcode() != BO_Assign) {
1289 unsupported(op);
1290 return NULL;
1293 lhs = op->getLHS();
1294 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1295 unsupported(op);
1296 return NULL;
1299 ref = cast<DeclRefExpr>(lhs);
1300 if (ref->getDecl() != iv) {
1301 unsupported(op);
1302 return NULL;
1305 expr = extract_expr(op->getRHS());
1306 expr_iv = extract_expr(lhs);
1308 type_size = pet_clang_get_type_size(iv->getType(), ast_context);
1309 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1312 /* Check that op is of the form iv += cst or iv -= cst
1313 * and return a pet_expr corresponding to cst or -cst accordingly.
1315 __isl_give pet_expr *PetScan::extract_compound_increment(
1316 CompoundAssignOperator *op, clang::ValueDecl *iv)
1318 Expr *lhs;
1319 DeclRefExpr *ref;
1320 bool neg = false;
1321 pet_expr *expr;
1322 BinaryOperatorKind opcode;
1324 opcode = op->getOpcode();
1325 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1326 unsupported(op);
1327 return NULL;
1329 if (opcode == BO_SubAssign)
1330 neg = true;
1332 lhs = op->getLHS();
1333 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1334 unsupported(op);
1335 return NULL;
1338 ref = cast<DeclRefExpr>(lhs);
1339 if (ref->getDecl() != iv) {
1340 unsupported(op);
1341 return NULL;
1344 expr = extract_expr(op->getRHS());
1345 if (neg) {
1346 int type_size;
1347 type_size = pet_clang_get_type_size(op->getType(), ast_context);
1348 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1351 return expr;
1354 /* Check that the increment of the given for loop increments
1355 * (or decrements) the induction variable "iv" and return
1356 * the increment as a pet_expr if successful.
1358 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1359 ValueDecl *iv)
1361 Stmt *inc = stmt->getInc();
1363 if (!inc) {
1364 report_missing_increment(stmt);
1365 return NULL;
1368 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1369 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1370 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1371 return extract_compound_increment(
1372 cast<CompoundAssignOperator>(inc), iv);
1373 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1374 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1376 unsupported(inc);
1377 return NULL;
1380 /* Construct a pet_tree for a while loop.
1382 * If we were only able to extract part of the body, then simply
1383 * return that part.
1385 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1387 pet_expr *pe_cond;
1388 pet_tree *tree;
1390 tree = extract(stmt->getBody());
1391 if (partial)
1392 return tree;
1393 pe_cond = extract_expr(stmt->getCond());
1394 tree = pet_tree_new_while(pe_cond, tree);
1396 return tree;
1399 /* Construct a pet_tree for a for statement.
1400 * The for loop is required to be of one of the following forms
1402 * for (i = init; condition; ++i)
1403 * for (i = init; condition; --i)
1404 * for (i = init; condition; i += constant)
1405 * for (i = init; condition; i -= constant)
1407 * We extract a pet_tree for the body and then include it in a pet_tree
1408 * of type pet_tree_for.
1410 * As a special case, we also allow a for loop of the form
1412 * for (;;)
1414 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1416 * If we were only able to extract part of the body, then simply
1417 * return that part.
1419 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1421 BinaryOperator *ass;
1422 Decl *decl;
1423 Stmt *init;
1424 Expr *rhs;
1425 ValueDecl *iv;
1426 pet_tree *tree;
1427 int independent;
1428 int declared;
1429 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1431 independent = is_current_stmt_marked_independent();
1433 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1434 tree = extract(stmt->getBody());
1435 if (partial)
1436 return tree;
1437 tree = pet_tree_new_infinite_loop(tree);
1438 return tree;
1441 init = stmt->getInit();
1442 if (!init) {
1443 unsupported(stmt);
1444 return NULL;
1446 if ((ass = initialization_assignment(init)) != NULL) {
1447 iv = extract_induction_variable(ass);
1448 if (!iv)
1449 return NULL;
1450 rhs = ass->getRHS();
1451 } else if ((decl = initialization_declaration(init)) != NULL) {
1452 VarDecl *var = extract_induction_variable(init, decl);
1453 if (!var)
1454 return NULL;
1455 iv = var;
1456 rhs = var->getInit();
1457 } else {
1458 unsupported(stmt->getInit());
1459 return NULL;
1462 declared = !initialization_assignment(stmt->getInit());
1463 tree = extract(stmt->getBody());
1464 if (partial)
1465 return tree;
1466 pe_iv = extract_access_expr(iv);
1467 pe_iv = mark_write(pe_iv);
1468 pe_init = extract_expr(rhs);
1469 if (!stmt->getCond())
1470 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1471 else
1472 pe_cond = extract_expr(stmt->getCond());
1473 pe_inc = extract_increment(stmt, iv);
1474 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1475 pe_inc, tree);
1476 return tree;
1479 /* Store the names of the variables declared in decl_context
1480 * in the set declared_names. Make sure to only do this once by
1481 * setting declared_names_collected.
1483 void PetScan::collect_declared_names()
1485 DeclContext *DC = decl_context;
1486 DeclContext::decl_iterator it;
1488 if (declared_names_collected)
1489 return;
1491 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1492 Decl *D = *it;
1493 NamedDecl *named;
1495 if (!isa<NamedDecl>(D))
1496 continue;
1497 named = cast<NamedDecl>(D);
1498 declared_names.insert(named->getName().str());
1501 declared_names_collected = true;
1504 /* Add the names in "names" that are not also in this->declared_names
1505 * to this->used_names.
1506 * It is up to the caller to make sure that declared_names has been
1507 * populated, if needed.
1509 void PetScan::add_new_used_names(const std::set<std::string> &names)
1511 std::set<std::string>::const_iterator it;
1513 for (it = names.begin(); it != names.end(); ++it) {
1514 if (declared_names.find(*it) != declared_names.end())
1515 continue;
1516 used_names.insert(*it);
1520 /* Is the name "name" used in any declaration other than "decl"?
1522 * If the name was found to be in use before, the consider it to be in use.
1523 * Otherwise, check the DeclContext of the function containing the scop
1524 * as well as all ancestors of this DeclContext for declarations
1525 * other than "decl" that declare something called "name".
1527 bool PetScan::name_in_use(const string &name, Decl *decl)
1529 DeclContext *DC;
1530 DeclContext::decl_iterator it;
1532 if (used_names.find(name) != used_names.end())
1533 return true;
1535 for (DC = decl_context; DC; DC = DC->getParent()) {
1536 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1537 Decl *D = *it;
1538 NamedDecl *named;
1540 if (D == decl)
1541 continue;
1542 if (!isa<NamedDecl>(D))
1543 continue;
1544 named = cast<NamedDecl>(D);
1545 if (named->getName().str() == name)
1546 return true;
1550 return false;
1553 /* Generate a new name based on "name" that is not in use.
1554 * Do so by adding a suffix _i, with i an integer.
1556 string PetScan::generate_new_name(const string &name)
1558 string new_name;
1560 do {
1561 std::ostringstream oss;
1562 oss << name << "_" << n_rename++;
1563 new_name = oss.str();
1564 } while (name_in_use(new_name, NULL));
1566 return new_name;
1569 /* Try and construct a pet_tree corresponding to a compound statement.
1571 * "skip_declarations" is set if we should skip initial declarations
1572 * in the children of the compound statements.
1574 * Collect a new set of declarations for the current compound statement.
1575 * If any of the names in these declarations is also used by another
1576 * declaration reachable from the current function, then rename it
1577 * to a name that is not already in use.
1578 * In particular, keep track of the old and new names in a pet_substituter
1579 * and apply the substitutions to the pet_tree corresponding to the
1580 * compound statement.
1582 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1583 bool skip_declarations)
1585 pet_tree *tree;
1586 std::vector<VarDecl *> saved_declarations;
1587 std::vector<VarDecl *>::iterator it;
1588 pet_substituter substituter;
1590 saved_declarations = declarations;
1591 declarations.clear();
1592 tree = extract(stmt->children(), true, skip_declarations, stmt);
1593 for (it = declarations.begin(); it != declarations.end(); ++it) {
1594 isl_id *id;
1595 pet_expr *expr;
1596 VarDecl *decl = *it;
1597 string name = decl->getName().str();
1598 bool in_use = name_in_use(name, decl);
1600 used_names.insert(name);
1601 if (!in_use)
1602 continue;
1604 name = generate_new_name(name);
1605 id = pet_id_from_name_and_decl(ctx, name.c_str(), decl);
1606 expr = pet_id_create_index_expr(id);
1607 expr = extract_access_expr(decl->getType(), expr);
1608 id = pet_id_from_decl(ctx, decl);
1609 substituter.add_sub(id, expr);
1610 used_names.insert(name);
1612 tree = substituter.substitute(tree);
1613 declarations = saved_declarations;
1615 return tree;
1618 /* Return the file offset of the expansion location of "Loc".
1620 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1622 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1625 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1627 /* Return a SourceLocation for the location after the first semicolon
1628 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1629 * call it and also skip trailing spaces and newline.
1631 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1632 const LangOptions &LO)
1634 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1637 #else
1639 /* Return a SourceLocation for the location after the first semicolon
1640 * after "loc". If Lexer::findLocationAfterToken is not available,
1641 * we look in the underlying character data for the first semicolon.
1643 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1644 const LangOptions &LO)
1646 const char *semi;
1647 const char *s = SM.getCharacterData(loc);
1649 semi = strchr(s, ';');
1650 if (!semi)
1651 return SourceLocation();
1652 return loc.getFileLocWithOffset(semi + 1 - s);
1655 #endif
1657 /* If the token at "loc" is the first token on the line, then return
1658 * a location referring to the start of the line and set *indent
1659 * to the indentation of "loc"
1660 * Otherwise, return "loc" and set *indent to "".
1662 * This function is used to extend a scop to the start of the line
1663 * if the first token of the scop is also the first token on the line.
1665 * We look for the first token on the line. If its location is equal to "loc",
1666 * then the latter is the location of the first token on the line.
1668 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1669 SourceManager &SM, const LangOptions &LO, char **indent)
1671 std::pair<FileID, unsigned> file_offset_pair;
1672 llvm::StringRef file;
1673 const char *pos;
1674 Token tok;
1675 SourceLocation token_loc, line_loc;
1676 int col;
1677 const char *s;
1679 loc = SM.getExpansionLoc(loc);
1680 col = SM.getExpansionColumnNumber(loc);
1681 line_loc = loc.getLocWithOffset(1 - col);
1682 file_offset_pair = SM.getDecomposedLoc(line_loc);
1683 file = SM.getBufferData(file_offset_pair.first, NULL);
1684 pos = file.data() + file_offset_pair.second;
1686 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1687 file.begin(), pos, file.end());
1688 lexer.LexFromRawLexer(tok);
1689 token_loc = tok.getLocation();
1691 s = SM.getCharacterData(line_loc);
1692 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1694 if (token_loc == loc)
1695 return line_loc;
1696 else
1697 return loc;
1700 /* Construct a pet_loc corresponding to the region covered by "range".
1701 * If "skip_semi" is set, then we assume "range" is followed by
1702 * a semicolon and also include this semicolon.
1704 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1705 bool skip_semi)
1707 SourceLocation loc = range.getBegin();
1708 SourceManager &SM = PP.getSourceManager();
1709 const LangOptions &LO = PP.getLangOpts();
1710 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1711 unsigned start, end;
1712 char *indent;
1714 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1715 start = getExpansionOffset(SM, loc);
1716 loc = range.getEnd();
1717 if (skip_semi)
1718 loc = location_after_semi(loc, SM, LO);
1719 else
1720 loc = PP.getLocForEndOfToken(loc);
1721 end = getExpansionOffset(SM, loc);
1723 return pet_loc_alloc(ctx, start, end, line, indent);
1726 /* Convert a top-level pet_expr to an expression pet_tree.
1728 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1729 SourceRange range, bool skip_semi)
1731 pet_loc *loc;
1732 pet_tree *tree;
1734 tree = pet_tree_new_expr(expr);
1735 loc = construct_pet_loc(range, skip_semi);
1736 tree = pet_tree_set_loc(tree, loc);
1738 return tree;
1741 /* Construct a pet_tree for an if statement.
1743 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1745 pet_expr *pe_cond;
1746 pet_tree *tree, *tree_else;
1748 pe_cond = extract_expr(stmt->getCond());
1749 tree = extract(stmt->getThen());
1750 if (stmt->getElse()) {
1751 tree_else = extract(stmt->getElse());
1752 if (options->autodetect) {
1753 if (tree && !tree_else) {
1754 partial = true;
1755 pet_expr_free(pe_cond);
1756 return tree;
1758 if (!tree && tree_else) {
1759 partial = true;
1760 pet_expr_free(pe_cond);
1761 return tree_else;
1764 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1765 } else
1766 tree = pet_tree_new_if(pe_cond, tree);
1767 return tree;
1770 /* Try and construct a pet_tree for a label statement.
1772 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1774 isl_id *label;
1775 pet_tree *tree;
1777 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1779 tree = extract(stmt->getSubStmt());
1780 tree = pet_tree_set_label(tree, label);
1781 return tree;
1784 /* Update the location of "tree" to include the source range of "stmt".
1786 * Actually, we create a new location based on the source range of "stmt" and
1787 * then extend this new location to include the region of the original location.
1788 * This ensures that the line number of the final location refers to "stmt".
1790 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1792 pet_loc *loc, *tree_loc;
1794 tree_loc = pet_tree_get_loc(tree);
1795 loc = construct_pet_loc(stmt->getSourceRange(), false);
1796 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1797 pet_loc_free(tree_loc);
1799 tree = pet_tree_set_loc(tree, loc);
1800 return tree;
1803 /* Is "expr" of a type that can be converted to an access expression?
1805 static bool is_access_expr_type(Expr *expr)
1807 switch (expr->getStmtClass()) {
1808 case Stmt::ArraySubscriptExprClass:
1809 case Stmt::DeclRefExprClass:
1810 case Stmt::MemberExprClass:
1811 return true;
1812 default:
1813 return false;
1817 /* Tell the pet_inliner "inliner" about the formal arguments
1818 * in "fd" and the corresponding actual arguments in "call".
1819 * Return 0 if this was successful and -1 otherwise.
1821 * Any pointer argument is treated as an array.
1822 * The other arguments are treated as scalars.
1824 * In case of scalars, there is no restriction on the actual argument.
1825 * This actual argument is assigned to a variable with a name
1826 * that is derived from the name of the corresponding formal argument,
1827 * but made not to conflict with any variable names that are
1828 * already in use.
1830 * In case of arrays, the actual argument needs to be an expression
1831 * of a type that can be converted to an access expression or the address
1832 * of such an expression, ignoring implicit and redundant casts.
1834 int PetScan::set_inliner_arguments(pet_inliner &inliner, CallExpr *call,
1835 FunctionDecl *fd)
1837 unsigned n;
1839 n = fd->getNumParams();
1840 for (unsigned i = 0; i < n; ++i) {
1841 ParmVarDecl *parm = fd->getParamDecl(i);
1842 QualType type = parm->getType();
1843 Expr *arg, *sub;
1844 pet_expr *expr;
1845 int is_addr = 0;
1847 arg = call->getArg(i);
1848 if (pet_clang_array_depth(type) == 0) {
1849 string name = parm->getName().str();
1850 if (name_in_use(name, NULL))
1851 name = generate_new_name(name);
1852 used_names.insert(name);
1853 inliner.add_scalar_arg(parm, name, extract_expr(arg));
1854 continue;
1856 arg = pet_clang_strip_casts(arg);
1857 sub = extract_addr_of_arg(arg);
1858 if (sub) {
1859 is_addr = 1;
1860 arg = pet_clang_strip_casts(sub);
1862 if (!is_access_expr_type(arg)) {
1863 report_unsupported_inline_function_argument(arg);
1864 return -1;
1866 expr = extract_access_expr(arg);
1867 if (!expr)
1868 return -1;
1869 inliner.add_array_arg(parm, expr, is_addr);
1872 return 0;
1875 /* Internal data structure for PetScan::substitute_array_sizes.
1876 * ps is the PetScan on which the method was called.
1877 * substituter is the substituter that is used to substitute variables
1878 * in the size expressions.
1880 struct pet_substitute_array_sizes_data {
1881 PetScan *ps;
1882 pet_substituter *substituter;
1885 extern "C" {
1886 static int substitute_array_size(__isl_keep pet_tree *tree, void *user);
1889 /* If "tree" is a declaration, then perform the substitutions
1890 * in data->substituter on its size expression and store the result
1891 * in the size expression cache of data->ps such that the modified expression
1892 * will be used in subsequent calls to get_array_size.
1894 static int substitute_array_size(__isl_keep pet_tree *tree, void *user)
1896 struct pet_substitute_array_sizes_data *data;
1897 isl_id *id;
1898 pet_expr *var, *size;
1900 if (!pet_tree_is_decl(tree))
1901 return 0;
1903 data = (struct pet_substitute_array_sizes_data *) user;
1904 var = pet_tree_decl_get_var(tree);
1905 id = pet_expr_access_get_id(var);
1906 pet_expr_free(var);
1908 size = data->ps->get_array_size(id);
1909 size = data->substituter->substitute(size);
1910 data->ps->set_array_size(id, size);
1912 return 0;
1915 /* Perform the substitutions in "substituter" on all the arrays declared
1916 * inside "tree" and store the results in the size expression cache
1917 * such that the modified expressions will be used in subsequent calls
1918 * to get_array_size.
1920 int PetScan::substitute_array_sizes(__isl_keep pet_tree *tree,
1921 pet_substituter *substituter)
1923 struct pet_substitute_array_sizes_data data = { this, substituter };
1925 return pet_tree_foreach_sub_tree(tree, &substitute_array_size, &data);
1928 /* Try and construct a pet_tree from the body of "fd" using the actual
1929 * arguments in "call" in place of the formal arguments.
1930 * "fd" is assumed to point to the declaration with a function body.
1931 * In particular, construct a block that consists of assignments
1932 * of (parts of) the actual arguments to temporary variables
1933 * followed by the inlined function body with the formal arguments
1934 * replaced by (expressions containing) these temporary variables.
1936 * The actual inlining is taken care of by the pet_inliner object.
1937 * This function merely calls set_inliner_arguments to tell
1938 * the pet_inliner about the actual arguments, extracts a pet_tree
1939 * from the body of the called function and then passes this pet_tree
1940 * to the pet_inliner.
1941 * The substitutions performed by the inliner are also applied
1942 * to the size expressions of the arrays declared in the inlined
1943 * function. These size expressions are not stored in the tree
1944 * itself, but rather in the size expression cache.
1946 * During the extraction of the function body, all variables names
1947 * that are declared in the calling function as well all variable
1948 * names that are known to be in use are considered to be in use
1949 * in the called function to ensure that there is no naming conflict.
1950 * Similarly, the additional names that are in use in the called function
1951 * are considered to be in use in the calling function as well.
1953 * The location of the pet_tree is reset to the call site to ensure
1954 * that the extent of the scop does not include the body of the called
1955 * function.
1957 __isl_give pet_tree *PetScan::extract_inlined_call(CallExpr *call,
1958 FunctionDecl *fd)
1960 int save_autodetect;
1961 pet_tree *tree;
1962 pet_loc *tree_loc;
1963 pet_inliner inliner(ctx, n_arg, ast_context);
1965 if (set_inliner_arguments(inliner, call, fd) < 0)
1966 return NULL;
1968 save_autodetect = options->autodetect;
1969 options->autodetect = 0;
1970 PetScan body_scan(PP, ast_context, fd, loc, options,
1971 isl_union_map_copy(value_bounds), independent);
1972 collect_declared_names();
1973 body_scan.add_new_used_names(declared_names);
1974 body_scan.add_new_used_names(used_names);
1975 tree = body_scan.extract(fd->getBody(), false);
1976 add_new_used_names(body_scan.used_names);
1977 options->autodetect = save_autodetect;
1979 tree_loc = construct_pet_loc(call->getSourceRange(), true);
1980 tree = pet_tree_set_loc(tree, tree_loc);
1982 substitute_array_sizes(tree, &inliner);
1984 return inliner.inline_tree(tree);
1987 /* Try and construct a pet_tree corresponding
1988 * to the expression statement "stmt".
1990 * If the outer expression is a function call and if the corresponding
1991 * function body is marked "inline", then return a pet_tree
1992 * corresponding to the inlined function.
1994 __isl_give pet_tree *PetScan::extract_expr_stmt(Stmt *stmt)
1996 pet_expr *expr;
1998 if (stmt->getStmtClass() == Stmt::CallExprClass) {
1999 CallExpr *call = cast<CallExpr>(stmt);
2000 FunctionDecl *fd = call->getDirectCallee();
2001 fd = pet_clang_find_function_decl_with_body(fd);
2002 if (fd && fd->isInlineSpecified())
2003 return extract_inlined_call(call, fd);
2006 expr = extract_expr(cast<Expr>(stmt));
2007 return extract(expr, stmt->getSourceRange(), true);
2010 /* Try and construct a pet_tree corresponding to "stmt".
2012 * If "stmt" is a compound statement, then "skip_declarations"
2013 * indicates whether we should skip initial declarations in the
2014 * compound statement.
2016 * If the constructed pet_tree is not a (possibly) partial representation
2017 * of "stmt", we update start and end of the pet_scop to those of "stmt".
2018 * In particular, if skip_declarations is set, then we may have skipped
2019 * declarations inside "stmt" and so the pet_scop may not represent
2020 * the entire "stmt".
2021 * Note that this function may be called with "stmt" referring to the entire
2022 * body of the function, including the outer braces. In such cases,
2023 * skip_declarations will be set and the braces will not be taken into
2024 * account in tree->loc.
2026 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
2028 pet_tree *tree;
2030 set_current_stmt(stmt);
2032 if (isa<Expr>(stmt))
2033 return extract_expr_stmt(cast<Expr>(stmt));
2035 switch (stmt->getStmtClass()) {
2036 case Stmt::WhileStmtClass:
2037 tree = extract(cast<WhileStmt>(stmt));
2038 break;
2039 case Stmt::ForStmtClass:
2040 tree = extract_for(cast<ForStmt>(stmt));
2041 break;
2042 case Stmt::IfStmtClass:
2043 tree = extract(cast<IfStmt>(stmt));
2044 break;
2045 case Stmt::CompoundStmtClass:
2046 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
2047 break;
2048 case Stmt::LabelStmtClass:
2049 tree = extract(cast<LabelStmt>(stmt));
2050 break;
2051 case Stmt::ContinueStmtClass:
2052 tree = pet_tree_new_continue(ctx);
2053 break;
2054 case Stmt::BreakStmtClass:
2055 tree = pet_tree_new_break(ctx);
2056 break;
2057 case Stmt::DeclStmtClass:
2058 tree = extract(cast<DeclStmt>(stmt));
2059 break;
2060 case Stmt::NullStmtClass:
2061 tree = pet_tree_new_block(ctx, 0, 0);
2062 break;
2063 default:
2064 report_unsupported_statement_type(stmt);
2065 return NULL;
2068 if (partial || skip_declarations)
2069 return tree;
2071 return update_loc(tree, stmt);
2074 /* Given a sequence of statements "stmt_range" of which the first "n_decl"
2075 * are declarations and of which the remaining statements are represented
2076 * by "tree", try and extend "tree" to include the last sequence of
2077 * the initial declarations that can be completely extracted.
2079 * We start collecting the initial declarations and start over
2080 * whenever we come across a declaration that we cannot extract.
2081 * If we have been able to extract any declarations, then we
2082 * copy over the contents of "tree" at the end of the declarations.
2083 * Otherwise, we simply return the original "tree".
2085 __isl_give pet_tree *PetScan::insert_initial_declarations(
2086 __isl_take pet_tree *tree, int n_decl, StmtRange stmt_range)
2088 StmtIterator i;
2089 pet_tree *res;
2090 int n_stmt;
2091 int is_block;
2092 int j;
2094 n_stmt = pet_tree_block_n_child(tree);
2095 is_block = pet_tree_block_get_block(tree);
2096 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2098 for (i = stmt_range.first; n_decl; ++i, --n_decl) {
2099 Stmt *child = *i;
2100 pet_tree *tree_i;
2102 tree_i = extract(child);
2103 if (tree_i && !partial) {
2104 res = pet_tree_block_add_child(res, tree_i);
2105 continue;
2107 pet_tree_free(tree_i);
2108 partial = false;
2109 if (pet_tree_block_n_child(res) == 0)
2110 continue;
2111 pet_tree_free(res);
2112 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2115 if (pet_tree_block_n_child(res) == 0) {
2116 pet_tree_free(res);
2117 return tree;
2120 for (j = 0; j < n_stmt; ++j) {
2121 pet_tree *tree_i;
2123 tree_i = pet_tree_block_get_child(tree, j);
2124 res = pet_tree_block_add_child(res, tree_i);
2126 pet_tree_free(tree);
2128 return res;
2131 /* Try and construct a pet_tree corresponding to (part of)
2132 * a sequence of statements.
2134 * "block" is set if the sequence represents the children of
2135 * a compound statement.
2136 * "skip_declarations" is set if we should skip initial declarations
2137 * in the sequence of statements.
2138 * "parent" is the statement that has stmt_range as (some of) its children.
2140 * If autodetect is set, then we allow the extraction of only a subrange
2141 * of the sequence of statements. However, if there is at least one
2142 * kill and there is some subsequent statement for which we could not
2143 * construct a tree, then turn off the "block" property of the tree
2144 * such that no extra kill will be introduced at the end of the (partial)
2145 * block. If, on the other hand, the final range contains
2146 * no statements, then we discard the entire range.
2147 * If only a subrange of the sequence was extracted, but each statement
2148 * in the sequence was extracted completely, and if there are some
2149 * variable declarations in the sequence before or inside
2150 * the extracted subrange, then check if any of these variables are
2151 * not used after the extracted subrange. If so, add kills to these
2152 * variables.
2154 * If the entire range was extracted, apart from some initial declarations,
2155 * then we try and extend the range with the latest of those initial
2156 * declarations.
2158 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
2159 bool skip_declarations, Stmt *parent)
2161 StmtIterator i;
2162 int j, skip;
2163 bool has_kills = false;
2164 bool partial_range = false;
2165 bool outer_partial = false;
2166 pet_tree *tree;
2167 SourceManager &SM = PP.getSourceManager();
2168 pet_killed_locals kl(SM);
2169 unsigned range_start, range_end;
2171 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
2174 tree = pet_tree_new_block(ctx, block, j);
2176 skip = 0;
2177 i = stmt_range.first;
2178 if (skip_declarations)
2179 for (; i != stmt_range.second; ++i) {
2180 if ((*i)->getStmtClass() != Stmt::DeclStmtClass)
2181 break;
2182 if (options->autodetect)
2183 kl.add_locals(cast<DeclStmt>(*i));
2184 ++skip;
2187 for (; i != stmt_range.second; ++i) {
2188 Stmt *child = *i;
2189 pet_tree *tree_i;
2191 tree_i = extract(child);
2192 if (pet_tree_block_n_child(tree) != 0 && partial) {
2193 pet_tree_free(tree_i);
2194 break;
2196 if (child->getStmtClass() == Stmt::DeclStmtClass) {
2197 if (options->autodetect)
2198 kl.add_locals(cast<DeclStmt>(child));
2199 if (tree_i && block)
2200 has_kills = true;
2202 if (options->autodetect) {
2203 if (tree_i) {
2204 range_end = getExpansionOffset(SM,
2205 child->getLocEnd());
2206 if (pet_tree_block_n_child(tree) == 0)
2207 range_start = getExpansionOffset(SM,
2208 child->getLocStart());
2209 tree = pet_tree_block_add_child(tree, tree_i);
2210 } else {
2211 partial_range = true;
2213 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
2214 outer_partial = partial = true;
2215 } else {
2216 tree = pet_tree_block_add_child(tree, tree_i);
2219 if (partial || !tree)
2220 break;
2223 if (!tree)
2224 return NULL;
2226 if (partial) {
2227 if (has_kills)
2228 tree = pet_tree_block_set_block(tree, 0);
2229 if (outer_partial) {
2230 kl.remove_accessed_after(parent,
2231 range_start, range_end);
2232 tree = add_kills(tree, kl.locals);
2234 } else if (partial_range) {
2235 if (pet_tree_block_n_child(tree) == 0) {
2236 pet_tree_free(tree);
2237 return NULL;
2239 partial = true;
2240 } else if (skip > 0)
2241 tree = insert_initial_declarations(tree, skip, stmt_range);
2243 return tree;
2246 extern "C" {
2247 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2248 void *user);
2249 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2250 __isl_keep pet_context *pc, void *user);
2253 /* Construct a pet_expr that holds the sizes of the array accessed
2254 * by "access".
2255 * This function is used as a callback to pet_context_add_parameters,
2256 * which is also passed a pointer to the PetScan object.
2258 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2259 void *user)
2261 PetScan *ps = (PetScan *) user;
2262 isl_id *id;
2263 pet_expr *size;
2265 id = pet_expr_access_get_id(access);
2266 size = ps->get_array_size(id);
2267 isl_id_free(id);
2269 return size;
2272 /* Construct and return a pet_array corresponding to the variable
2273 * accessed by "access".
2274 * This function is used as a callback to pet_scop_from_pet_tree,
2275 * which is also passed a pointer to the PetScan object.
2277 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2278 __isl_keep pet_context *pc, void *user)
2280 PetScan *ps = (PetScan *) user;
2281 isl_id *id;
2282 pet_array *array;
2284 id = pet_expr_access_get_id(access);
2285 array = ps->extract_array(id, NULL, pc);
2286 isl_id_free(id);
2288 return array;
2291 /* Extract a function summary from the body of "fd".
2293 * We extract a scop from the function body in a context with as
2294 * parameters the integer arguments of the function.
2295 * We turn off autodetection (in case it was set) to ensure that
2296 * the entire function body is considered.
2297 * We then collect the accessed array elements and attach them
2298 * to the corresponding array arguments, taking into account
2299 * that the function body may access members of array elements.
2301 * The reason for representing the integer arguments as parameters in
2302 * the context is that if we were to instead start with a context
2303 * with the function arguments as initial dimensions, then we would not
2304 * be able to refer to them from the array extents, without turning
2305 * array extents into maps.
2307 * The result is stored in the summary_cache cache so that we can reuse
2308 * it if this method gets called on the same function again later on.
2310 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
2312 isl_space *space;
2313 isl_set *domain;
2314 pet_context *pc;
2315 pet_tree *tree;
2316 pet_function_summary *summary;
2317 unsigned n;
2318 ScopLoc loc;
2319 int save_autodetect;
2320 struct pet_scop *scop;
2321 int int_size;
2322 isl_union_set *may_read, *may_write, *must_write;
2323 isl_union_map *to_inner;
2325 if (summary_cache.find(fd) != summary_cache.end())
2326 return pet_function_summary_copy(summary_cache[fd]);
2328 space = isl_space_set_alloc(ctx, 0, 0);
2330 n = fd->getNumParams();
2331 summary = pet_function_summary_alloc(ctx, n);
2332 for (unsigned i = 0; i < n; ++i) {
2333 ParmVarDecl *parm = fd->getParamDecl(i);
2334 QualType type = parm->getType();
2335 isl_id *id;
2337 if (!type->isIntegerType())
2338 continue;
2339 id = pet_id_from_decl(ctx, parm);
2340 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
2341 space = isl_space_set_dim_id(space, isl_dim_param, 0,
2342 isl_id_copy(id));
2343 summary = pet_function_summary_set_int(summary, i, id);
2346 save_autodetect = options->autodetect;
2347 options->autodetect = 0;
2348 PetScan body_scan(PP, ast_context, fd, loc, options,
2349 isl_union_map_copy(value_bounds), independent);
2351 tree = body_scan.extract(fd->getBody(), false);
2353 domain = isl_set_universe(space);
2354 pc = pet_context_alloc(domain);
2355 pc = pet_context_add_parameters(pc, tree,
2356 &::get_array_size, &body_scan);
2357 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2358 scop = pet_scop_from_pet_tree(tree, int_size,
2359 &::extract_array, &body_scan, pc);
2360 scop = scan_arrays(scop, pc);
2361 may_read = isl_union_map_range(pet_scop_get_may_reads(scop));
2362 may_write = isl_union_map_range(pet_scop_get_may_writes(scop));
2363 must_write = isl_union_map_range(pet_scop_get_must_writes(scop));
2364 to_inner = pet_scop_compute_outer_to_inner(scop);
2365 pet_scop_free(scop);
2367 for (unsigned i = 0; i < n; ++i) {
2368 ParmVarDecl *parm = fd->getParamDecl(i);
2369 QualType type = parm->getType();
2370 struct pet_array *array;
2371 isl_space *space;
2372 isl_union_set *data_set;
2373 isl_union_set *may_read_i, *may_write_i, *must_write_i;
2375 if (pet_clang_array_depth(type) == 0)
2376 continue;
2378 array = body_scan.extract_array(parm, NULL, pc);
2379 space = array ? isl_set_get_space(array->extent) : NULL;
2380 pet_array_free(array);
2381 data_set = isl_union_set_from_set(isl_set_universe(space));
2382 data_set = isl_union_set_apply(data_set,
2383 isl_union_map_copy(to_inner));
2384 may_read_i = isl_union_set_intersect(
2385 isl_union_set_copy(may_read),
2386 isl_union_set_copy(data_set));
2387 may_write_i = isl_union_set_intersect(
2388 isl_union_set_copy(may_write),
2389 isl_union_set_copy(data_set));
2390 must_write_i = isl_union_set_intersect(
2391 isl_union_set_copy(must_write), data_set);
2392 summary = pet_function_summary_set_array(summary, i,
2393 may_read_i, may_write_i, must_write_i);
2396 isl_union_set_free(may_read);
2397 isl_union_set_free(may_write);
2398 isl_union_set_free(must_write);
2399 isl_union_map_free(to_inner);
2401 options->autodetect = save_autodetect;
2402 pet_context_free(pc);
2404 summary_cache[fd] = pet_function_summary_copy(summary);
2406 return summary;
2409 /* If "fd" has a function body, then extract a function summary from
2410 * this body and attach it to the call expression "expr".
2412 * Even if a function body is available, "fd" itself may point
2413 * to a declaration without function body. We therefore first
2414 * replace it by the declaration that comes with a body (if any).
2416 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
2417 FunctionDecl *fd)
2419 pet_function_summary *summary;
2421 if (!expr)
2422 return NULL;
2423 fd = pet_clang_find_function_decl_with_body(fd);
2424 if (!fd)
2425 return expr;
2427 summary = get_summary(fd);
2429 expr = pet_expr_call_set_summary(expr, summary);
2431 return expr;
2434 /* Extract a pet_scop from "tree".
2436 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
2437 * then add pet_arrays for all accessed arrays.
2438 * We populate the pet_context with assignments for all parameters used
2439 * inside "tree" or any of the size expressions for the arrays accessed
2440 * by "tree" so that they can be used in affine expressions.
2442 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
2444 int int_size;
2445 isl_set *domain;
2446 pet_context *pc;
2447 pet_scop *scop;
2449 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2451 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2452 pc = pet_context_alloc(domain);
2453 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
2454 scop = pet_scop_from_pet_tree(tree, int_size,
2455 &::extract_array, this, pc);
2456 scop = scan_arrays(scop, pc);
2457 pet_context_free(pc);
2459 return scop;
2462 /* Add a call to __pencil_kill to the end of "tree" that kills
2463 * all the variables in "locals" and return the result.
2465 * No location is added to the kill because the most natural
2466 * location would lie outside the scop. Attaching such a location
2467 * to this tree would extend the scope of the final result
2468 * to include the location.
2470 __isl_give pet_tree *PetScan::add_kills(__isl_take pet_tree *tree,
2471 set<ValueDecl *> locals)
2473 int i;
2474 pet_expr *expr;
2475 pet_tree *kill, *block;
2476 set<ValueDecl *>::iterator it;
2478 if (locals.size() == 0)
2479 return tree;
2480 expr = pet_expr_new_call(ctx, "__pencil_kill", locals.size());
2481 i = 0;
2482 for (it = locals.begin(); it != locals.end(); ++it) {
2483 pet_expr *arg;
2484 arg = extract_access_expr(*it);
2485 expr = pet_expr_set_arg(expr, i++, arg);
2487 kill = pet_tree_new_expr(expr);
2488 block = pet_tree_new_block(ctx, 0, 2);
2489 block = pet_tree_block_add_child(block, tree);
2490 block = pet_tree_block_add_child(block, kill);
2492 return block;
2495 /* Check if the scop marked by the user is exactly this Stmt
2496 * or part of this Stmt.
2497 * If so, return a pet_scop corresponding to the marked region.
2498 * Otherwise, return NULL.
2500 * If the scop is not further nested inside a child of "stmt",
2501 * then check if there are any variable declarations before the scop
2502 * inside "stmt". If so, and if these variables are not used
2503 * after the scop, then add kills to the variables.
2505 * If the scop starts in the middle of one of the children, without
2506 * also ending in that child, then report an error.
2508 struct pet_scop *PetScan::scan(Stmt *stmt)
2510 SourceManager &SM = PP.getSourceManager();
2511 unsigned start_off, end_off;
2512 pet_tree *tree;
2514 start_off = getExpansionOffset(SM, stmt->getLocStart());
2515 end_off = getExpansionOffset(SM, stmt->getLocEnd());
2517 if (start_off > loc.end)
2518 return NULL;
2519 if (end_off < loc.start)
2520 return NULL;
2522 if (start_off >= loc.start && end_off <= loc.end)
2523 return extract_scop(extract(stmt));
2525 pet_killed_locals kl(SM);
2526 StmtIterator start;
2527 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
2528 Stmt *child = *start;
2529 if (!child)
2530 continue;
2531 start_off = getExpansionOffset(SM, child->getLocStart());
2532 end_off = getExpansionOffset(SM, child->getLocEnd());
2533 if (start_off < loc.start && end_off >= loc.end)
2534 return scan(child);
2535 if (start_off >= loc.start)
2536 break;
2537 if (loc.start < end_off) {
2538 report_unbalanced_pragmas(loc.scop, loc.endscop);
2539 return NULL;
2541 if (isa<DeclStmt>(child))
2542 kl.add_locals(cast<DeclStmt>(child));
2545 StmtIterator end;
2546 for (end = start; end != stmt->child_end(); ++end) {
2547 Stmt *child = *end;
2548 start_off = SM.getFileOffset(child->getLocStart());
2549 if (start_off >= loc.end)
2550 break;
2553 kl.remove_accessed_after(stmt, loc.start, loc.end);
2555 tree = extract(StmtRange(start, end), false, false, stmt);
2556 tree = add_kills(tree, kl.locals);
2557 return extract_scop(tree);
2560 /* Set the size of index "pos" of "array" to "size".
2561 * In particular, add a constraint of the form
2563 * i_pos < size
2565 * to array->extent and a constraint of the form
2567 * size >= 0
2569 * to array->context.
2571 * The domain of "size" is assumed to be zero-dimensional.
2573 static struct pet_array *update_size(struct pet_array *array, int pos,
2574 __isl_take isl_pw_aff *size)
2576 isl_set *valid;
2577 isl_set *univ;
2578 isl_set *bound;
2579 isl_space *dim;
2580 isl_aff *aff;
2581 isl_pw_aff *index;
2582 isl_id *id;
2584 if (!array)
2585 goto error;
2587 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2588 array->context = isl_set_intersect(array->context, valid);
2590 dim = isl_set_get_space(array->extent);
2591 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2592 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2593 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2594 index = isl_pw_aff_alloc(univ, aff);
2596 size = isl_pw_aff_add_dims(size, isl_dim_in,
2597 isl_set_dim(array->extent, isl_dim_set));
2598 id = isl_set_get_tuple_id(array->extent);
2599 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2600 bound = isl_pw_aff_lt_set(index, size);
2602 array->extent = isl_set_intersect(array->extent, bound);
2604 if (!array->context || !array->extent)
2605 return pet_array_free(array);
2607 return array;
2608 error:
2609 isl_pw_aff_free(size);
2610 return NULL;
2613 #ifdef HAVE_DECAYEDTYPE
2615 /* If "qt" is a decayed type, then set *decayed to true and
2616 * return the original type.
2618 static QualType undecay(QualType qt, bool *decayed)
2620 const Type *type = qt.getTypePtr();
2622 *decayed = isa<DecayedType>(type);
2623 if (*decayed)
2624 qt = cast<DecayedType>(type)->getOriginalType();
2625 return qt;
2628 #else
2630 /* If "qt" is a decayed type, then set *decayed to true and
2631 * return the original type.
2632 * Since this version of clang does not define a DecayedType,
2633 * we cannot obtain the original type even if it had been decayed and
2634 * we set *decayed to false.
2636 static QualType undecay(QualType qt, bool *decayed)
2638 *decayed = false;
2639 return qt;
2642 #endif
2644 /* Figure out the size of the array at position "pos" and all
2645 * subsequent positions from "qt" and update the corresponding
2646 * argument of "expr" accordingly.
2648 * The initial type (when pos is zero) may be a pointer type decayed
2649 * from an array type, if this initial type is the type of a function
2650 * argument. This only happens if the original array type has
2651 * a constant size in the outer dimension as otherwise we get
2652 * a VariableArrayType. Try and obtain this original type (if available) and
2653 * take the outer array size into account if it was marked static.
2655 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2656 QualType qt, int pos)
2658 const ArrayType *atype;
2659 pet_expr *size;
2660 bool decayed = false;
2662 if (!expr)
2663 return NULL;
2665 if (pos == 0)
2666 qt = undecay(qt, &decayed);
2668 if (qt->isPointerType()) {
2669 qt = qt->getPointeeType();
2670 return set_upper_bounds(expr, qt, pos + 1);
2672 if (!qt->isArrayType())
2673 return expr;
2675 qt = qt->getCanonicalTypeInternal();
2676 atype = cast<ArrayType>(qt.getTypePtr());
2678 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2679 qt = atype->getElementType();
2680 return set_upper_bounds(expr, qt, pos + 1);
2683 if (qt->isConstantArrayType()) {
2684 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2685 size = extract_expr(ca->getSize());
2686 expr = pet_expr_set_arg(expr, pos, size);
2687 } else if (qt->isVariableArrayType()) {
2688 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2689 size = extract_expr(vla->getSizeExpr());
2690 expr = pet_expr_set_arg(expr, pos, size);
2693 qt = atype->getElementType();
2695 return set_upper_bounds(expr, qt, pos + 1);
2698 /* Construct a pet_expr that holds the sizes of the array represented by "id".
2699 * The returned expression is a call expression with as arguments
2700 * the sizes in each dimension. If we are unable to derive the size
2701 * in a given dimension, then the corresponding argument is set to infinity.
2702 * In fact, we initialize all arguments to infinity and then update
2703 * them if we are able to figure out the size.
2705 * The result is stored in the id_size cache so that it can be reused
2706 * if this method is called on the same array identifier later.
2707 * The result is also stored in the type_size cache in case
2708 * it gets called on a different array identifier with the same type.
2710 __isl_give pet_expr *PetScan::get_array_size(__isl_keep isl_id *id)
2712 QualType qt = pet_id_get_array_type(id);
2713 int depth;
2714 pet_expr *expr, *inf;
2715 const Type *type = qt.getTypePtr();
2716 isl_maybe_pet_expr m;
2718 m = isl_id_to_pet_expr_try_get(id_size, id);
2719 if (m.valid < 0 || m.valid)
2720 return m.value;
2721 if (type_size.find(type) != type_size.end())
2722 return pet_expr_copy(type_size[type]);
2724 depth = pet_clang_array_depth(qt);
2725 inf = pet_expr_new_int(isl_val_infty(ctx));
2726 expr = pet_expr_new_call(ctx, "bounds", depth);
2727 for (int i = 0; i < depth; ++i)
2728 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2729 pet_expr_free(inf);
2731 expr = set_upper_bounds(expr, qt, 0);
2732 type_size[type] = pet_expr_copy(expr);
2733 id_size = isl_id_to_pet_expr_set(id_size, isl_id_copy(id),
2734 pet_expr_copy(expr));
2736 return expr;
2739 /* Set the array size of the array identified by "id" to "size",
2740 * replacing any previously stored value.
2742 void PetScan::set_array_size(__isl_take isl_id *id, __isl_take pet_expr *size)
2744 id_size = isl_id_to_pet_expr_set(id_size, id, size);
2747 /* Does "expr" represent the "integer" infinity?
2749 static int is_infty(__isl_keep pet_expr *expr)
2751 isl_val *v;
2752 int res;
2754 if (pet_expr_get_type(expr) != pet_expr_int)
2755 return 0;
2756 v = pet_expr_int_get_val(expr);
2757 res = isl_val_is_infty(v);
2758 isl_val_free(v);
2760 return res;
2763 /* Figure out the dimensions of an array "array" and
2764 * update "array" accordingly.
2766 * We first construct a pet_expr that holds the sizes of the array
2767 * in each dimension. The resulting expression may containing
2768 * infinity values for dimension where we are unable to derive
2769 * a size expression.
2771 * The arguments of the size expression that have a value different from
2772 * infinity are then converted to an affine expression
2773 * within the context "pc" and incorporated into the size of "array".
2774 * If we are unable to convert a size expression to an affine expression or
2775 * if the size is not a (symbolic) constant,
2776 * then we leave the corresponding size of "array" untouched.
2778 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2779 __isl_keep pet_context *pc)
2781 int n;
2782 isl_id *id;
2783 pet_expr *expr;
2785 if (!array)
2786 return NULL;
2788 id = isl_set_get_tuple_id(array->extent);
2789 expr = get_array_size(id);
2790 isl_id_free(id);
2792 n = pet_expr_get_n_arg(expr);
2793 for (int i = 0; i < n; ++i) {
2794 pet_expr *arg;
2795 isl_pw_aff *size;
2797 arg = pet_expr_get_arg(expr, i);
2798 if (!is_infty(arg)) {
2799 int dim;
2801 size = pet_expr_extract_affine(arg, pc);
2802 dim = isl_pw_aff_dim(size, isl_dim_in);
2803 if (!size)
2804 array = pet_array_free(array);
2805 else if (isl_pw_aff_involves_nan(size) ||
2806 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2807 isl_pw_aff_free(size);
2808 else {
2809 size = isl_pw_aff_drop_dims(size,
2810 isl_dim_in, 0, dim);
2811 array = update_size(array, i, size);
2814 pet_expr_free(arg);
2816 pet_expr_free(expr);
2818 return array;
2821 /* Does "decl" have a definition that we can keep track of in a pet_type?
2823 static bool has_printable_definition(RecordDecl *decl)
2825 if (!decl->getDeclName())
2826 return false;
2827 return decl->getLexicalDeclContext() == decl->getDeclContext();
2830 /* Add all TypedefType objects that appear when dereferencing "type"
2831 * to "types".
2833 static void insert_intermediate_typedefs(PetTypes *types, QualType type)
2835 type = pet_clang_base_or_typedef_type(type);
2836 while (isa<TypedefType>(type)) {
2837 const TypedefType *tt;
2839 tt = cast<TypedefType>(type);
2840 types->insert(tt->getDecl());
2841 type = tt->desugar();
2842 type = pet_clang_base_or_typedef_type(type);
2846 /* Construct and return a pet_array corresponding to the variable
2847 * represented by "id".
2848 * In particular, initialize array->extent to
2850 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2852 * and then call set_upper_bounds to set the upper bounds on the indices
2853 * based on the type of the variable. The upper bounds are converted
2854 * to affine expressions within the context "pc".
2856 * If the base type is that of a record with a top-level definition or
2857 * of a typedef and if "types" is not null, then the RecordDecl or
2858 * TypedefType corresponding to the type, as well as any intermediate
2859 * TypedefType, is added to "types".
2861 * If the base type is that of a record with no top-level definition,
2862 * then we replace it by "<subfield>".
2864 * If the variable is a scalar, i.e., a zero-dimensional array,
2865 * then the "const" qualifier, if any, is removed from the base type.
2866 * This makes it easier for users of pet to turn initializations
2867 * into assignments.
2869 struct pet_array *PetScan::extract_array(__isl_keep isl_id *id,
2870 PetTypes *types, __isl_keep pet_context *pc)
2872 struct pet_array *array;
2873 QualType qt = pet_id_get_array_type(id);
2874 int depth = pet_clang_array_depth(qt);
2875 QualType base = pet_clang_base_type(qt);
2876 string name;
2877 isl_space *space;
2879 array = isl_calloc_type(ctx, struct pet_array);
2880 if (!array)
2881 return NULL;
2883 space = isl_space_set_alloc(ctx, 0, depth);
2884 space = isl_space_set_tuple_id(space, isl_dim_set, isl_id_copy(id));
2886 array->extent = isl_set_nat_universe(space);
2888 space = isl_space_params_alloc(ctx, 0);
2889 array->context = isl_set_universe(space);
2891 array = set_upper_bounds(array, pc);
2892 if (!array)
2893 return NULL;
2895 if (depth == 0)
2896 base.removeLocalConst();
2897 name = base.getAsString();
2899 if (types) {
2900 insert_intermediate_typedefs(types, qt);
2901 if (isa<TypedefType>(base)) {
2902 types->insert(cast<TypedefType>(base)->getDecl());
2903 } else if (base->isRecordType()) {
2904 RecordDecl *decl = pet_clang_record_decl(base);
2905 TypedefNameDecl *typedecl;
2906 typedecl = decl->getTypedefNameForAnonDecl();
2907 if (typedecl)
2908 types->insert(typedecl);
2909 else if (has_printable_definition(decl))
2910 types->insert(decl);
2911 else
2912 name = "<subfield>";
2916 array->element_type = strdup(name.c_str());
2917 array->element_is_record = base->isRecordType();
2918 array->element_size = size_in_bytes(ast_context, base);
2920 return array;
2923 /* Construct and return a pet_array corresponding to the variable "decl".
2925 struct pet_array *PetScan::extract_array(ValueDecl *decl,
2926 PetTypes *types, __isl_keep pet_context *pc)
2928 isl_id *id;
2929 pet_array *array;
2931 id = pet_id_from_decl(ctx, decl);
2932 array = extract_array(id, types, pc);
2933 isl_id_free(id);
2935 return array;
2938 /* Construct and return a pet_array corresponding to the sequence
2939 * of declarations represented by "decls".
2940 * The upper bounds of the array are converted to affine expressions
2941 * within the context "pc".
2942 * If the sequence contains a single declaration, then it corresponds
2943 * to a simple array access. Otherwise, it corresponds to a member access,
2944 * with the declaration for the substructure following that of the containing
2945 * structure in the sequence of declarations.
2946 * We start with the outermost substructure and then combine it with
2947 * information from the inner structures.
2949 * Additionally, keep track of all required types in "types".
2951 struct pet_array *PetScan::extract_array(__isl_keep isl_id_list *decls,
2952 PetTypes *types, __isl_keep pet_context *pc)
2954 int i, n;
2955 isl_id *id;
2956 struct pet_array *array;
2958 id = isl_id_list_get_id(decls, 0);
2959 array = extract_array(id, types, pc);
2960 isl_id_free(id);
2962 n = isl_id_list_n_id(decls);
2963 for (i = 1; i < n; ++i) {
2964 struct pet_array *parent;
2965 const char *base_name, *field_name;
2966 char *product_name;
2968 parent = array;
2969 id = isl_id_list_get_id(decls, i);
2970 array = extract_array(id, types, pc);
2971 isl_id_free(id);
2972 if (!array)
2973 return pet_array_free(parent);
2975 base_name = isl_set_get_tuple_name(parent->extent);
2976 field_name = isl_set_get_tuple_name(array->extent);
2977 product_name = pet_array_member_access_name(ctx,
2978 base_name, field_name);
2980 array->extent = isl_set_product(isl_set_copy(parent->extent),
2981 array->extent);
2982 if (product_name)
2983 array->extent = isl_set_set_tuple_name(array->extent,
2984 product_name);
2985 array->context = isl_set_intersect(array->context,
2986 isl_set_copy(parent->context));
2988 pet_array_free(parent);
2989 free(product_name);
2991 if (!array->extent || !array->context || !product_name)
2992 return pet_array_free(array);
2995 return array;
2998 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2999 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
3000 std::set<TypeDecl *> &types_done);
3001 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3002 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
3003 std::set<TypeDecl *> &types_done);
3005 /* For each of the fields of "decl" that is itself a record type
3006 * or a typedef, or an array of such type, add a corresponding pet_type
3007 * to "scop".
3009 static struct pet_scop *add_field_types(isl_ctx *ctx, struct pet_scop *scop,
3010 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
3011 std::set<TypeDecl *> &types_done)
3013 RecordDecl::field_iterator it;
3015 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
3016 QualType type = it->getType();
3018 type = pet_clang_base_or_typedef_type(type);
3019 if (isa<TypedefType>(type)) {
3020 TypedefNameDecl *typedefdecl;
3022 typedefdecl = cast<TypedefType>(type)->getDecl();
3023 scop = add_type(ctx, scop, typedefdecl,
3024 PP, types, types_done);
3025 } else if (type->isRecordType()) {
3026 RecordDecl *record;
3028 record = pet_clang_record_decl(type);
3029 scop = add_type(ctx, scop, record,
3030 PP, types, types_done);
3034 return scop;
3037 /* Add a pet_type corresponding to "decl" to "scop", provided
3038 * it is a member of types.records and it has not been added before
3039 * (i.e., it is not a member of "types_done").
3041 * Since we want the user to be able to print the types
3042 * in the order in which they appear in the scop, we need to
3043 * make sure that types of fields in a structure appear before
3044 * that structure. We therefore call ourselves recursively
3045 * through add_field_types on the types of all record subfields.
3047 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3048 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
3049 std::set<TypeDecl *> &types_done)
3051 string s;
3052 llvm::raw_string_ostream S(s);
3054 if (types.records.find(decl) == types.records.end())
3055 return scop;
3056 if (types_done.find(decl) != types_done.end())
3057 return scop;
3059 add_field_types(ctx, scop, decl, PP, types, types_done);
3061 if (strlen(decl->getName().str().c_str()) == 0)
3062 return scop;
3064 decl->print(S, PrintingPolicy(PP.getLangOpts()));
3065 S.str();
3067 scop->types[scop->n_type] = pet_type_alloc(ctx,
3068 decl->getName().str().c_str(), s.c_str());
3069 if (!scop->types[scop->n_type])
3070 return pet_scop_free(scop);
3072 types_done.insert(decl);
3074 scop->n_type++;
3076 return scop;
3079 /* Add a pet_type corresponding to "decl" to "scop", provided
3080 * it is a member of types.typedefs and it has not been added before
3081 * (i.e., it is not a member of "types_done").
3083 * If the underlying type is a structure, then we print the typedef
3084 * ourselves since clang does not print the definition of the structure
3085 * in the typedef. We also make sure in this case that the types of
3086 * the fields in the structure are added first.
3087 * Since the definition of the structure also gets printed this way,
3088 * add it to types_done such that it will not be printed again,
3089 * not even without the typedef.
3091 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3092 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
3093 std::set<TypeDecl *> &types_done)
3095 string s;
3096 llvm::raw_string_ostream S(s);
3097 QualType qt = decl->getUnderlyingType();
3099 if (types.typedefs.find(decl) == types.typedefs.end())
3100 return scop;
3101 if (types_done.find(decl) != types_done.end())
3102 return scop;
3104 if (qt->isRecordType()) {
3105 RecordDecl *rec = pet_clang_record_decl(qt);
3107 add_field_types(ctx, scop, rec, PP, types, types_done);
3108 S << "typedef ";
3109 rec->print(S, PrintingPolicy(PP.getLangOpts()));
3110 S << " ";
3111 S << decl->getName();
3112 types_done.insert(rec);
3113 } else {
3114 decl->print(S, PrintingPolicy(PP.getLangOpts()));
3116 S.str();
3118 scop->types[scop->n_type] = pet_type_alloc(ctx,
3119 decl->getName().str().c_str(), s.c_str());
3120 if (!scop->types[scop->n_type])
3121 return pet_scop_free(scop);
3123 types_done.insert(decl);
3125 scop->n_type++;
3127 return scop;
3130 /* Construct a list of pet_arrays, one for each array (or scalar)
3131 * accessed inside "scop", add this list to "scop" and return the result.
3132 * The upper bounds of the arrays are converted to affine expressions
3133 * within the context "pc".
3135 * The context of "scop" is updated with the intersection of
3136 * the contexts of all arrays, i.e., constraints on the parameters
3137 * that ensure that the arrays have a valid (non-negative) size.
3139 * If any of the extracted arrays refers to a member access or
3140 * has a typedef'd type as base type,
3141 * then also add the required types to "scop".
3142 * The typedef types are printed first because their definitions
3143 * may include the definition of a struct and these struct definitions
3144 * should not be printed separately. While the typedef definition
3145 * is being printed, the struct is marked as having been printed as well,
3146 * such that the later printing of the struct by itself can be prevented.
3148 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
3149 __isl_keep pet_context *pc)
3151 int i, n;
3152 array_desc_set arrays;
3153 array_desc_set::iterator it;
3154 PetTypes types;
3155 std::set<TypeDecl *> types_done;
3156 std::set<clang::RecordDecl *, less_name>::iterator records_it;
3157 std::set<clang::TypedefNameDecl *, less_name>::iterator typedefs_it;
3158 int n_array;
3159 struct pet_array **scop_arrays;
3161 if (!scop)
3162 return NULL;
3164 pet_scop_collect_arrays(scop, arrays);
3165 if (arrays.size() == 0)
3166 return scop;
3168 n_array = scop->n_array;
3170 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3171 n_array + arrays.size());
3172 if (!scop_arrays)
3173 goto error;
3174 scop->arrays = scop_arrays;
3176 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3177 struct pet_array *array;
3178 array = extract_array(*it, &types, pc);
3179 scop->arrays[n_array + i] = array;
3180 if (!scop->arrays[n_array + i])
3181 goto error;
3182 scop->n_array++;
3183 scop->context = isl_set_intersect(scop->context,
3184 isl_set_copy(array->context));
3185 if (!scop->context)
3186 goto error;
3189 n = types.records.size() + types.typedefs.size();
3190 if (n == 0)
3191 return scop;
3193 scop->types = isl_alloc_array(ctx, struct pet_type *, n);
3194 if (!scop->types)
3195 goto error;
3197 for (typedefs_it = types.typedefs.begin();
3198 typedefs_it != types.typedefs.end(); ++typedefs_it)
3199 scop = add_type(ctx, scop, *typedefs_it, PP, types, types_done);
3201 for (records_it = types.records.begin();
3202 records_it != types.records.end(); ++records_it)
3203 scop = add_type(ctx, scop, *records_it, PP, types, types_done);
3205 return scop;
3206 error:
3207 pet_scop_free(scop);
3208 return NULL;
3211 /* Bound all parameters in scop->context to the possible values
3212 * of the corresponding C variable.
3214 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
3216 int n;
3218 if (!scop)
3219 return NULL;
3221 n = isl_set_dim(scop->context, isl_dim_param);
3222 for (int i = 0; i < n; ++i) {
3223 isl_id *id;
3224 ValueDecl *decl;
3226 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
3227 if (pet_nested_in_id(id)) {
3228 isl_id_free(id);
3229 isl_die(isl_set_get_ctx(scop->context),
3230 isl_error_internal,
3231 "unresolved nested parameter", goto error);
3233 decl = pet_id_get_decl(id);
3234 isl_id_free(id);
3236 scop->context = set_parameter_bounds(scop->context, i, decl);
3238 if (!scop->context)
3239 goto error;
3242 return scop;
3243 error:
3244 pet_scop_free(scop);
3245 return NULL;
3248 /* Construct a pet_scop from the given function.
3250 * If the scop was delimited by scop and endscop pragmas, then we override
3251 * the file offsets by those derived from the pragmas.
3253 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3255 pet_scop *scop;
3256 Stmt *stmt;
3258 stmt = fd->getBody();
3260 if (options->autodetect) {
3261 set_current_stmt(stmt);
3262 scop = extract_scop(extract(stmt, true));
3263 } else {
3264 current_line = loc.start_line;
3265 scop = scan(stmt);
3266 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
3268 scop = add_parameter_bounds(scop);
3269 scop = pet_scop_gist(scop, value_bounds);
3271 return scop;
3274 /* Update this->last_line and this->current_line based on the fact
3275 * that we are about to consider "stmt".
3277 void PetScan::set_current_stmt(Stmt *stmt)
3279 SourceLocation loc = stmt->getLocStart();
3280 SourceManager &SM = PP.getSourceManager();
3282 last_line = current_line;
3283 current_line = SM.getExpansionLineNumber(loc);
3286 /* Is the current statement marked by an independent pragma?
3287 * That is, is there an independent pragma on a line between
3288 * the line of the current statement and the line of the previous statement.
3289 * The search is not implemented very efficiently. We currently
3290 * assume that there are only a few independent pragmas, if any.
3292 bool PetScan::is_current_stmt_marked_independent()
3294 for (unsigned i = 0; i < independent.size(); ++i) {
3295 unsigned line = independent[i].line;
3297 if (last_line < line && line < current_line)
3298 return true;
3301 return false;