PetScan::extract: always treat compound statement as a block
[pet.git] / scan.cc
blob4ce21059b15b098c6945b2777d61c86d772f1083
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2015 Ecole Normale Superieure. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
32 * Leiden University.
33 */
35 #include "config.h"
37 #include <string.h>
38 #include <set>
39 #include <map>
40 #include <iostream>
41 #include <llvm/Support/raw_ostream.h>
42 #include <clang/AST/ASTContext.h>
43 #include <clang/AST/ASTDiagnostic.h>
44 #include <clang/AST/Attr.h>
45 #include <clang/AST/Expr.h>
46 #include <clang/AST/RecursiveASTVisitor.h>
48 #include <isl/id.h>
49 #include <isl/space.h>
50 #include <isl/aff.h>
51 #include <isl/set.h>
52 #include <isl/union_set.h>
54 #include "aff.h"
55 #include "array.h"
56 #include "clang.h"
57 #include "context.h"
58 #include "expr.h"
59 #include "nest.h"
60 #include "options.h"
61 #include "scan.h"
62 #include "scop.h"
63 #include "scop_plus.h"
64 #include "tree.h"
65 #include "tree2scop.h"
67 using namespace std;
68 using namespace clang;
70 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
72 switch (kind) {
73 case UO_Minus:
74 return pet_op_minus;
75 case UO_Not:
76 return pet_op_not;
77 case UO_LNot:
78 return pet_op_lnot;
79 case UO_PostInc:
80 return pet_op_post_inc;
81 case UO_PostDec:
82 return pet_op_post_dec;
83 case UO_PreInc:
84 return pet_op_pre_inc;
85 case UO_PreDec:
86 return pet_op_pre_dec;
87 default:
88 return pet_op_last;
92 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
94 switch (kind) {
95 case BO_AddAssign:
96 return pet_op_add_assign;
97 case BO_SubAssign:
98 return pet_op_sub_assign;
99 case BO_MulAssign:
100 return pet_op_mul_assign;
101 case BO_DivAssign:
102 return pet_op_div_assign;
103 case BO_Assign:
104 return pet_op_assign;
105 case BO_Add:
106 return pet_op_add;
107 case BO_Sub:
108 return pet_op_sub;
109 case BO_Mul:
110 return pet_op_mul;
111 case BO_Div:
112 return pet_op_div;
113 case BO_Rem:
114 return pet_op_mod;
115 case BO_Shl:
116 return pet_op_shl;
117 case BO_Shr:
118 return pet_op_shr;
119 case BO_EQ:
120 return pet_op_eq;
121 case BO_NE:
122 return pet_op_ne;
123 case BO_LE:
124 return pet_op_le;
125 case BO_GE:
126 return pet_op_ge;
127 case BO_LT:
128 return pet_op_lt;
129 case BO_GT:
130 return pet_op_gt;
131 case BO_And:
132 return pet_op_and;
133 case BO_Xor:
134 return pet_op_xor;
135 case BO_Or:
136 return pet_op_or;
137 case BO_LAnd:
138 return pet_op_land;
139 case BO_LOr:
140 return pet_op_lor;
141 default:
142 return pet_op_last;
146 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
147 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
149 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
150 SourceLocation(), var, false, var->getInnerLocStart(),
151 var->getType(), VK_LValue);
153 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
154 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
156 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
157 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
158 VK_LValue);
160 #else
161 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
163 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
164 var, var->getInnerLocStart(), var->getType(), VK_LValue);
166 #endif
168 #ifdef GETTYPEINFORETURNSTYPEINFO
170 static int size_in_bytes(ASTContext &context, QualType type)
172 return context.getTypeInfo(type).Width / 8;
175 #else
177 static int size_in_bytes(ASTContext &context, QualType type)
179 return context.getTypeInfo(type).first / 8;
182 #endif
184 /* Check if the element type corresponding to the given array type
185 * has a const qualifier.
187 static bool const_base(QualType qt)
189 const Type *type = qt.getTypePtr();
191 if (type->isPointerType())
192 return const_base(type->getPointeeType());
193 if (type->isArrayType()) {
194 const ArrayType *atype;
195 type = type->getCanonicalTypeInternal().getTypePtr();
196 atype = cast<ArrayType>(type);
197 return const_base(atype->getElementType());
200 return qt.isConstQualified();
203 /* Create an isl_id that refers to the named declarator "decl".
205 static __isl_give isl_id *create_decl_id(isl_ctx *ctx, NamedDecl *decl)
207 return isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
210 PetScan::~PetScan()
212 std::map<const Type *, pet_expr *>::iterator it;
213 std::map<FunctionDecl *, pet_function_summary *>::iterator it_s;
215 for (it = type_size.begin(); it != type_size.end(); ++it)
216 pet_expr_free(it->second);
217 for (it_s = summary_cache.begin(); it_s != summary_cache.end(); ++it_s)
218 pet_function_summary_free(it_s->second);
220 isl_union_map_free(value_bounds);
223 /* Report a diagnostic, unless autodetect is set.
225 void PetScan::report(Stmt *stmt, unsigned id)
227 if (options->autodetect)
228 return;
230 SourceLocation loc = stmt->getLocStart();
231 DiagnosticsEngine &diag = PP.getDiagnostics();
232 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
235 /* Called if we found something we (currently) cannot handle.
236 * We'll provide more informative warnings later.
238 * We only actually complain if autodetect is false.
240 void PetScan::unsupported(Stmt *stmt)
242 DiagnosticsEngine &diag = PP.getDiagnostics();
243 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
244 "unsupported");
245 report(stmt, id);
248 /* Report an unsupported statement type, unless autodetect is set.
250 void PetScan::report_unsupported_statement_type(Stmt *stmt)
252 DiagnosticsEngine &diag = PP.getDiagnostics();
253 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
254 "this type of statement is not supported");
255 report(stmt, id);
258 /* Report a missing prototype, unless autodetect is set.
260 void PetScan::report_prototype_required(Stmt *stmt)
262 DiagnosticsEngine &diag = PP.getDiagnostics();
263 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
264 "prototype required");
265 report(stmt, id);
268 /* Report a missing increment, unless autodetect is set.
270 void PetScan::report_missing_increment(Stmt *stmt)
272 DiagnosticsEngine &diag = PP.getDiagnostics();
273 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
274 "missing increment");
275 report(stmt, id);
278 /* Report a missing summary function, unless autodetect is set.
280 void PetScan::report_missing_summary_function(Stmt *stmt)
282 DiagnosticsEngine &diag = PP.getDiagnostics();
283 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
284 "missing summary function");
285 report(stmt, id);
288 /* Report a missing summary function body, unless autodetect is set.
290 void PetScan::report_missing_summary_function_body(Stmt *stmt)
292 DiagnosticsEngine &diag = PP.getDiagnostics();
293 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
294 "missing summary function body");
295 report(stmt, id);
298 /* Extract an integer from "val", which is assumed to be non-negative.
300 static __isl_give isl_val *extract_unsigned(isl_ctx *ctx,
301 const llvm::APInt &val)
303 unsigned n;
304 const uint64_t *data;
306 data = val.getRawData();
307 n = val.getNumWords();
308 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
311 /* Extract an integer from "val". If "is_signed" is set, then "val"
312 * is signed. Otherwise it it unsigned.
314 static __isl_give isl_val *extract_int(isl_ctx *ctx, bool is_signed,
315 llvm::APInt val)
317 int is_negative = is_signed && val.isNegative();
318 isl_val *v;
320 if (is_negative)
321 val = -val;
323 v = extract_unsigned(ctx, val);
325 if (is_negative)
326 v = isl_val_neg(v);
327 return v;
330 /* Extract an integer from "expr".
332 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
334 const Type *type = expr->getType().getTypePtr();
335 bool is_signed = type->hasSignedIntegerRepresentation();
337 return ::extract_int(ctx, is_signed, expr->getValue());
340 /* Extract an integer from "expr".
341 * Return NULL if "expr" does not (obviously) represent an integer.
343 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
345 return extract_int(expr->getSubExpr());
348 /* Extract an integer from "expr".
349 * Return NULL if "expr" does not (obviously) represent an integer.
351 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
353 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
354 return extract_int(ctx, cast<IntegerLiteral>(expr));
355 if (expr->getStmtClass() == Stmt::ParenExprClass)
356 return extract_int(cast<ParenExpr>(expr));
358 unsupported(expr);
359 return NULL;
362 /* Extract a pet_expr from the APInt "val", which is assumed
363 * to be non-negative.
365 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
367 return pet_expr_new_int(extract_unsigned(ctx, val));
370 /* Return the number of bits needed to represent the type "qt",
371 * if it is an integer type. Otherwise return 0.
372 * If qt is signed then return the opposite of the number of bits.
374 static int get_type_size(QualType qt, ASTContext &ast_context)
376 int size;
378 if (!qt->isIntegerType())
379 return 0;
381 size = ast_context.getIntWidth(qt);
382 if (!qt->isUnsignedIntegerType())
383 size = -size;
385 return size;
388 /* Return the number of bits needed to represent the type of "decl",
389 * if it is an integer type. Otherwise return 0.
390 * If qt is signed then return the opposite of the number of bits.
392 static int get_type_size(ValueDecl *decl)
394 return get_type_size(decl->getType(), decl->getASTContext());
397 /* Bound parameter "pos" of "set" to the possible values of "decl".
399 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
400 unsigned pos, ValueDecl *decl)
402 int type_size;
403 isl_ctx *ctx;
404 isl_val *bound;
406 ctx = isl_set_get_ctx(set);
407 type_size = get_type_size(decl);
408 if (type_size == 0)
409 isl_die(ctx, isl_error_invalid, "not an integer type",
410 return isl_set_free(set));
411 if (type_size > 0) {
412 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
413 bound = isl_val_int_from_ui(ctx, type_size);
414 bound = isl_val_2exp(bound);
415 bound = isl_val_sub_ui(bound, 1);
416 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
417 } else {
418 bound = isl_val_int_from_ui(ctx, -type_size - 1);
419 bound = isl_val_2exp(bound);
420 bound = isl_val_sub_ui(bound, 1);
421 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
422 isl_val_copy(bound));
423 bound = isl_val_neg(bound);
424 bound = isl_val_sub_ui(bound, 1);
425 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
428 return set;
431 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
433 return extract_index_expr(expr->getSubExpr());
436 /* Return the depth of an array of the given type.
438 static int array_depth(const Type *type)
440 if (type->isPointerType())
441 return 1 + array_depth(type->getPointeeType().getTypePtr());
442 if (type->isArrayType()) {
443 const ArrayType *atype;
444 type = type->getCanonicalTypeInternal().getTypePtr();
445 atype = cast<ArrayType>(type);
446 return 1 + array_depth(atype->getElementType().getTypePtr());
448 return 0;
451 /* Return the depth of the array accessed by the index expression "index".
452 * If "index" is an affine expression, i.e., if it does not access
453 * any array, then return 1.
454 * If "index" represent a member access, i.e., if its range is a wrapped
455 * relation, then return the sum of the depth of the array of structures
456 * and that of the member inside the structure.
458 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
460 isl_id *id;
461 ValueDecl *decl;
463 if (!index)
464 return -1;
466 if (isl_multi_pw_aff_range_is_wrapping(index)) {
467 int domain_depth, range_depth;
468 isl_multi_pw_aff *domain, *range;
470 domain = isl_multi_pw_aff_copy(index);
471 domain = isl_multi_pw_aff_range_factor_domain(domain);
472 domain_depth = extract_depth(domain);
473 isl_multi_pw_aff_free(domain);
474 range = isl_multi_pw_aff_copy(index);
475 range = isl_multi_pw_aff_range_factor_range(range);
476 range_depth = extract_depth(range);
477 isl_multi_pw_aff_free(range);
479 return domain_depth + range_depth;
482 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
483 return 1;
485 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
486 if (!id)
487 return -1;
488 decl = (ValueDecl *) isl_id_get_user(id);
489 isl_id_free(id);
491 return array_depth(decl->getType().getTypePtr());
494 /* Return the depth of the array accessed by the access expression "expr".
496 static int extract_depth(__isl_keep pet_expr *expr)
498 isl_multi_pw_aff *index;
499 int depth;
501 index = pet_expr_access_get_index(expr);
502 depth = extract_depth(index);
503 isl_multi_pw_aff_free(index);
505 return depth;
508 /* Construct a pet_expr representing an index expression for an access
509 * to the variable referenced by "expr".
511 * If "expr" references an enum constant, then return an integer expression
512 * instead, representing the value of the enum constant.
514 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
516 return extract_index_expr(expr->getDecl());
519 /* Construct a pet_expr representing an index expression for an access
520 * to the variable "decl".
522 * If "decl" is an enum constant, then we return an integer expression
523 * instead, representing the value of the enum constant.
525 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
527 isl_id *id;
528 isl_space *space;
530 if (isa<EnumConstantDecl>(decl))
531 return extract_expr(cast<EnumConstantDecl>(decl));
533 id = create_decl_id(ctx, decl);
534 space = isl_space_alloc(ctx, 0, 0, 0);
535 space = isl_space_set_tuple_id(space, isl_dim_out, id);
537 return pet_expr_from_index(isl_multi_pw_aff_zero(space));
540 /* Construct a pet_expr representing the index expression "expr"
541 * Return NULL on error.
543 * If "expr" is a reference to an enum constant, then return
544 * an integer expression instead, representing the value of the enum constant.
546 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
548 switch (expr->getStmtClass()) {
549 case Stmt::ImplicitCastExprClass:
550 return extract_index_expr(cast<ImplicitCastExpr>(expr));
551 case Stmt::DeclRefExprClass:
552 return extract_index_expr(cast<DeclRefExpr>(expr));
553 case Stmt::ArraySubscriptExprClass:
554 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
555 case Stmt::IntegerLiteralClass:
556 return extract_expr(cast<IntegerLiteral>(expr));
557 case Stmt::MemberExprClass:
558 return extract_index_expr(cast<MemberExpr>(expr));
559 default:
560 unsupported(expr);
562 return NULL;
565 /* Extract an index expression from the given array subscript expression.
567 * We first extract an index expression from the base.
568 * This will result in an index expression with a range that corresponds
569 * to the earlier indices.
570 * We then extract the current index and let
571 * pet_expr_access_subscript combine the two.
573 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
575 Expr *base = expr->getBase();
576 Expr *idx = expr->getIdx();
577 pet_expr *index;
578 pet_expr *base_expr;
580 base_expr = extract_index_expr(base);
581 index = extract_expr(idx);
583 base_expr = pet_expr_access_subscript(base_expr, index);
585 return base_expr;
588 /* Extract an index expression from a member expression.
590 * If the base access (to the structure containing the member)
591 * is of the form
593 * A[..]
595 * and the member is called "f", then the member access is of
596 * the form
598 * A_f[A[..] -> f[]]
600 * If the member access is to an anonymous struct, then simply return
602 * A[..]
604 * If the member access in the source code is of the form
606 * A->f
608 * then it is treated as
610 * A[0].f
612 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
614 Expr *base = expr->getBase();
615 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
616 pet_expr *base_index;
617 isl_id *id;
619 base_index = extract_index_expr(base);
621 if (expr->isArrow()) {
622 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
623 base_index = pet_expr_access_subscript(base_index, index);
626 if (field->isAnonymousStructOrUnion())
627 return base_index;
629 id = create_decl_id(ctx, field);
631 return pet_expr_access_member(base_index, id);
634 /* Mark the given access pet_expr as a write.
636 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
638 access = pet_expr_access_set_write(access, 1);
639 access = pet_expr_access_set_read(access, 0);
641 return access;
644 /* Mark the given (read) access pet_expr as also possibly being written.
645 * That is, initialize the may write access relation from the may read relation
646 * and initialize the must write access relation to the empty relation.
648 static __isl_give pet_expr *mark_may_write(__isl_take pet_expr *expr)
650 isl_union_map *access;
651 isl_union_map *empty;
653 access = pet_expr_access_get_dependent_access(expr,
654 pet_expr_access_may_read);
655 empty = isl_union_map_empty(isl_union_map_get_space(access));
656 expr = pet_expr_access_set_access(expr, pet_expr_access_may_write,
657 access);
658 expr = pet_expr_access_set_access(expr, pet_expr_access_must_write,
659 empty);
661 return expr;
664 /* Construct a pet_expr representing a unary operator expression.
666 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
668 int type_size;
669 pet_expr *arg;
670 enum pet_op_type op;
672 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
673 if (op == pet_op_last) {
674 unsupported(expr);
675 return NULL;
678 arg = extract_expr(expr->getSubExpr());
680 if (expr->isIncrementDecrementOp() &&
681 pet_expr_get_type(arg) == pet_expr_access) {
682 arg = mark_write(arg);
683 arg = pet_expr_access_set_read(arg, 1);
686 type_size = get_type_size(expr->getType(), ast_context);
687 return pet_expr_new_unary(type_size, op, arg);
690 /* Construct a pet_expr representing a binary operator expression.
692 * If the top level operator is an assignment and the LHS is an access,
693 * then we mark that access as a write. If the operator is a compound
694 * assignment, the access is marked as both a read and a write.
696 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
698 int type_size;
699 pet_expr *lhs, *rhs;
700 enum pet_op_type op;
702 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
703 if (op == pet_op_last) {
704 unsupported(expr);
705 return NULL;
708 lhs = extract_expr(expr->getLHS());
709 rhs = extract_expr(expr->getRHS());
711 if (expr->isAssignmentOp() &&
712 pet_expr_get_type(lhs) == pet_expr_access) {
713 lhs = mark_write(lhs);
714 if (expr->isCompoundAssignmentOp())
715 lhs = pet_expr_access_set_read(lhs, 1);
718 type_size = get_type_size(expr->getType(), ast_context);
719 return pet_expr_new_binary(type_size, op, lhs, rhs);
722 /* Construct a pet_tree for a (single) variable declaration.
724 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
726 Decl *decl;
727 VarDecl *vd;
728 pet_expr *lhs, *rhs;
729 pet_tree *tree;
731 if (!stmt->isSingleDecl()) {
732 unsupported(stmt);
733 return NULL;
736 decl = stmt->getSingleDecl();
737 vd = cast<VarDecl>(decl);
739 lhs = extract_access_expr(vd);
740 lhs = mark_write(lhs);
741 if (!vd->getInit())
742 tree = pet_tree_new_decl(lhs);
743 else {
744 rhs = extract_expr(vd->getInit());
745 tree = pet_tree_new_decl_init(lhs, rhs);
748 return tree;
751 /* Construct a pet_expr representing a conditional operation.
753 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
755 pet_expr *cond, *lhs, *rhs;
756 isl_pw_aff *pa;
758 cond = extract_expr(expr->getCond());
759 lhs = extract_expr(expr->getTrueExpr());
760 rhs = extract_expr(expr->getFalseExpr());
762 return pet_expr_new_ternary(cond, lhs, rhs);
765 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
767 return extract_expr(expr->getSubExpr());
770 /* Construct a pet_expr representing a floating point value.
772 * If the floating point literal does not appear in a macro,
773 * then we use the original representation in the source code
774 * as the string representation. Otherwise, we use the pretty
775 * printer to produce a string representation.
777 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
779 double d;
780 string s;
781 const LangOptions &LO = PP.getLangOpts();
782 SourceLocation loc = expr->getLocation();
784 if (!loc.isMacroID()) {
785 SourceManager &SM = PP.getSourceManager();
786 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
787 s = string(SM.getCharacterData(loc), len);
788 } else {
789 llvm::raw_string_ostream S(s);
790 expr->printPretty(S, 0, PrintingPolicy(LO));
791 S.str();
793 d = expr->getValueAsApproximateDouble();
794 return pet_expr_new_double(ctx, d, s.c_str());
797 /* Convert the index expression "index" into an access pet_expr of type "qt".
799 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
800 __isl_take pet_expr *index)
802 int depth;
803 int type_size;
805 depth = extract_depth(index);
806 type_size = get_type_size(qt, ast_context);
808 index = pet_expr_set_type_size(index, type_size);
809 index = pet_expr_access_set_depth(index, depth);
811 return index;
814 /* Extract an index expression from "expr" and then convert it into
815 * an access pet_expr.
817 * If "expr" is a reference to an enum constant, then return
818 * an integer expression instead, representing the value of the enum constant.
820 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
822 pet_expr *index;
824 index = extract_index_expr(expr);
826 if (pet_expr_get_type(index) == pet_expr_int)
827 return index;
829 return extract_access_expr(expr->getType(), index);
832 /* Extract an index expression from "decl" and then convert it into
833 * an access pet_expr.
835 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
837 return extract_access_expr(decl->getType(), extract_index_expr(decl));
840 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
842 return extract_expr(expr->getSubExpr());
845 /* Extract an assume statement from the argument "expr"
846 * of a __pencil_assume statement.
848 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
850 return pet_expr_new_unary(0, pet_op_assume, extract_expr(expr));
853 /* Construct a pet_expr corresponding to the function call argument "expr".
854 * The argument appears in position "pos" of a call to function "fd".
856 * If we are passing along a pointer to an array element
857 * or an entire row or even higher dimensional slice of an array,
858 * then the function being called may write into the array.
860 * We assume here that if the function is declared to take a pointer
861 * to a const type, then the function may only perform a read
862 * and that otherwise, it may either perform a read or a write (or both).
863 * We only perform this check if "detect_writes" is set.
865 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
866 Expr *expr, bool detect_writes)
868 pet_expr *res;
869 int is_addr = 0, is_partial = 0;
871 while (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
872 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
873 expr = ice->getSubExpr();
875 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
876 UnaryOperator *op = cast<UnaryOperator>(expr);
877 if (op->getOpcode() == UO_AddrOf) {
878 is_addr = 1;
879 expr = op->getSubExpr();
882 res = extract_expr(expr);
883 if (!res)
884 return NULL;
885 if (array_depth(expr->getType().getTypePtr()) > 0)
886 is_partial = 1;
887 if (detect_writes && (is_addr || is_partial) &&
888 pet_expr_get_type(res) == pet_expr_access) {
889 ParmVarDecl *parm;
890 if (!fd->hasPrototype()) {
891 report_prototype_required(expr);
892 return pet_expr_free(res);
894 parm = fd->getParamDecl(pos);
895 if (!const_base(parm->getType()))
896 res = mark_may_write(res);
899 if (is_addr)
900 res = pet_expr_new_unary(0, pet_op_address_of, res);
901 return res;
904 /* Find the first FunctionDecl with the given name.
905 * "call" is the corresponding call expression and is only used
906 * for reporting errors.
908 * Return NULL on error.
910 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
912 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
913 DeclContext::decl_iterator begin = tu->decls_begin();
914 DeclContext::decl_iterator end = tu->decls_end();
915 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
916 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
917 if (!fd)
918 continue;
919 if (fd->getName().str().compare(name) != 0)
920 continue;
921 if (fd->hasBody())
922 return fd;
923 report_missing_summary_function_body(call);
924 return NULL;
926 report_missing_summary_function(call);
927 return NULL;
930 /* Return the FunctionDecl for the summary function associated to the
931 * function called by "call".
933 * In particular, if the pencil option is set, then
934 * search for an annotate attribute formatted as
935 * "pencil_access(name)", where "name" is the name of the summary function.
937 * If no summary function was specified, then return the FunctionDecl
938 * that is actually being called.
940 * Return NULL on error.
942 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
944 FunctionDecl *decl = call->getDirectCallee();
945 if (!decl)
946 return NULL;
948 if (!options->pencil)
949 return decl;
951 specific_attr_iterator<AnnotateAttr> begin, end, i;
952 begin = decl->specific_attr_begin<AnnotateAttr>();
953 end = decl->specific_attr_end<AnnotateAttr>();
954 for (i = begin; i != end; ++i) {
955 string attr = (*i)->getAnnotation().str();
957 const char prefix[] = "pencil_access(";
958 size_t start = attr.find(prefix);
959 if (start == string::npos)
960 continue;
961 start += strlen(prefix);
962 string name = attr.substr(start, attr.find(')') - start);
964 return find_decl_from_name(call, name);
967 return decl;
970 /* Construct a pet_expr representing a function call.
972 * In the special case of a "call" to __pencil_assume,
973 * construct an assume expression instead.
975 * In the case of a "call" to __pencil_kill, the arguments
976 * are neither read nor written (only killed), so there
977 * is no need to check for writes to these arguments.
979 * __pencil_assume and __pencil_kill are only recognized
980 * when the pencil option is set.
982 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
984 pet_expr *res = NULL;
985 FunctionDecl *fd;
986 string name;
987 unsigned n_arg;
988 bool is_kill;
990 fd = expr->getDirectCallee();
991 if (!fd) {
992 unsupported(expr);
993 return NULL;
996 name = fd->getDeclName().getAsString();
997 n_arg = expr->getNumArgs();
999 if (options->pencil && n_arg == 1 && name == "__pencil_assume")
1000 return extract_assume(expr->getArg(0));
1001 is_kill = options->pencil && name == "__pencil_kill";
1003 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1004 if (!res)
1005 return NULL;
1007 for (int i = 0; i < n_arg; ++i) {
1008 Expr *arg = expr->getArg(i);
1009 res = pet_expr_set_arg(res, i,
1010 PetScan::extract_argument(fd, i, arg, !is_kill));
1013 fd = get_summary_function(expr);
1014 if (!fd)
1015 return pet_expr_free(res);
1017 res = set_summary(res, fd);
1019 return res;
1022 /* Construct a pet_expr representing a (C style) cast.
1024 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1026 pet_expr *arg;
1027 QualType type;
1029 arg = extract_expr(expr->getSubExpr());
1030 if (!arg)
1031 return NULL;
1033 type = expr->getTypeAsWritten();
1034 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1037 /* Construct a pet_expr representing an integer.
1039 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1041 return pet_expr_new_int(extract_int(expr));
1044 /* Construct a pet_expr representing the integer enum constant "ecd".
1046 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
1048 isl_val *v;
1049 const llvm::APSInt &init = ecd->getInitVal();
1050 v = ::extract_int(ctx, init.isSigned(), init);
1051 return pet_expr_new_int(v);
1054 /* Try and construct a pet_expr representing "expr".
1056 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1058 switch (expr->getStmtClass()) {
1059 case Stmt::UnaryOperatorClass:
1060 return extract_expr(cast<UnaryOperator>(expr));
1061 case Stmt::CompoundAssignOperatorClass:
1062 case Stmt::BinaryOperatorClass:
1063 return extract_expr(cast<BinaryOperator>(expr));
1064 case Stmt::ImplicitCastExprClass:
1065 return extract_expr(cast<ImplicitCastExpr>(expr));
1066 case Stmt::ArraySubscriptExprClass:
1067 case Stmt::DeclRefExprClass:
1068 case Stmt::MemberExprClass:
1069 return extract_access_expr(expr);
1070 case Stmt::IntegerLiteralClass:
1071 return extract_expr(cast<IntegerLiteral>(expr));
1072 case Stmt::FloatingLiteralClass:
1073 return extract_expr(cast<FloatingLiteral>(expr));
1074 case Stmt::ParenExprClass:
1075 return extract_expr(cast<ParenExpr>(expr));
1076 case Stmt::ConditionalOperatorClass:
1077 return extract_expr(cast<ConditionalOperator>(expr));
1078 case Stmt::CallExprClass:
1079 return extract_expr(cast<CallExpr>(expr));
1080 case Stmt::CStyleCastExprClass:
1081 return extract_expr(cast<CStyleCastExpr>(expr));
1082 default:
1083 unsupported(expr);
1085 return NULL;
1088 /* Check if the given initialization statement is an assignment.
1089 * If so, return that assignment. Otherwise return NULL.
1091 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1093 BinaryOperator *ass;
1095 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1096 return NULL;
1098 ass = cast<BinaryOperator>(init);
1099 if (ass->getOpcode() != BO_Assign)
1100 return NULL;
1102 return ass;
1105 /* Check if the given initialization statement is a declaration
1106 * of a single variable.
1107 * If so, return that declaration. Otherwise return NULL.
1109 Decl *PetScan::initialization_declaration(Stmt *init)
1111 DeclStmt *decl;
1113 if (init->getStmtClass() != Stmt::DeclStmtClass)
1114 return NULL;
1116 decl = cast<DeclStmt>(init);
1118 if (!decl->isSingleDecl())
1119 return NULL;
1121 return decl->getSingleDecl();
1124 /* Given the assignment operator in the initialization of a for loop,
1125 * extract the induction variable, i.e., the (integer)variable being
1126 * assigned.
1128 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1130 Expr *lhs;
1131 DeclRefExpr *ref;
1132 ValueDecl *decl;
1133 const Type *type;
1135 lhs = init->getLHS();
1136 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1137 unsupported(init);
1138 return NULL;
1141 ref = cast<DeclRefExpr>(lhs);
1142 decl = ref->getDecl();
1143 type = decl->getType().getTypePtr();
1145 if (!type->isIntegerType()) {
1146 unsupported(lhs);
1147 return NULL;
1150 return decl;
1153 /* Given the initialization statement of a for loop and the single
1154 * declaration in this initialization statement,
1155 * extract the induction variable, i.e., the (integer) variable being
1156 * declared.
1158 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1160 VarDecl *vd;
1162 vd = cast<VarDecl>(decl);
1164 const QualType type = vd->getType();
1165 if (!type->isIntegerType()) {
1166 unsupported(init);
1167 return NULL;
1170 if (!vd->getInit()) {
1171 unsupported(init);
1172 return NULL;
1175 return vd;
1178 /* Check that op is of the form iv++ or iv--.
1179 * Return a pet_expr representing "1" or "-1" accordingly.
1181 __isl_give pet_expr *PetScan::extract_unary_increment(
1182 clang::UnaryOperator *op, clang::ValueDecl *iv)
1184 Expr *sub;
1185 DeclRefExpr *ref;
1186 isl_val *v;
1188 if (!op->isIncrementDecrementOp()) {
1189 unsupported(op);
1190 return NULL;
1193 sub = op->getSubExpr();
1194 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1195 unsupported(op);
1196 return NULL;
1199 ref = cast<DeclRefExpr>(sub);
1200 if (ref->getDecl() != iv) {
1201 unsupported(op);
1202 return NULL;
1205 if (op->isIncrementOp())
1206 v = isl_val_one(ctx);
1207 else
1208 v = isl_val_negone(ctx);
1210 return pet_expr_new_int(v);
1213 /* Check if op is of the form
1215 * iv = expr
1217 * and return the increment "expr - iv" as a pet_expr.
1219 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1220 clang::ValueDecl *iv)
1222 int type_size;
1223 Expr *lhs;
1224 DeclRefExpr *ref;
1225 pet_expr *expr, *expr_iv;
1227 if (op->getOpcode() != BO_Assign) {
1228 unsupported(op);
1229 return NULL;
1232 lhs = op->getLHS();
1233 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1234 unsupported(op);
1235 return NULL;
1238 ref = cast<DeclRefExpr>(lhs);
1239 if (ref->getDecl() != iv) {
1240 unsupported(op);
1241 return NULL;
1244 expr = extract_expr(op->getRHS());
1245 expr_iv = extract_expr(lhs);
1247 type_size = get_type_size(iv->getType(), ast_context);
1248 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1251 /* Check that op is of the form iv += cst or iv -= cst
1252 * and return a pet_expr corresponding to cst or -cst accordingly.
1254 __isl_give pet_expr *PetScan::extract_compound_increment(
1255 CompoundAssignOperator *op, clang::ValueDecl *iv)
1257 Expr *lhs;
1258 DeclRefExpr *ref;
1259 bool neg = false;
1260 pet_expr *expr;
1261 BinaryOperatorKind opcode;
1263 opcode = op->getOpcode();
1264 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1265 unsupported(op);
1266 return NULL;
1268 if (opcode == BO_SubAssign)
1269 neg = true;
1271 lhs = op->getLHS();
1272 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1273 unsupported(op);
1274 return NULL;
1277 ref = cast<DeclRefExpr>(lhs);
1278 if (ref->getDecl() != iv) {
1279 unsupported(op);
1280 return NULL;
1283 expr = extract_expr(op->getRHS());
1284 if (neg) {
1285 int type_size;
1286 type_size = get_type_size(op->getType(), ast_context);
1287 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1290 return expr;
1293 /* Check that the increment of the given for loop increments
1294 * (or decrements) the induction variable "iv" and return
1295 * the increment as a pet_expr if successful.
1297 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1298 ValueDecl *iv)
1300 Stmt *inc = stmt->getInc();
1302 if (!inc) {
1303 report_missing_increment(stmt);
1304 return NULL;
1307 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1308 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1309 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1310 return extract_compound_increment(
1311 cast<CompoundAssignOperator>(inc), iv);
1312 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1313 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1315 unsupported(inc);
1316 return NULL;
1319 /* Construct a pet_tree for a while loop.
1321 * If we were only able to extract part of the body, then simply
1322 * return that part.
1324 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1326 pet_expr *pe_cond;
1327 pet_tree *tree;
1329 tree = extract(stmt->getBody());
1330 if (partial)
1331 return tree;
1332 pe_cond = extract_expr(stmt->getCond());
1333 tree = pet_tree_new_while(pe_cond, tree);
1335 return tree;
1338 /* Construct a pet_tree for a for statement.
1339 * The for loop is required to be of one of the following forms
1341 * for (i = init; condition; ++i)
1342 * for (i = init; condition; --i)
1343 * for (i = init; condition; i += constant)
1344 * for (i = init; condition; i -= constant)
1346 * We extract a pet_tree for the body and then include it in a pet_tree
1347 * of type pet_tree_for.
1349 * As a special case, we also allow a for loop of the form
1351 * for (;;)
1353 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1355 * If we were only able to extract part of the body, then simply
1356 * return that part.
1358 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1360 BinaryOperator *ass;
1361 Decl *decl;
1362 Stmt *init;
1363 Expr *lhs, *rhs;
1364 ValueDecl *iv;
1365 pet_tree *tree;
1366 struct pet_scop *scop;
1367 int independent;
1368 int declared;
1369 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1371 independent = is_current_stmt_marked_independent();
1373 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1374 tree = extract(stmt->getBody());
1375 if (partial)
1376 return tree;
1377 tree = pet_tree_new_infinite_loop(tree);
1378 return tree;
1381 init = stmt->getInit();
1382 if (!init) {
1383 unsupported(stmt);
1384 return NULL;
1386 if ((ass = initialization_assignment(init)) != NULL) {
1387 iv = extract_induction_variable(ass);
1388 if (!iv)
1389 return NULL;
1390 lhs = ass->getLHS();
1391 rhs = ass->getRHS();
1392 } else if ((decl = initialization_declaration(init)) != NULL) {
1393 VarDecl *var = extract_induction_variable(init, decl);
1394 if (!var)
1395 return NULL;
1396 iv = var;
1397 rhs = var->getInit();
1398 lhs = create_DeclRefExpr(var);
1399 } else {
1400 unsupported(stmt->getInit());
1401 return NULL;
1404 declared = !initialization_assignment(stmt->getInit());
1405 tree = extract(stmt->getBody());
1406 if (partial)
1407 return tree;
1408 pe_iv = extract_access_expr(iv);
1409 pe_iv = mark_write(pe_iv);
1410 pe_init = extract_expr(rhs);
1411 if (!stmt->getCond())
1412 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1413 else
1414 pe_cond = extract_expr(stmt->getCond());
1415 pe_inc = extract_increment(stmt, iv);
1416 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1417 pe_inc, tree);
1418 return tree;
1421 /* Try and construct a pet_tree corresponding to a compound statement.
1423 * "skip_declarations" is set if we should skip initial declarations
1424 * in the children of the compound statements.
1426 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1427 bool skip_declarations)
1429 return extract(stmt->children(), true, skip_declarations);
1432 /* Return the file offset of the expansion location of "Loc".
1434 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1436 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1439 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1441 /* Return a SourceLocation for the location after the first semicolon
1442 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1443 * call it and also skip trailing spaces and newline.
1445 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1446 const LangOptions &LO)
1448 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1451 #else
1453 /* Return a SourceLocation for the location after the first semicolon
1454 * after "loc". If Lexer::findLocationAfterToken is not available,
1455 * we look in the underlying character data for the first semicolon.
1457 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1458 const LangOptions &LO)
1460 const char *semi;
1461 const char *s = SM.getCharacterData(loc);
1463 semi = strchr(s, ';');
1464 if (!semi)
1465 return SourceLocation();
1466 return loc.getFileLocWithOffset(semi + 1 - s);
1469 #endif
1471 /* If the token at "loc" is the first token on the line, then return
1472 * a location referring to the start of the line and set *indent
1473 * to the indentation of "loc"
1474 * Otherwise, return "loc" and set *indent to "".
1476 * This function is used to extend a scop to the start of the line
1477 * if the first token of the scop is also the first token on the line.
1479 * We look for the first token on the line. If its location is equal to "loc",
1480 * then the latter is the location of the first token on the line.
1482 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1483 SourceManager &SM, const LangOptions &LO, char **indent)
1485 std::pair<FileID, unsigned> file_offset_pair;
1486 llvm::StringRef file;
1487 const char *pos;
1488 Token tok;
1489 SourceLocation token_loc, line_loc;
1490 int col;
1491 const char *s;
1493 loc = SM.getExpansionLoc(loc);
1494 col = SM.getExpansionColumnNumber(loc);
1495 line_loc = loc.getLocWithOffset(1 - col);
1496 file_offset_pair = SM.getDecomposedLoc(line_loc);
1497 file = SM.getBufferData(file_offset_pair.first, NULL);
1498 pos = file.data() + file_offset_pair.second;
1500 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1501 file.begin(), pos, file.end());
1502 lexer.LexFromRawLexer(tok);
1503 token_loc = tok.getLocation();
1505 s = SM.getCharacterData(line_loc);
1506 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1508 if (token_loc == loc)
1509 return line_loc;
1510 else
1511 return loc;
1514 /* Construct a pet_loc corresponding to the region covered by "range".
1515 * If "skip_semi" is set, then we assume "range" is followed by
1516 * a semicolon and also include this semicolon.
1518 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1519 bool skip_semi)
1521 SourceLocation loc = range.getBegin();
1522 SourceManager &SM = PP.getSourceManager();
1523 const LangOptions &LO = PP.getLangOpts();
1524 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1525 unsigned start, end;
1526 char *indent;
1528 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1529 start = getExpansionOffset(SM, loc);
1530 loc = range.getEnd();
1531 if (skip_semi)
1532 loc = location_after_semi(loc, SM, LO);
1533 else
1534 loc = PP.getLocForEndOfToken(loc);
1535 end = getExpansionOffset(SM, loc);
1537 return pet_loc_alloc(ctx, start, end, line, indent);
1540 /* Convert a top-level pet_expr to an expression pet_tree.
1542 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1543 SourceRange range, bool skip_semi)
1545 pet_loc *loc;
1546 pet_tree *tree;
1548 tree = pet_tree_new_expr(expr);
1549 loc = construct_pet_loc(range, skip_semi);
1550 tree = pet_tree_set_loc(tree, loc);
1552 return tree;
1555 /* Construct a pet_tree for an if statement.
1557 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1559 pet_expr *pe_cond;
1560 pet_tree *tree, *tree_else;
1561 struct pet_scop *scop;
1562 int int_size;
1564 pe_cond = extract_expr(stmt->getCond());
1565 tree = extract(stmt->getThen());
1566 if (stmt->getElse()) {
1567 tree_else = extract(stmt->getElse());
1568 if (options->autodetect) {
1569 if (tree && !tree_else) {
1570 partial = true;
1571 pet_expr_free(pe_cond);
1572 return tree;
1574 if (!tree && tree_else) {
1575 partial = true;
1576 pet_expr_free(pe_cond);
1577 return tree_else;
1580 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1581 } else
1582 tree = pet_tree_new_if(pe_cond, tree);
1583 return tree;
1586 /* Try and construct a pet_tree for a label statement.
1588 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1590 isl_id *label;
1591 pet_tree *tree;
1593 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1595 tree = extract(stmt->getSubStmt());
1596 tree = pet_tree_set_label(tree, label);
1597 return tree;
1600 /* Update the location of "tree" to include the source range of "stmt".
1602 * Actually, we create a new location based on the source range of "stmt" and
1603 * then extend this new location to include the region of the original location.
1604 * This ensures that the line number of the final location refers to "stmt".
1606 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1608 pet_loc *loc, *tree_loc;
1610 tree_loc = pet_tree_get_loc(tree);
1611 loc = construct_pet_loc(stmt->getSourceRange(), false);
1612 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1613 pet_loc_free(tree_loc);
1615 tree = pet_tree_set_loc(tree, loc);
1616 return tree;
1619 /* Try and construct a pet_tree corresponding to "stmt".
1621 * If "stmt" is a compound statement, then "skip_declarations"
1622 * indicates whether we should skip initial declarations in the
1623 * compound statement.
1625 * If the constructed pet_tree is not a (possibly) partial representation
1626 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1627 * In particular, if skip_declarations is set, then we may have skipped
1628 * declarations inside "stmt" and so the pet_scop may not represent
1629 * the entire "stmt".
1630 * Note that this function may be called with "stmt" referring to the entire
1631 * body of the function, including the outer braces. In such cases,
1632 * skip_declarations will be set and the braces will not be taken into
1633 * account in tree->loc.
1635 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
1637 pet_tree *tree;
1639 set_current_stmt(stmt);
1641 if (isa<Expr>(stmt))
1642 return extract(extract_expr(cast<Expr>(stmt)),
1643 stmt->getSourceRange(), true);
1645 switch (stmt->getStmtClass()) {
1646 case Stmt::WhileStmtClass:
1647 tree = extract(cast<WhileStmt>(stmt));
1648 break;
1649 case Stmt::ForStmtClass:
1650 tree = extract_for(cast<ForStmt>(stmt));
1651 break;
1652 case Stmt::IfStmtClass:
1653 tree = extract(cast<IfStmt>(stmt));
1654 break;
1655 case Stmt::CompoundStmtClass:
1656 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
1657 break;
1658 case Stmt::LabelStmtClass:
1659 tree = extract(cast<LabelStmt>(stmt));
1660 break;
1661 case Stmt::ContinueStmtClass:
1662 tree = pet_tree_new_continue(ctx);
1663 break;
1664 case Stmt::BreakStmtClass:
1665 tree = pet_tree_new_break(ctx);
1666 break;
1667 case Stmt::DeclStmtClass:
1668 tree = extract(cast<DeclStmt>(stmt));
1669 break;
1670 default:
1671 report_unsupported_statement_type(stmt);
1672 return NULL;
1675 if (partial || skip_declarations)
1676 return tree;
1678 return update_loc(tree, stmt);
1681 /* Try and construct a pet_tree corresponding to (part of)
1682 * a sequence of statements.
1684 * "block" is set if the sequence represents the children of
1685 * a compound statement.
1686 * "skip_declarations" is set if we should skip initial declarations
1687 * in the sequence of statements.
1689 * If autodetect is set, then we allow the extraction of only a subrange
1690 * of the sequence of statements. However, if there is at least one
1691 * kill and there is some subsequent statement for which we could not
1692 * construct a tree, then turn off the "block" property of the tree
1693 * such that no extra kill will be introduced at the end of the (partial)
1694 * block. If, on the other hand, the final range contains
1695 * no statements, then we discard the entire range.
1697 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
1698 bool skip_declarations)
1700 StmtIterator i;
1701 int j;
1702 bool has_kills = false;
1703 bool partial_range = false;
1704 pet_tree *tree;
1706 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
1709 tree = pet_tree_new_block(ctx, block, j);
1711 for (i = stmt_range.first; i != stmt_range.second; ++i) {
1712 Stmt *child = *i;
1713 pet_tree *tree_i;
1715 if (pet_tree_block_n_child(tree) == 0 && skip_declarations &&
1716 child->getStmtClass() == Stmt::DeclStmtClass)
1717 continue;
1719 tree_i = extract(child);
1720 if (pet_tree_block_n_child(tree) != 0 && partial) {
1721 pet_tree_free(tree_i);
1722 break;
1724 if (tree_i && child->getStmtClass() == Stmt::DeclStmtClass &&
1725 block)
1726 has_kills = true;
1727 if (options->autodetect) {
1728 if (tree_i)
1729 tree = pet_tree_block_add_child(tree, tree_i);
1730 else
1731 partial_range = true;
1732 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
1733 partial = true;
1734 } else {
1735 tree = pet_tree_block_add_child(tree, tree_i);
1738 if (partial || !tree)
1739 break;
1742 if (!tree)
1743 return NULL;
1745 if (partial) {
1746 if (has_kills)
1747 tree = pet_tree_block_set_block(tree, 0);
1748 } else if (partial_range) {
1749 if (pet_tree_block_n_child(tree) == 0) {
1750 pet_tree_free(tree);
1751 return NULL;
1753 partial = true;
1756 return tree;
1759 /* Is "T" the type of a variable length array with static size?
1761 static bool is_vla_with_static_size(QualType T)
1763 const VariableArrayType *vlatype;
1765 if (!T->isVariableArrayType())
1766 return false;
1767 vlatype = cast<VariableArrayType>(T);
1768 return vlatype->getSizeModifier() == VariableArrayType::Static;
1771 /* Return the type of "decl" as an array.
1773 * In particular, if "decl" is a parameter declaration that
1774 * is a variable length array with a static size, then
1775 * return the original type (i.e., the variable length array).
1776 * Otherwise, return the type of decl.
1778 static QualType get_array_type(ValueDecl *decl)
1780 ParmVarDecl *parm;
1781 QualType T;
1783 parm = dyn_cast<ParmVarDecl>(decl);
1784 if (!parm)
1785 return decl->getType();
1787 T = parm->getOriginalType();
1788 if (!is_vla_with_static_size(T))
1789 return decl->getType();
1790 return T;
1793 extern "C" {
1794 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1795 void *user);
1796 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1797 __isl_keep pet_context *pc, void *user);
1800 /* Construct a pet_expr that holds the sizes of the array accessed
1801 * by "access".
1802 * This function is used as a callback to pet_context_add_parameters,
1803 * which is also passed a pointer to the PetScan object.
1805 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1806 void *user)
1808 PetScan *ps = (PetScan *) user;
1809 isl_id *id;
1810 ValueDecl *decl;
1811 const Type *type;
1813 id = pet_expr_access_get_id(access);
1814 decl = (ValueDecl *) isl_id_get_user(id);
1815 isl_id_free(id);
1816 type = get_array_type(decl).getTypePtr();
1817 return ps->get_array_size(type);
1820 /* Construct and return a pet_array corresponding to the variable
1821 * accessed by "access".
1822 * This function is used as a callback to pet_scop_from_pet_tree,
1823 * which is also passed a pointer to the PetScan object.
1825 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1826 __isl_keep pet_context *pc, void *user)
1828 PetScan *ps = (PetScan *) user;
1829 isl_ctx *ctx;
1830 isl_id *id;
1831 ValueDecl *iv;
1833 ctx = pet_expr_get_ctx(access);
1834 id = pet_expr_access_get_id(access);
1835 iv = (ValueDecl *) isl_id_get_user(id);
1836 isl_id_free(id);
1837 return ps->extract_array(ctx, iv, NULL, pc);
1840 /* Extract a function summary from the body of "fd".
1842 * We extract a scop from the function body in a context with as
1843 * parameters the integer arguments of the function.
1844 * We turn off autodetection (in case it was set) to ensure that
1845 * the entire function body is considered.
1846 * We then collect the accessed array elements and attach them
1847 * to the corresponding array arguments, taking into account
1848 * that the function body may access members of array elements.
1850 * The reason for representing the integer arguments as parameters in
1851 * the context is that if we were to instead start with a context
1852 * with the function arguments as initial dimensions, then we would not
1853 * be able to refer to them from the array extents, without turning
1854 * array extents into maps.
1856 * The result is stored in the summary_cache cache so that we can reuse
1857 * it if this method gets called on the same function again later on.
1859 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
1861 isl_space *space;
1862 isl_set *domain;
1863 pet_context *pc;
1864 pet_tree *tree;
1865 pet_function_summary *summary;
1866 unsigned n;
1867 ScopLoc loc;
1868 int save_autodetect;
1869 struct pet_scop *scop;
1870 int int_size;
1871 isl_union_set *may_read, *may_write, *must_write;
1872 isl_union_map *to_inner;
1874 if (summary_cache.find(fd) != summary_cache.end())
1875 return pet_function_summary_copy(summary_cache[fd]);
1877 space = isl_space_set_alloc(ctx, 0, 0);
1879 n = fd->getNumParams();
1880 summary = pet_function_summary_alloc(ctx, n);
1881 for (int i = 0; i < n; ++i) {
1882 ParmVarDecl *parm = fd->getParamDecl(i);
1883 QualType type = parm->getType();
1884 isl_id *id;
1886 if (!type->isIntegerType())
1887 continue;
1888 id = create_decl_id(ctx, parm);
1889 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
1890 space = isl_space_set_dim_id(space, isl_dim_param, 0,
1891 isl_id_copy(id));
1892 summary = pet_function_summary_set_int(summary, i, id);
1895 save_autodetect = options->autodetect;
1896 options->autodetect = 0;
1897 PetScan body_scan(PP, ast_context, loc, options,
1898 isl_union_map_copy(value_bounds), independent);
1900 tree = body_scan.extract(fd->getBody(), false);
1902 domain = isl_set_universe(space);
1903 pc = pet_context_alloc(domain);
1904 pc = pet_context_add_parameters(pc, tree,
1905 &::get_array_size, &body_scan);
1906 int_size = size_in_bytes(ast_context, ast_context.IntTy);
1907 scop = pet_scop_from_pet_tree(tree, int_size,
1908 &::extract_array, &body_scan, pc);
1909 scop = scan_arrays(scop, pc);
1910 may_read = isl_union_map_range(pet_scop_collect_may_reads(scop));
1911 may_write = isl_union_map_range(pet_scop_collect_may_writes(scop));
1912 must_write = isl_union_map_range(pet_scop_collect_must_writes(scop));
1913 to_inner = pet_scop_compute_outer_to_inner(scop);
1914 pet_scop_free(scop);
1916 for (int i = 0; i < n; ++i) {
1917 ParmVarDecl *parm = fd->getParamDecl(i);
1918 QualType type = parm->getType();
1919 struct pet_array *array;
1920 isl_space *space;
1921 isl_union_set *data_set;
1922 isl_union_set *may_read_i, *may_write_i, *must_write_i;
1924 if (array_depth(type.getTypePtr()) == 0)
1925 continue;
1927 array = body_scan.extract_array(ctx, parm, NULL, pc);
1928 space = array ? isl_set_get_space(array->extent) : NULL;
1929 pet_array_free(array);
1930 data_set = isl_union_set_from_set(isl_set_universe(space));
1931 data_set = isl_union_set_apply(data_set,
1932 isl_union_map_copy(to_inner));
1933 may_read_i = isl_union_set_intersect(
1934 isl_union_set_copy(may_read),
1935 isl_union_set_copy(data_set));
1936 may_write_i = isl_union_set_intersect(
1937 isl_union_set_copy(may_write),
1938 isl_union_set_copy(data_set));
1939 must_write_i = isl_union_set_intersect(
1940 isl_union_set_copy(must_write), data_set);
1941 summary = pet_function_summary_set_array(summary, i,
1942 may_read_i, may_write_i, must_write_i);
1945 isl_union_set_free(may_read);
1946 isl_union_set_free(may_write);
1947 isl_union_set_free(must_write);
1948 isl_union_map_free(to_inner);
1950 options->autodetect = save_autodetect;
1951 pet_context_free(pc);
1953 summary_cache[fd] = pet_function_summary_copy(summary);
1955 return summary;
1958 /* If "fd" has a function body, then extract a function summary from
1959 * this body and attach it to the call expression "expr".
1961 * Even if a function body is available, "fd" itself may point
1962 * to a declaration without function body. We therefore first
1963 * replace it by the declaration that comes with a body (if any).
1965 * It is not clear why hasBody takes a reference to a const FunctionDecl *.
1966 * It seems that it is possible to directly use the iterators to obtain
1967 * a non-const pointer.
1968 * Since we are not going to use the pointer to modify anything anyway,
1969 * it seems safe to drop the constness. The alternative would be to
1970 * modify a lot of other functions to include const qualifiers.
1972 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
1973 FunctionDecl *fd)
1975 pet_function_summary *summary;
1976 const FunctionDecl *def;
1978 if (!expr)
1979 return NULL;
1980 if (!fd->hasBody(def))
1981 return expr;
1983 fd = const_cast<FunctionDecl *>(def);
1985 summary = get_summary(fd);
1987 expr = pet_expr_call_set_summary(expr, summary);
1989 return expr;
1992 /* Extract a pet_scop from "tree".
1994 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
1995 * then add pet_arrays for all accessed arrays.
1996 * We populate the pet_context with assignments for all parameters used
1997 * inside "tree" or any of the size expressions for the arrays accessed
1998 * by "tree" so that they can be used in affine expressions.
2000 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
2002 int int_size;
2003 isl_set *domain;
2004 pet_context *pc;
2005 pet_scop *scop;
2007 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2009 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2010 pc = pet_context_alloc(domain);
2011 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
2012 scop = pet_scop_from_pet_tree(tree, int_size,
2013 &::extract_array, this, pc);
2014 scop = scan_arrays(scop, pc);
2015 pet_context_free(pc);
2017 return scop;
2020 /* Check if the scop marked by the user is exactly this Stmt
2021 * or part of this Stmt.
2022 * If so, return a pet_scop corresponding to the marked region.
2023 * Otherwise, return NULL.
2025 struct pet_scop *PetScan::scan(Stmt *stmt)
2027 SourceManager &SM = PP.getSourceManager();
2028 unsigned start_off, end_off;
2030 start_off = getExpansionOffset(SM, stmt->getLocStart());
2031 end_off = getExpansionOffset(SM, stmt->getLocEnd());
2033 if (start_off > loc.end)
2034 return NULL;
2035 if (end_off < loc.start)
2036 return NULL;
2038 if (start_off >= loc.start && end_off <= loc.end)
2039 return extract_scop(extract(stmt));
2041 StmtIterator start;
2042 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
2043 Stmt *child = *start;
2044 if (!child)
2045 continue;
2046 start_off = getExpansionOffset(SM, child->getLocStart());
2047 end_off = getExpansionOffset(SM, child->getLocEnd());
2048 if (start_off < loc.start && end_off >= loc.end)
2049 return scan(child);
2050 if (start_off >= loc.start)
2051 break;
2054 StmtIterator end;
2055 for (end = start; end != stmt->child_end(); ++end) {
2056 Stmt *child = *end;
2057 start_off = SM.getFileOffset(child->getLocStart());
2058 if (start_off >= loc.end)
2059 break;
2062 return extract_scop(extract(StmtRange(start, end), false, false));
2065 /* Set the size of index "pos" of "array" to "size".
2066 * In particular, add a constraint of the form
2068 * i_pos < size
2070 * to array->extent and a constraint of the form
2072 * size >= 0
2074 * to array->context.
2076 * The domain of "size" is assumed to be zero-dimensional.
2078 static struct pet_array *update_size(struct pet_array *array, int pos,
2079 __isl_take isl_pw_aff *size)
2081 isl_set *valid;
2082 isl_set *univ;
2083 isl_set *bound;
2084 isl_space *dim;
2085 isl_aff *aff;
2086 isl_pw_aff *index;
2087 isl_id *id;
2089 if (!array)
2090 goto error;
2092 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2093 array->context = isl_set_intersect(array->context, valid);
2095 dim = isl_set_get_space(array->extent);
2096 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2097 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2098 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2099 index = isl_pw_aff_alloc(univ, aff);
2101 size = isl_pw_aff_add_dims(size, isl_dim_in,
2102 isl_set_dim(array->extent, isl_dim_set));
2103 id = isl_set_get_tuple_id(array->extent);
2104 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2105 bound = isl_pw_aff_lt_set(index, size);
2107 array->extent = isl_set_intersect(array->extent, bound);
2109 if (!array->context || !array->extent)
2110 return pet_array_free(array);
2112 return array;
2113 error:
2114 isl_pw_aff_free(size);
2115 return NULL;
2118 #ifdef HAVE_DECAYEDTYPE
2120 /* If "type" is a decayed type, then set *decayed to true and
2121 * return the original type.
2123 static const Type *undecay(const Type *type, bool *decayed)
2125 *decayed = isa<DecayedType>(type);
2126 if (*decayed)
2127 type = cast<DecayedType>(type)->getOriginalType().getTypePtr();
2128 return type;
2131 #else
2133 /* If "type" is a decayed type, then set *decayed to true and
2134 * return the original type.
2135 * Since this version of clang does not define a DecayedType,
2136 * we cannot obtain the original type even if it had been decayed and
2137 * we set *decayed to false.
2139 static const Type *undecay(const Type *type, bool *decayed)
2141 *decayed = false;
2142 return type;
2145 #endif
2147 /* Figure out the size of the array at position "pos" and all
2148 * subsequent positions from "type" and update the corresponding
2149 * argument of "expr" accordingly.
2151 * The initial type (when pos is zero) may be a pointer type decayed
2152 * from an array type, if this initial type is the type of a function
2153 * argument. This only happens if the original array type has
2154 * a constant size in the outer dimension as otherwise we get
2155 * a VariableArrayType. Try and obtain this original type (if available) and
2156 * take the outer array size into account if it was marked static.
2158 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2159 const Type *type, int pos)
2161 const ArrayType *atype;
2162 pet_expr *size;
2163 bool decayed = false;
2165 if (!expr)
2166 return NULL;
2168 if (pos == 0)
2169 type = undecay(type, &decayed);
2171 if (type->isPointerType()) {
2172 type = type->getPointeeType().getTypePtr();
2173 return set_upper_bounds(expr, type, pos + 1);
2175 if (!type->isArrayType())
2176 return expr;
2178 type = type->getCanonicalTypeInternal().getTypePtr();
2179 atype = cast<ArrayType>(type);
2181 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2182 type = atype->getElementType().getTypePtr();
2183 return set_upper_bounds(expr, type, pos + 1);
2186 if (type->isConstantArrayType()) {
2187 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2188 size = extract_expr(ca->getSize());
2189 expr = pet_expr_set_arg(expr, pos, size);
2190 } else if (type->isVariableArrayType()) {
2191 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2192 size = extract_expr(vla->getSizeExpr());
2193 expr = pet_expr_set_arg(expr, pos, size);
2196 type = atype->getElementType().getTypePtr();
2198 return set_upper_bounds(expr, type, pos + 1);
2201 /* Construct a pet_expr that holds the sizes of an array of the given type.
2202 * The returned expression is a call expression with as arguments
2203 * the sizes in each dimension. If we are unable to derive the size
2204 * in a given dimension, then the corresponding argument is set to infinity.
2205 * In fact, we initialize all arguments to infinity and then update
2206 * them if we are able to figure out the size.
2208 * The result is stored in the type_size cache so that we can reuse
2209 * it if this method gets called on the same type again later on.
2211 __isl_give pet_expr *PetScan::get_array_size(const Type *type)
2213 int depth;
2214 pet_expr *expr, *inf;
2216 if (type_size.find(type) != type_size.end())
2217 return pet_expr_copy(type_size[type]);
2219 depth = array_depth(type);
2220 inf = pet_expr_new_int(isl_val_infty(ctx));
2221 expr = pet_expr_new_call(ctx, "bounds", depth);
2222 for (int i = 0; i < depth; ++i)
2223 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2224 pet_expr_free(inf);
2226 expr = set_upper_bounds(expr, type, 0);
2227 type_size[type] = pet_expr_copy(expr);
2229 return expr;
2232 /* Does "expr" represent the "integer" infinity?
2234 static int is_infty(__isl_keep pet_expr *expr)
2236 isl_val *v;
2237 int res;
2239 if (pet_expr_get_type(expr) != pet_expr_int)
2240 return 0;
2241 v = pet_expr_int_get_val(expr);
2242 res = isl_val_is_infty(v);
2243 isl_val_free(v);
2245 return res;
2248 /* Figure out the dimensions of an array "array" based on its type
2249 * "type" and update "array" accordingly.
2251 * We first construct a pet_expr that holds the sizes of the array
2252 * in each dimension. The resulting expression may containing
2253 * infinity values for dimension where we are unable to derive
2254 * a size expression.
2256 * The arguments of the size expression that have a value different from
2257 * infinity are then converted to an affine expression
2258 * within the context "pc" and incorporated into the size of "array".
2259 * If we are unable to convert a size expression to an affine expression or
2260 * if the size is not a (symbolic) constant,
2261 * then we leave the corresponding size of "array" untouched.
2263 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2264 const Type *type, __isl_keep pet_context *pc)
2266 int n;
2267 pet_expr *expr;
2269 if (!array)
2270 return NULL;
2272 expr = get_array_size(type);
2274 n = pet_expr_get_n_arg(expr);
2275 for (int i = 0; i < n; ++i) {
2276 pet_expr *arg;
2277 isl_pw_aff *size;
2279 arg = pet_expr_get_arg(expr, i);
2280 if (!is_infty(arg)) {
2281 int dim;
2283 size = pet_expr_extract_affine(arg, pc);
2284 dim = isl_pw_aff_dim(size, isl_dim_in);
2285 if (!size)
2286 array = pet_array_free(array);
2287 else if (isl_pw_aff_involves_nan(size) ||
2288 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2289 isl_pw_aff_free(size);
2290 else {
2291 size = isl_pw_aff_drop_dims(size,
2292 isl_dim_in, 0, dim);
2293 array = update_size(array, i, size);
2296 pet_expr_free(arg);
2298 pet_expr_free(expr);
2300 return array;
2303 /* Does "decl" have definition that we can keep track of in a pet_type?
2305 static bool has_printable_definition(RecordDecl *decl)
2307 if (!decl->getDeclName())
2308 return false;
2309 return decl->getLexicalDeclContext() == decl->getDeclContext();
2312 /* Construct and return a pet_array corresponding to the variable "decl".
2313 * In particular, initialize array->extent to
2315 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2317 * and then call set_upper_bounds to set the upper bounds on the indices
2318 * based on the type of the variable. The upper bounds are converted
2319 * to affine expressions within the context "pc".
2321 * If the base type is that of a record with a top-level definition or
2322 * of a typedef and if "types" is not null, then the RecordDecl or
2323 * TypedefType corresponding to the type
2324 * is added to "types".
2326 * If the base type is that of a record with no top-level definition,
2327 * then we replace it by "<subfield>".
2329 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
2330 PetTypes *types, __isl_keep pet_context *pc)
2332 struct pet_array *array;
2333 QualType qt = get_array_type(decl);
2334 const Type *type = qt.getTypePtr();
2335 int depth = array_depth(type);
2336 QualType base = pet_clang_base_type(qt);
2337 string name;
2338 isl_id *id;
2339 isl_space *dim;
2341 array = isl_calloc_type(ctx, struct pet_array);
2342 if (!array)
2343 return NULL;
2345 id = create_decl_id(ctx, decl);
2346 dim = isl_space_set_alloc(ctx, 0, depth);
2347 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
2349 array->extent = isl_set_nat_universe(dim);
2351 dim = isl_space_params_alloc(ctx, 0);
2352 array->context = isl_set_universe(dim);
2354 array = set_upper_bounds(array, type, pc);
2355 if (!array)
2356 return NULL;
2358 name = base.getAsString();
2360 if (types) {
2361 if (isa<TypedefType>(base)) {
2362 types->insert(cast<TypedefType>(base)->getDecl());
2363 } else if (base->isRecordType()) {
2364 RecordDecl *decl = pet_clang_record_decl(base);
2365 if (has_printable_definition(decl))
2366 types->insert(decl);
2367 else
2368 name = "<subfield>";
2372 array->element_type = strdup(name.c_str());
2373 array->element_is_record = base->isRecordType();
2374 array->element_size = size_in_bytes(decl->getASTContext(), base);
2376 return array;
2379 /* Construct and return a pet_array corresponding to the sequence
2380 * of declarations "decls".
2381 * The upper bounds of the array are converted to affine expressions
2382 * within the context "pc".
2383 * If the sequence contains a single declaration, then it corresponds
2384 * to a simple array access. Otherwise, it corresponds to a member access,
2385 * with the declaration for the substructure following that of the containing
2386 * structure in the sequence of declarations.
2387 * We start with the outermost substructure and then combine it with
2388 * information from the inner structures.
2390 * Additionally, keep track of all required types in "types".
2392 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
2393 vector<ValueDecl *> decls, PetTypes *types, __isl_keep pet_context *pc)
2395 struct pet_array *array;
2396 vector<ValueDecl *>::iterator it;
2398 it = decls.begin();
2400 array = extract_array(ctx, *it, types, pc);
2402 for (++it; it != decls.end(); ++it) {
2403 struct pet_array *parent;
2404 const char *base_name, *field_name;
2405 char *product_name;
2407 parent = array;
2408 array = extract_array(ctx, *it, types, pc);
2409 if (!array)
2410 return pet_array_free(parent);
2412 base_name = isl_set_get_tuple_name(parent->extent);
2413 field_name = isl_set_get_tuple_name(array->extent);
2414 product_name = pet_array_member_access_name(ctx,
2415 base_name, field_name);
2417 array->extent = isl_set_product(isl_set_copy(parent->extent),
2418 array->extent);
2419 if (product_name)
2420 array->extent = isl_set_set_tuple_name(array->extent,
2421 product_name);
2422 array->context = isl_set_intersect(array->context,
2423 isl_set_copy(parent->context));
2425 pet_array_free(parent);
2426 free(product_name);
2428 if (!array->extent || !array->context || !product_name)
2429 return pet_array_free(array);
2432 return array;
2435 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2436 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2437 std::set<TypeDecl *> &types_done);
2438 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2439 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2440 std::set<TypeDecl *> &types_done);
2442 /* For each of the fields of "decl" that is itself a record type
2443 * or a typedef, add a corresponding pet_type to "scop".
2445 static struct pet_scop *add_field_types(isl_ctx *ctx, struct pet_scop *scop,
2446 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2447 std::set<TypeDecl *> &types_done)
2449 RecordDecl::field_iterator it;
2451 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
2452 QualType type = it->getType();
2454 if (isa<TypedefType>(type)) {
2455 TypedefNameDecl *typedefdecl;
2457 typedefdecl = cast<TypedefType>(type)->getDecl();
2458 scop = add_type(ctx, scop, typedefdecl,
2459 PP, types, types_done);
2460 } else if (type->isRecordType()) {
2461 RecordDecl *record;
2463 record = pet_clang_record_decl(type);
2464 scop = add_type(ctx, scop, record,
2465 PP, types, types_done);
2469 return scop;
2472 /* Add a pet_type corresponding to "decl" to "scop", provided
2473 * it is a member of types.records and it has not been added before
2474 * (i.e., it is not a member of "types_done").
2476 * Since we want the user to be able to print the types
2477 * in the order in which they appear in the scop, we need to
2478 * make sure that types of fields in a structure appear before
2479 * that structure. We therefore call ourselves recursively
2480 * through add_field_types on the types of all record subfields.
2482 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2483 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2484 std::set<TypeDecl *> &types_done)
2486 string s;
2487 llvm::raw_string_ostream S(s);
2489 if (types.records.find(decl) == types.records.end())
2490 return scop;
2491 if (types_done.find(decl) != types_done.end())
2492 return scop;
2494 add_field_types(ctx, scop, decl, PP, types, types_done);
2496 if (strlen(decl->getName().str().c_str()) == 0)
2497 return scop;
2499 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2500 S.str();
2502 scop->types[scop->n_type] = pet_type_alloc(ctx,
2503 decl->getName().str().c_str(), s.c_str());
2504 if (!scop->types[scop->n_type])
2505 return pet_scop_free(scop);
2507 types_done.insert(decl);
2509 scop->n_type++;
2511 return scop;
2514 /* Add a pet_type corresponding to "decl" to "scop", provided
2515 * it is a member of types.typedefs and it has not been added before
2516 * (i.e., it is not a member of "types_done").
2518 * If the underlying type is a structure, then we print the typedef
2519 * ourselves since clang does not print the definition of the structure
2520 * in the typedef. We also make sure in this case that the types of
2521 * the fields in the structure are added first.
2523 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2524 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2525 std::set<TypeDecl *> &types_done)
2527 string s;
2528 llvm::raw_string_ostream S(s);
2529 QualType qt = decl->getUnderlyingType();
2531 if (types.typedefs.find(decl) == types.typedefs.end())
2532 return scop;
2533 if (types_done.find(decl) != types_done.end())
2534 return scop;
2536 if (qt->isRecordType()) {
2537 RecordDecl *rec = pet_clang_record_decl(qt);
2539 add_field_types(ctx, scop, rec, PP, types, types_done);
2540 S << "typedef ";
2541 rec->print(S, PrintingPolicy(PP.getLangOpts()));
2542 S << " ";
2543 S << decl->getName();
2544 } else {
2545 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2547 S.str();
2549 scop->types[scop->n_type] = pet_type_alloc(ctx,
2550 decl->getName().str().c_str(), s.c_str());
2551 if (!scop->types[scop->n_type])
2552 return pet_scop_free(scop);
2554 types_done.insert(decl);
2556 scop->n_type++;
2558 return scop;
2561 /* Construct a list of pet_arrays, one for each array (or scalar)
2562 * accessed inside "scop", add this list to "scop" and return the result.
2563 * The upper bounds of the arrays are converted to affine expressions
2564 * within the context "pc".
2566 * The context of "scop" is updated with the intersection of
2567 * the contexts of all arrays, i.e., constraints on the parameters
2568 * that ensure that the arrays have a valid (non-negative) size.
2570 * If any of the extracted arrays refers to a member access or
2571 * has a typedef'd type as base type,
2572 * then also add the required types to "scop".
2574 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
2575 __isl_keep pet_context *pc)
2577 int i, n;
2578 array_desc_set arrays;
2579 array_desc_set::iterator it;
2580 PetTypes types;
2581 std::set<TypeDecl *> types_done;
2582 std::set<clang::RecordDecl *, less_name>::iterator records_it;
2583 std::set<clang::TypedefNameDecl *, less_name>::iterator typedefs_it;
2584 int n_array;
2585 struct pet_array **scop_arrays;
2587 if (!scop)
2588 return NULL;
2590 pet_scop_collect_arrays(scop, arrays);
2591 if (arrays.size() == 0)
2592 return scop;
2594 n_array = scop->n_array;
2596 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2597 n_array + arrays.size());
2598 if (!scop_arrays)
2599 goto error;
2600 scop->arrays = scop_arrays;
2602 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
2603 struct pet_array *array;
2604 array = extract_array(ctx, *it, &types, pc);
2605 scop->arrays[n_array + i] = array;
2606 if (!scop->arrays[n_array + i])
2607 goto error;
2608 scop->n_array++;
2609 scop->context = isl_set_intersect(scop->context,
2610 isl_set_copy(array->context));
2611 if (!scop->context)
2612 goto error;
2615 n = types.records.size() + types.typedefs.size();
2616 if (n == 0)
2617 return scop;
2619 scop->types = isl_alloc_array(ctx, struct pet_type *, n);
2620 if (!scop->types)
2621 goto error;
2623 for (records_it = types.records.begin();
2624 records_it != types.records.end(); ++records_it)
2625 scop = add_type(ctx, scop, *records_it, PP, types, types_done);
2627 for (typedefs_it = types.typedefs.begin();
2628 typedefs_it != types.typedefs.end(); ++typedefs_it)
2629 scop = add_type(ctx, scop, *typedefs_it, PP, types, types_done);
2631 return scop;
2632 error:
2633 pet_scop_free(scop);
2634 return NULL;
2637 /* Bound all parameters in scop->context to the possible values
2638 * of the corresponding C variable.
2640 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
2642 int n;
2644 if (!scop)
2645 return NULL;
2647 n = isl_set_dim(scop->context, isl_dim_param);
2648 for (int i = 0; i < n; ++i) {
2649 isl_id *id;
2650 ValueDecl *decl;
2652 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
2653 if (pet_nested_in_id(id)) {
2654 isl_id_free(id);
2655 isl_die(isl_set_get_ctx(scop->context),
2656 isl_error_internal,
2657 "unresolved nested parameter", goto error);
2659 decl = (ValueDecl *) isl_id_get_user(id);
2660 isl_id_free(id);
2662 scop->context = set_parameter_bounds(scop->context, i, decl);
2664 if (!scop->context)
2665 goto error;
2668 return scop;
2669 error:
2670 pet_scop_free(scop);
2671 return NULL;
2674 /* Construct a pet_scop from the given function.
2676 * If the scop was delimited by scop and endscop pragmas, then we override
2677 * the file offsets by those derived from the pragmas.
2679 struct pet_scop *PetScan::scan(FunctionDecl *fd)
2681 pet_scop *scop;
2682 Stmt *stmt;
2684 stmt = fd->getBody();
2686 if (options->autodetect) {
2687 set_current_stmt(stmt);
2688 scop = extract_scop(extract(stmt, true));
2689 } else {
2690 current_line = loc.start_line;
2691 scop = scan(stmt);
2692 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
2694 scop = add_parameter_bounds(scop);
2695 scop = pet_scop_gist(scop, value_bounds);
2697 return scop;
2700 /* Update this->last_line and this->current_line based on the fact
2701 * that we are about to consider "stmt".
2703 void PetScan::set_current_stmt(Stmt *stmt)
2705 SourceLocation loc = stmt->getLocStart();
2706 SourceManager &SM = PP.getSourceManager();
2708 last_line = current_line;
2709 current_line = SM.getExpansionLineNumber(loc);
2712 /* Is the current statement marked by an independent pragma?
2713 * That is, is there an independent pragma on a line between
2714 * the line of the current statement and the line of the previous statement.
2715 * The search is not implemented very efficiently. We currently
2716 * assume that there are only a few independent pragmas, if any.
2718 bool PetScan::is_current_stmt_marked_independent()
2720 for (int i = 0; i < independent.size(); ++i) {
2721 unsigned line = independent[i].line;
2723 if (last_line < line && line < current_line)
2724 return true;
2727 return false;