scop.c: extract out pet_stmt_is_affine_assume and pet_stmt_assume_get_index
[pet.git] / scan.cc
blobed2a3d8400e4db3fd678a91ce58336b4b93a38b8
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2014 Ecole Normale Superieure. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
32 * Leiden University.
33 */
35 #include <string.h>
36 #include <set>
37 #include <map>
38 #include <iostream>
39 #include <llvm/Support/raw_ostream.h>
40 #include <clang/AST/ASTContext.h>
41 #include <clang/AST/ASTDiagnostic.h>
42 #include <clang/AST/Expr.h>
43 #include <clang/AST/RecursiveASTVisitor.h>
45 #include <isl/id.h>
46 #include <isl/space.h>
47 #include <isl/aff.h>
48 #include <isl/set.h>
50 #include "aff.h"
51 #include "array.h"
52 #include "clang.h"
53 #include "context.h"
54 #include "expr.h"
55 #include "nest.h"
56 #include "options.h"
57 #include "scan.h"
58 #include "scop.h"
59 #include "scop_plus.h"
60 #include "tree.h"
61 #include "tree2scop.h"
63 #include "config.h"
65 using namespace std;
66 using namespace clang;
68 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
70 switch (kind) {
71 case UO_Minus:
72 return pet_op_minus;
73 case UO_Not:
74 return pet_op_not;
75 case UO_LNot:
76 return pet_op_lnot;
77 case UO_PostInc:
78 return pet_op_post_inc;
79 case UO_PostDec:
80 return pet_op_post_dec;
81 case UO_PreInc:
82 return pet_op_pre_inc;
83 case UO_PreDec:
84 return pet_op_pre_dec;
85 default:
86 return pet_op_last;
90 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
92 switch (kind) {
93 case BO_AddAssign:
94 return pet_op_add_assign;
95 case BO_SubAssign:
96 return pet_op_sub_assign;
97 case BO_MulAssign:
98 return pet_op_mul_assign;
99 case BO_DivAssign:
100 return pet_op_div_assign;
101 case BO_Assign:
102 return pet_op_assign;
103 case BO_Add:
104 return pet_op_add;
105 case BO_Sub:
106 return pet_op_sub;
107 case BO_Mul:
108 return pet_op_mul;
109 case BO_Div:
110 return pet_op_div;
111 case BO_Rem:
112 return pet_op_mod;
113 case BO_Shl:
114 return pet_op_shl;
115 case BO_Shr:
116 return pet_op_shr;
117 case BO_EQ:
118 return pet_op_eq;
119 case BO_NE:
120 return pet_op_ne;
121 case BO_LE:
122 return pet_op_le;
123 case BO_GE:
124 return pet_op_ge;
125 case BO_LT:
126 return pet_op_lt;
127 case BO_GT:
128 return pet_op_gt;
129 case BO_And:
130 return pet_op_and;
131 case BO_Xor:
132 return pet_op_xor;
133 case BO_Or:
134 return pet_op_or;
135 case BO_LAnd:
136 return pet_op_land;
137 case BO_LOr:
138 return pet_op_lor;
139 default:
140 return pet_op_last;
144 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
145 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
147 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
148 SourceLocation(), var, false, var->getInnerLocStart(),
149 var->getType(), VK_LValue);
151 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
152 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
154 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
155 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
156 VK_LValue);
158 #else
159 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
161 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
162 var, var->getInnerLocStart(), var->getType(), VK_LValue);
164 #endif
166 /* Check if the element type corresponding to the given array type
167 * has a const qualifier.
169 static bool const_base(QualType qt)
171 const Type *type = qt.getTypePtr();
173 if (type->isPointerType())
174 return const_base(type->getPointeeType());
175 if (type->isArrayType()) {
176 const ArrayType *atype;
177 type = type->getCanonicalTypeInternal().getTypePtr();
178 atype = cast<ArrayType>(type);
179 return const_base(atype->getElementType());
182 return qt.isConstQualified();
185 /* Create an isl_id that refers to the named declarator "decl".
187 static __isl_give isl_id *create_decl_id(isl_ctx *ctx, NamedDecl *decl)
189 return isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
192 PetScan::~PetScan()
194 std::map<const Type *, pet_expr *>::iterator it;
196 for (it = type_size.begin(); it != type_size.end(); ++it)
197 pet_expr_free(it->second);
199 isl_union_map_free(value_bounds);
202 /* Report a diagnostic, unless autodetect is set.
204 void PetScan::report(Stmt *stmt, unsigned id)
206 if (options->autodetect)
207 return;
209 SourceLocation loc = stmt->getLocStart();
210 DiagnosticsEngine &diag = PP.getDiagnostics();
211 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
214 /* Called if we found something we (currently) cannot handle.
215 * We'll provide more informative warnings later.
217 * We only actually complain if autodetect is false.
219 void PetScan::unsupported(Stmt *stmt)
221 DiagnosticsEngine &diag = PP.getDiagnostics();
222 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
223 "unsupported");
224 report(stmt, id);
227 /* Report a missing prototype, unless autodetect is set.
229 void PetScan::report_prototype_required(Stmt *stmt)
231 DiagnosticsEngine &diag = PP.getDiagnostics();
232 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
233 "prototype required");
234 report(stmt, id);
237 /* Report a missing increment, unless autodetect is set.
239 void PetScan::report_missing_increment(Stmt *stmt)
241 DiagnosticsEngine &diag = PP.getDiagnostics();
242 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
243 "missing increment");
244 report(stmt, id);
247 /* Extract an integer from "val", which is assumed to be non-negative.
249 static __isl_give isl_val *extract_unsigned(isl_ctx *ctx,
250 const llvm::APInt &val)
252 unsigned n;
253 const uint64_t *data;
255 data = val.getRawData();
256 n = val.getNumWords();
257 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
260 /* Extract an integer from "val". If "is_signed" is set, then "val"
261 * is signed. Otherwise it it unsigned.
263 static __isl_give isl_val *extract_int(isl_ctx *ctx, bool is_signed,
264 llvm::APInt val)
266 int is_negative = is_signed && val.isNegative();
267 isl_val *v;
269 if (is_negative)
270 val = -val;
272 v = extract_unsigned(ctx, val);
274 if (is_negative)
275 v = isl_val_neg(v);
276 return v;
279 /* Extract an integer from "expr".
281 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
283 const Type *type = expr->getType().getTypePtr();
284 bool is_signed = type->hasSignedIntegerRepresentation();
286 return ::extract_int(ctx, is_signed, expr->getValue());
289 /* Extract an integer from "expr".
290 * Return NULL if "expr" does not (obviously) represent an integer.
292 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
294 return extract_int(expr->getSubExpr());
297 /* Extract an integer from "expr".
298 * Return NULL if "expr" does not (obviously) represent an integer.
300 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
302 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
303 return extract_int(ctx, cast<IntegerLiteral>(expr));
304 if (expr->getStmtClass() == Stmt::ParenExprClass)
305 return extract_int(cast<ParenExpr>(expr));
307 unsupported(expr);
308 return NULL;
311 /* Extract a pet_expr from the APInt "val", which is assumed
312 * to be non-negative.
314 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
316 return pet_expr_new_int(extract_unsigned(ctx, val));
319 /* Return the number of bits needed to represent the type "qt",
320 * if it is an integer type. Otherwise return 0.
321 * If qt is signed then return the opposite of the number of bits.
323 static int get_type_size(QualType qt, ASTContext &ast_context)
325 int size;
327 if (!qt->isIntegerType())
328 return 0;
330 size = ast_context.getIntWidth(qt);
331 if (!qt->isUnsignedIntegerType())
332 size = -size;
334 return size;
337 /* Return the number of bits needed to represent the type of "decl",
338 * if it is an integer type. Otherwise return 0.
339 * If qt is signed then return the opposite of the number of bits.
341 static int get_type_size(ValueDecl *decl)
343 return get_type_size(decl->getType(), decl->getASTContext());
346 /* Bound parameter "pos" of "set" to the possible values of "decl".
348 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
349 unsigned pos, ValueDecl *decl)
351 int type_size;
352 isl_ctx *ctx;
353 isl_val *bound;
355 ctx = isl_set_get_ctx(set);
356 type_size = get_type_size(decl);
357 if (type_size == 0)
358 isl_die(ctx, isl_error_invalid, "not an integer type",
359 return isl_set_free(set));
360 if (type_size > 0) {
361 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
362 bound = isl_val_int_from_ui(ctx, type_size);
363 bound = isl_val_2exp(bound);
364 bound = isl_val_sub_ui(bound, 1);
365 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
366 } else {
367 bound = isl_val_int_from_ui(ctx, -type_size - 1);
368 bound = isl_val_2exp(bound);
369 bound = isl_val_sub_ui(bound, 1);
370 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
371 isl_val_copy(bound));
372 bound = isl_val_neg(bound);
373 bound = isl_val_sub_ui(bound, 1);
374 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
377 return set;
380 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
382 return extract_index_expr(expr->getSubExpr());
385 /* Return the depth of an array of the given type.
387 static int array_depth(const Type *type)
389 if (type->isPointerType())
390 return 1 + array_depth(type->getPointeeType().getTypePtr());
391 if (type->isArrayType()) {
392 const ArrayType *atype;
393 type = type->getCanonicalTypeInternal().getTypePtr();
394 atype = cast<ArrayType>(type);
395 return 1 + array_depth(atype->getElementType().getTypePtr());
397 return 0;
400 /* Return the depth of the array accessed by the index expression "index".
401 * If "index" is an affine expression, i.e., if it does not access
402 * any array, then return 1.
403 * If "index" represent a member access, i.e., if its range is a wrapped
404 * relation, then return the sum of the depth of the array of structures
405 * and that of the member inside the structure.
407 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
409 isl_id *id;
410 ValueDecl *decl;
412 if (!index)
413 return -1;
415 if (isl_multi_pw_aff_range_is_wrapping(index)) {
416 int domain_depth, range_depth;
417 isl_multi_pw_aff *domain, *range;
419 domain = isl_multi_pw_aff_copy(index);
420 domain = isl_multi_pw_aff_range_factor_domain(domain);
421 domain_depth = extract_depth(domain);
422 isl_multi_pw_aff_free(domain);
423 range = isl_multi_pw_aff_copy(index);
424 range = isl_multi_pw_aff_range_factor_range(range);
425 range_depth = extract_depth(range);
426 isl_multi_pw_aff_free(range);
428 return domain_depth + range_depth;
431 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
432 return 1;
434 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
435 if (!id)
436 return -1;
437 decl = (ValueDecl *) isl_id_get_user(id);
438 isl_id_free(id);
440 return array_depth(decl->getType().getTypePtr());
443 /* Return the depth of the array accessed by the access expression "expr".
445 static int extract_depth(__isl_keep pet_expr *expr)
447 isl_multi_pw_aff *index;
448 int depth;
450 index = pet_expr_access_get_index(expr);
451 depth = extract_depth(index);
452 isl_multi_pw_aff_free(index);
454 return depth;
457 /* Construct a pet_expr representing an index expression for an access
458 * to the variable referenced by "expr".
460 * If "expr" references an enum constant, then return an integer expression
461 * instead, representing the value of the enum constant.
463 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
465 return extract_index_expr(expr->getDecl());
468 /* Construct a pet_expr representing an index expression for an access
469 * to the variable "decl".
471 * If "decl" is an enum constant, then we return an integer expression
472 * instead, representing the value of the enum constant.
474 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
476 isl_id *id;
477 isl_space *space;
479 if (isa<EnumConstantDecl>(decl))
480 return extract_expr(cast<EnumConstantDecl>(decl));
482 id = create_decl_id(ctx, decl);
483 space = isl_space_alloc(ctx, 0, 0, 0);
484 space = isl_space_set_tuple_id(space, isl_dim_out, id);
486 return pet_expr_from_index(isl_multi_pw_aff_zero(space));
489 /* Construct a pet_expr representing the index expression "expr"
490 * Return NULL on error.
492 * If "expr" is a reference to an enum constant, then return
493 * an integer expression instead, representing the value of the enum constant.
495 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
497 switch (expr->getStmtClass()) {
498 case Stmt::ImplicitCastExprClass:
499 return extract_index_expr(cast<ImplicitCastExpr>(expr));
500 case Stmt::DeclRefExprClass:
501 return extract_index_expr(cast<DeclRefExpr>(expr));
502 case Stmt::ArraySubscriptExprClass:
503 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
504 case Stmt::IntegerLiteralClass:
505 return extract_expr(cast<IntegerLiteral>(expr));
506 case Stmt::MemberExprClass:
507 return extract_index_expr(cast<MemberExpr>(expr));
508 default:
509 unsupported(expr);
511 return NULL;
514 /* Extract an index expression from the given array subscript expression.
516 * We first extract an index expression from the base.
517 * This will result in an index expression with a range that corresponds
518 * to the earlier indices.
519 * We then extract the current index and let
520 * pet_expr_access_subscript combine the two.
522 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
524 Expr *base = expr->getBase();
525 Expr *idx = expr->getIdx();
526 pet_expr *index;
527 pet_expr *base_expr;
529 base_expr = extract_index_expr(base);
530 index = extract_expr(idx);
532 base_expr = pet_expr_access_subscript(base_expr, index);
534 return base_expr;
537 /* Extract an index expression from a member expression.
539 * If the base access (to the structure containing the member)
540 * is of the form
542 * A[..]
544 * and the member is called "f", then the member access is of
545 * the form
547 * A_f[A[..] -> f[]]
549 * If the member access is to an anonymous struct, then simply return
551 * A[..]
553 * If the member access in the source code is of the form
555 * A->f
557 * then it is treated as
559 * A[0].f
561 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
563 Expr *base = expr->getBase();
564 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
565 pet_expr *base_index;
566 isl_id *id;
568 base_index = extract_index_expr(base);
570 if (expr->isArrow()) {
571 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
572 base_index = pet_expr_access_subscript(base_index, index);
575 if (field->isAnonymousStructOrUnion())
576 return base_index;
578 id = create_decl_id(ctx, field);
580 return pet_expr_access_member(base_index, id);
583 /* Mark the given access pet_expr as a write.
585 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
587 access = pet_expr_access_set_write(access, 1);
588 access = pet_expr_access_set_read(access, 0);
590 return access;
593 /* Construct a pet_expr representing a unary operator expression.
595 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
597 pet_expr *arg;
598 enum pet_op_type op;
600 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
601 if (op == pet_op_last) {
602 unsupported(expr);
603 return NULL;
606 arg = extract_expr(expr->getSubExpr());
608 if (expr->isIncrementDecrementOp() &&
609 pet_expr_get_type(arg) == pet_expr_access) {
610 arg = mark_write(arg);
611 arg = pet_expr_access_set_read(arg, 1);
614 return pet_expr_new_unary(op, arg);
617 /* Construct a pet_expr representing a binary operator expression.
619 * If the top level operator is an assignment and the LHS is an access,
620 * then we mark that access as a write. If the operator is a compound
621 * assignment, the access is marked as both a read and a write.
623 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
625 int type_size;
626 pet_expr *lhs, *rhs;
627 enum pet_op_type op;
629 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
630 if (op == pet_op_last) {
631 unsupported(expr);
632 return NULL;
635 lhs = extract_expr(expr->getLHS());
636 rhs = extract_expr(expr->getRHS());
638 if (expr->isAssignmentOp() &&
639 pet_expr_get_type(lhs) == pet_expr_access) {
640 lhs = mark_write(lhs);
641 if (expr->isCompoundAssignmentOp())
642 lhs = pet_expr_access_set_read(lhs, 1);
645 type_size = get_type_size(expr->getType(), ast_context);
646 return pet_expr_new_binary(type_size, op, lhs, rhs);
649 /* Construct a pet_tree for a (single) variable declaration.
651 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
653 Decl *decl;
654 VarDecl *vd;
655 pet_expr *lhs, *rhs;
656 pet_tree *tree;
658 if (!stmt->isSingleDecl()) {
659 unsupported(stmt);
660 return NULL;
663 decl = stmt->getSingleDecl();
664 vd = cast<VarDecl>(decl);
666 lhs = extract_access_expr(vd);
667 lhs = mark_write(lhs);
668 if (!vd->getInit())
669 tree = pet_tree_new_decl(lhs);
670 else {
671 rhs = extract_expr(vd->getInit());
672 tree = pet_tree_new_decl_init(lhs, rhs);
675 return tree;
678 /* Construct a pet_expr representing a conditional operation.
680 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
682 pet_expr *cond, *lhs, *rhs;
683 isl_pw_aff *pa;
685 cond = extract_expr(expr->getCond());
686 lhs = extract_expr(expr->getTrueExpr());
687 rhs = extract_expr(expr->getFalseExpr());
689 return pet_expr_new_ternary(cond, lhs, rhs);
692 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
694 return extract_expr(expr->getSubExpr());
697 /* Construct a pet_expr representing a floating point value.
699 * If the floating point literal does not appear in a macro,
700 * then we use the original representation in the source code
701 * as the string representation. Otherwise, we use the pretty
702 * printer to produce a string representation.
704 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
706 double d;
707 string s;
708 const LangOptions &LO = PP.getLangOpts();
709 SourceLocation loc = expr->getLocation();
711 if (!loc.isMacroID()) {
712 SourceManager &SM = PP.getSourceManager();
713 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
714 s = string(SM.getCharacterData(loc), len);
715 } else {
716 llvm::raw_string_ostream S(s);
717 expr->printPretty(S, 0, PrintingPolicy(LO));
718 S.str();
720 d = expr->getValueAsApproximateDouble();
721 return pet_expr_new_double(ctx, d, s.c_str());
724 /* Convert the index expression "index" into an access pet_expr of type "qt".
726 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
727 __isl_take pet_expr *index)
729 int depth;
730 int type_size;
732 depth = extract_depth(index);
733 type_size = get_type_size(qt, ast_context);
735 index = pet_expr_set_type_size(index, type_size);
736 index = pet_expr_access_set_depth(index, depth);
738 return index;
741 /* Extract an index expression from "expr" and then convert it into
742 * an access pet_expr.
744 * If "expr" is a reference to an enum constant, then return
745 * an integer expression instead, representing the value of the enum constant.
747 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
749 pet_expr *index;
751 index = extract_index_expr(expr);
753 if (pet_expr_get_type(index) == pet_expr_int)
754 return index;
756 return extract_access_expr(expr->getType(), index);
759 /* Extract an index expression from "decl" and then convert it into
760 * an access pet_expr.
762 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
764 return extract_access_expr(decl->getType(), extract_index_expr(decl));
767 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
769 return extract_expr(expr->getSubExpr());
772 /* Extract an assume statement from the argument "expr"
773 * of a __pencil_assume statement.
775 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
777 return pet_expr_new_unary(pet_op_assume, extract_expr(expr));
780 /* Construct a pet_expr corresponding to the function call argument "expr".
781 * The argument appears in position "pos" of a call to function "fd".
783 * If we are passing along a pointer to an array element
784 * or an entire row or even higher dimensional slice of an array,
785 * then the function being called may write into the array.
787 * We assume here that if the function is declared to take a pointer
788 * to a const type, then the function will perform a read
789 * and that otherwise, it will perform a write.
791 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
792 Expr *expr)
794 pet_expr *res;
795 int is_addr = 0, is_partial = 0;
796 Stmt::StmtClass sc;
798 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
799 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
800 expr = ice->getSubExpr();
802 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
803 UnaryOperator *op = cast<UnaryOperator>(expr);
804 if (op->getOpcode() == UO_AddrOf) {
805 is_addr = 1;
806 expr = op->getSubExpr();
809 res = extract_expr(expr);
810 if (!res)
811 return NULL;
812 sc = expr->getStmtClass();
813 if ((sc == Stmt::ArraySubscriptExprClass ||
814 sc == Stmt::MemberExprClass) &&
815 array_depth(expr->getType().getTypePtr()) > 0)
816 is_partial = 1;
817 if ((is_addr || is_partial) &&
818 pet_expr_get_type(res) == pet_expr_access) {
819 ParmVarDecl *parm;
820 if (!fd->hasPrototype()) {
821 report_prototype_required(expr);
822 return pet_expr_free(res);
824 parm = fd->getParamDecl(pos);
825 if (!const_base(parm->getType()))
826 res = mark_write(res);
829 if (is_addr)
830 res = pet_expr_new_unary(pet_op_address_of, res);
831 return res;
834 /* Construct a pet_expr representing a function call.
836 * In the special case of a "call" to __pencil_assume,
837 * construct an assume expression instead.
839 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
841 pet_expr *res = NULL;
842 FunctionDecl *fd;
843 string name;
844 unsigned n_arg;
846 fd = expr->getDirectCallee();
847 if (!fd) {
848 unsupported(expr);
849 return NULL;
852 name = fd->getDeclName().getAsString();
853 n_arg = expr->getNumArgs();
855 if (n_arg == 1 && name == "__pencil_assume")
856 return extract_assume(expr->getArg(0));
858 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
859 if (!res)
860 return NULL;
862 for (int i = 0; i < n_arg; ++i) {
863 Expr *arg = expr->getArg(i);
864 res = pet_expr_set_arg(res, i,
865 PetScan::extract_argument(fd, i, arg));
868 return res;
871 /* Construct a pet_expr representing a (C style) cast.
873 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
875 pet_expr *arg;
876 QualType type;
878 arg = extract_expr(expr->getSubExpr());
879 if (!arg)
880 return NULL;
882 type = expr->getTypeAsWritten();
883 return pet_expr_new_cast(type.getAsString().c_str(), arg);
886 /* Construct a pet_expr representing an integer.
888 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
890 return pet_expr_new_int(extract_int(expr));
893 /* Construct a pet_expr representing the integer enum constant "ecd".
895 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
897 isl_val *v;
898 const llvm::APSInt &init = ecd->getInitVal();
899 v = ::extract_int(ctx, init.isSigned(), init);
900 return pet_expr_new_int(v);
903 /* Try and construct a pet_expr representing "expr".
905 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
907 switch (expr->getStmtClass()) {
908 case Stmt::UnaryOperatorClass:
909 return extract_expr(cast<UnaryOperator>(expr));
910 case Stmt::CompoundAssignOperatorClass:
911 case Stmt::BinaryOperatorClass:
912 return extract_expr(cast<BinaryOperator>(expr));
913 case Stmt::ImplicitCastExprClass:
914 return extract_expr(cast<ImplicitCastExpr>(expr));
915 case Stmt::ArraySubscriptExprClass:
916 case Stmt::DeclRefExprClass:
917 case Stmt::MemberExprClass:
918 return extract_access_expr(expr);
919 case Stmt::IntegerLiteralClass:
920 return extract_expr(cast<IntegerLiteral>(expr));
921 case Stmt::FloatingLiteralClass:
922 return extract_expr(cast<FloatingLiteral>(expr));
923 case Stmt::ParenExprClass:
924 return extract_expr(cast<ParenExpr>(expr));
925 case Stmt::ConditionalOperatorClass:
926 return extract_expr(cast<ConditionalOperator>(expr));
927 case Stmt::CallExprClass:
928 return extract_expr(cast<CallExpr>(expr));
929 case Stmt::CStyleCastExprClass:
930 return extract_expr(cast<CStyleCastExpr>(expr));
931 default:
932 unsupported(expr);
934 return NULL;
937 /* Check if the given initialization statement is an assignment.
938 * If so, return that assignment. Otherwise return NULL.
940 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
942 BinaryOperator *ass;
944 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
945 return NULL;
947 ass = cast<BinaryOperator>(init);
948 if (ass->getOpcode() != BO_Assign)
949 return NULL;
951 return ass;
954 /* Check if the given initialization statement is a declaration
955 * of a single variable.
956 * If so, return that declaration. Otherwise return NULL.
958 Decl *PetScan::initialization_declaration(Stmt *init)
960 DeclStmt *decl;
962 if (init->getStmtClass() != Stmt::DeclStmtClass)
963 return NULL;
965 decl = cast<DeclStmt>(init);
967 if (!decl->isSingleDecl())
968 return NULL;
970 return decl->getSingleDecl();
973 /* Given the assignment operator in the initialization of a for loop,
974 * extract the induction variable, i.e., the (integer)variable being
975 * assigned.
977 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
979 Expr *lhs;
980 DeclRefExpr *ref;
981 ValueDecl *decl;
982 const Type *type;
984 lhs = init->getLHS();
985 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
986 unsupported(init);
987 return NULL;
990 ref = cast<DeclRefExpr>(lhs);
991 decl = ref->getDecl();
992 type = decl->getType().getTypePtr();
994 if (!type->isIntegerType()) {
995 unsupported(lhs);
996 return NULL;
999 return decl;
1002 /* Given the initialization statement of a for loop and the single
1003 * declaration in this initialization statement,
1004 * extract the induction variable, i.e., the (integer) variable being
1005 * declared.
1007 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1009 VarDecl *vd;
1011 vd = cast<VarDecl>(decl);
1013 const QualType type = vd->getType();
1014 if (!type->isIntegerType()) {
1015 unsupported(init);
1016 return NULL;
1019 if (!vd->getInit()) {
1020 unsupported(init);
1021 return NULL;
1024 return vd;
1027 /* Check that op is of the form iv++ or iv--.
1028 * Return a pet_expr representing "1" or "-1" accordingly.
1030 __isl_give pet_expr *PetScan::extract_unary_increment(
1031 clang::UnaryOperator *op, clang::ValueDecl *iv)
1033 Expr *sub;
1034 DeclRefExpr *ref;
1035 isl_val *v;
1037 if (!op->isIncrementDecrementOp()) {
1038 unsupported(op);
1039 return NULL;
1042 sub = op->getSubExpr();
1043 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1044 unsupported(op);
1045 return NULL;
1048 ref = cast<DeclRefExpr>(sub);
1049 if (ref->getDecl() != iv) {
1050 unsupported(op);
1051 return NULL;
1054 if (op->isIncrementOp())
1055 v = isl_val_one(ctx);
1056 else
1057 v = isl_val_negone(ctx);
1059 return pet_expr_new_int(v);
1062 /* Check if op is of the form
1064 * iv = expr
1066 * and return the increment "expr - iv" as a pet_expr.
1068 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1069 clang::ValueDecl *iv)
1071 int type_size;
1072 Expr *lhs;
1073 DeclRefExpr *ref;
1074 pet_expr *expr, *expr_iv;
1076 if (op->getOpcode() != BO_Assign) {
1077 unsupported(op);
1078 return NULL;
1081 lhs = op->getLHS();
1082 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1083 unsupported(op);
1084 return NULL;
1087 ref = cast<DeclRefExpr>(lhs);
1088 if (ref->getDecl() != iv) {
1089 unsupported(op);
1090 return NULL;
1093 expr = extract_expr(op->getRHS());
1094 expr_iv = extract_expr(lhs);
1096 type_size = get_type_size(iv->getType(), ast_context);
1097 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1100 /* Check that op is of the form iv += cst or iv -= cst
1101 * and return a pet_expr corresponding to cst or -cst accordingly.
1103 __isl_give pet_expr *PetScan::extract_compound_increment(
1104 CompoundAssignOperator *op, clang::ValueDecl *iv)
1106 Expr *lhs;
1107 DeclRefExpr *ref;
1108 bool neg = false;
1109 pet_expr *expr;
1110 BinaryOperatorKind opcode;
1112 opcode = op->getOpcode();
1113 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1114 unsupported(op);
1115 return NULL;
1117 if (opcode == BO_SubAssign)
1118 neg = true;
1120 lhs = op->getLHS();
1121 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1122 unsupported(op);
1123 return NULL;
1126 ref = cast<DeclRefExpr>(lhs);
1127 if (ref->getDecl() != iv) {
1128 unsupported(op);
1129 return NULL;
1132 expr = extract_expr(op->getRHS());
1133 if (neg)
1134 expr = pet_expr_new_unary(pet_op_minus, expr);
1136 return expr;
1139 /* Check that the increment of the given for loop increments
1140 * (or decrements) the induction variable "iv" and return
1141 * the increment as a pet_expr if successful.
1143 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1144 ValueDecl *iv)
1146 Stmt *inc = stmt->getInc();
1148 if (!inc) {
1149 report_missing_increment(stmt);
1150 return NULL;
1153 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1154 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1155 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1156 return extract_compound_increment(
1157 cast<CompoundAssignOperator>(inc), iv);
1158 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1159 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1161 unsupported(inc);
1162 return NULL;
1165 /* Construct a pet_tree for a while loop.
1167 * If we were only able to extract part of the body, then simply
1168 * return that part.
1170 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1172 pet_expr *pe_cond;
1173 pet_tree *tree;
1175 tree = extract(stmt->getBody());
1176 if (partial)
1177 return tree;
1178 pe_cond = extract_expr(stmt->getCond());
1179 tree = pet_tree_new_while(pe_cond, tree);
1181 return tree;
1184 /* Construct a pet_tree for a for statement.
1185 * The for loop is required to be of one of the following forms
1187 * for (i = init; condition; ++i)
1188 * for (i = init; condition; --i)
1189 * for (i = init; condition; i += constant)
1190 * for (i = init; condition; i -= constant)
1192 * We extract a pet_tree for the body and then include it in a pet_tree
1193 * of type pet_tree_for.
1195 * As a special case, we also allow a for loop of the form
1197 * for (;;)
1199 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1201 * If we were only able to extract part of the body, then simply
1202 * return that part.
1204 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1206 BinaryOperator *ass;
1207 Decl *decl;
1208 Stmt *init;
1209 Expr *lhs, *rhs;
1210 ValueDecl *iv;
1211 pet_tree *tree;
1212 struct pet_scop *scop;
1213 int declared;
1214 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1216 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1217 tree = extract(stmt->getBody());
1218 if (partial)
1219 return tree;
1220 tree = pet_tree_new_infinite_loop(tree);
1221 return tree;
1224 init = stmt->getInit();
1225 if (!init) {
1226 unsupported(stmt);
1227 return NULL;
1229 if ((ass = initialization_assignment(init)) != NULL) {
1230 iv = extract_induction_variable(ass);
1231 if (!iv)
1232 return NULL;
1233 lhs = ass->getLHS();
1234 rhs = ass->getRHS();
1235 } else if ((decl = initialization_declaration(init)) != NULL) {
1236 VarDecl *var = extract_induction_variable(init, decl);
1237 if (!var)
1238 return NULL;
1239 iv = var;
1240 rhs = var->getInit();
1241 lhs = create_DeclRefExpr(var);
1242 } else {
1243 unsupported(stmt->getInit());
1244 return NULL;
1247 declared = !initialization_assignment(stmt->getInit());
1248 tree = extract(stmt->getBody());
1249 if (partial)
1250 return tree;
1251 pe_iv = extract_access_expr(iv);
1252 pe_iv = mark_write(pe_iv);
1253 pe_init = extract_expr(rhs);
1254 if (!stmt->getCond())
1255 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1256 else
1257 pe_cond = extract_expr(stmt->getCond());
1258 pe_inc = extract_increment(stmt, iv);
1259 tree = pet_tree_new_for(declared, pe_iv, pe_init, pe_cond,
1260 pe_inc, tree);
1261 return tree;
1264 /* Try and construct a pet_tree corresponding to a compound statement.
1266 * "skip_declarations" is set if we should skip initial declarations
1267 * in the children of the compound statements. This then implies
1268 * that this sequence of children should not be treated as a block
1269 * since the initial statements may be skipped.
1271 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1272 bool skip_declarations)
1274 return extract(stmt->children(), !skip_declarations, skip_declarations);
1277 /* Return the file offset of the expansion location of "Loc".
1279 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1281 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1284 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1286 /* Return a SourceLocation for the location after the first semicolon
1287 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1288 * call it and also skip trailing spaces and newline.
1290 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1291 const LangOptions &LO)
1293 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1296 #else
1298 /* Return a SourceLocation for the location after the first semicolon
1299 * after "loc". If Lexer::findLocationAfterToken is not available,
1300 * we look in the underlying character data for the first semicolon.
1302 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1303 const LangOptions &LO)
1305 const char *semi;
1306 const char *s = SM.getCharacterData(loc);
1308 semi = strchr(s, ';');
1309 if (!semi)
1310 return SourceLocation();
1311 return loc.getFileLocWithOffset(semi + 1 - s);
1314 #endif
1316 /* If the token at "loc" is the first token on the line, then return
1317 * a location referring to the start of the line and set *indent
1318 * to the indentation of "loc"
1319 * Otherwise, return "loc" and set *indent to "".
1321 * This function is used to extend a scop to the start of the line
1322 * if the first token of the scop is also the first token on the line.
1324 * We look for the first token on the line. If its location is equal to "loc",
1325 * then the latter is the location of the first token on the line.
1327 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1328 SourceManager &SM, const LangOptions &LO, char **indent)
1330 std::pair<FileID, unsigned> file_offset_pair;
1331 llvm::StringRef file;
1332 const char *pos;
1333 Token tok;
1334 SourceLocation token_loc, line_loc;
1335 int col;
1336 const char *s;
1338 loc = SM.getExpansionLoc(loc);
1339 col = SM.getExpansionColumnNumber(loc);
1340 line_loc = loc.getLocWithOffset(1 - col);
1341 file_offset_pair = SM.getDecomposedLoc(line_loc);
1342 file = SM.getBufferData(file_offset_pair.first, NULL);
1343 pos = file.data() + file_offset_pair.second;
1345 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1346 file.begin(), pos, file.end());
1347 lexer.LexFromRawLexer(tok);
1348 token_loc = tok.getLocation();
1350 s = SM.getCharacterData(line_loc);
1351 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1353 if (token_loc == loc)
1354 return line_loc;
1355 else
1356 return loc;
1359 /* Construct a pet_loc corresponding to the region covered by "range".
1360 * If "skip_semi" is set, then we assume "range" is followed by
1361 * a semicolon and also include this semicolon.
1363 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1364 bool skip_semi)
1366 SourceLocation loc = range.getBegin();
1367 SourceManager &SM = PP.getSourceManager();
1368 const LangOptions &LO = PP.getLangOpts();
1369 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1370 unsigned start, end;
1371 char *indent;
1373 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1374 start = getExpansionOffset(SM, loc);
1375 loc = range.getEnd();
1376 if (skip_semi)
1377 loc = location_after_semi(loc, SM, LO);
1378 else
1379 loc = PP.getLocForEndOfToken(loc);
1380 end = getExpansionOffset(SM, loc);
1382 return pet_loc_alloc(ctx, start, end, line, indent);
1385 /* Convert a top-level pet_expr to an expression pet_tree.
1387 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1388 SourceRange range, bool skip_semi)
1390 pet_loc *loc;
1391 pet_tree *tree;
1393 tree = pet_tree_new_expr(expr);
1394 loc = construct_pet_loc(range, skip_semi);
1395 tree = pet_tree_set_loc(tree, loc);
1397 return tree;
1400 /* Construct a pet_tree for an if statement.
1402 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1404 pet_expr *pe_cond;
1405 pet_tree *tree, *tree_else;
1406 struct pet_scop *scop;
1407 int int_size;
1409 pe_cond = extract_expr(stmt->getCond());
1410 tree = extract(stmt->getThen());
1411 if (stmt->getElse()) {
1412 tree_else = extract(stmt->getElse());
1413 if (options->autodetect) {
1414 if (tree && !tree_else) {
1415 partial = true;
1416 pet_expr_free(pe_cond);
1417 return tree;
1419 if (!tree && tree_else) {
1420 partial = true;
1421 pet_expr_free(pe_cond);
1422 return tree_else;
1425 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1426 } else
1427 tree = pet_tree_new_if(pe_cond, tree);
1428 return tree;
1431 /* Try and construct a pet_tree for a label statement.
1432 * We currently only allow labels on expression statements.
1434 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1436 isl_id *label;
1437 pet_tree *tree;
1438 Stmt *sub;
1440 sub = stmt->getSubStmt();
1441 if (!isa<Expr>(sub)) {
1442 unsupported(stmt);
1443 return NULL;
1446 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1448 tree = extract(extract_expr(cast<Expr>(sub)), stmt->getSourceRange(),
1449 true);
1450 tree = pet_tree_set_label(tree, label);
1451 return tree;
1454 /* Update the location of "tree" to include the source range of "stmt".
1456 * Actually, we create a new location based on the source range of "stmt" and
1457 * then extend this new location to include the region of the original location.
1458 * This ensures that the line number of the final location refers to "stmt".
1460 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1462 pet_loc *loc, *tree_loc;
1464 tree_loc = pet_tree_get_loc(tree);
1465 loc = construct_pet_loc(stmt->getSourceRange(), false);
1466 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1467 pet_loc_free(tree_loc);
1469 tree = pet_tree_set_loc(tree, loc);
1470 return tree;
1473 /* Try and construct a pet_tree corresponding to "stmt".
1475 * If "stmt" is a compound statement, then "skip_declarations"
1476 * indicates whether we should skip initial declarations in the
1477 * compound statement.
1479 * If the constructed pet_tree is not a (possibly) partial representation
1480 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1481 * In particular, if skip_declarations is set, then we may have skipped
1482 * declarations inside "stmt" and so the pet_scop may not represent
1483 * the entire "stmt".
1484 * Note that this function may be called with "stmt" referring to the entire
1485 * body of the function, including the outer braces. In such cases,
1486 * skip_declarations will be set and the braces will not be taken into
1487 * account in tree->loc.
1489 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
1491 pet_tree *tree;
1493 if (isa<Expr>(stmt))
1494 return extract(extract_expr(cast<Expr>(stmt)),
1495 stmt->getSourceRange(), true);
1497 switch (stmt->getStmtClass()) {
1498 case Stmt::WhileStmtClass:
1499 tree = extract(cast<WhileStmt>(stmt));
1500 break;
1501 case Stmt::ForStmtClass:
1502 tree = extract_for(cast<ForStmt>(stmt));
1503 break;
1504 case Stmt::IfStmtClass:
1505 tree = extract(cast<IfStmt>(stmt));
1506 break;
1507 case Stmt::CompoundStmtClass:
1508 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
1509 break;
1510 case Stmt::LabelStmtClass:
1511 tree = extract(cast<LabelStmt>(stmt));
1512 break;
1513 case Stmt::ContinueStmtClass:
1514 tree = pet_tree_new_continue(ctx);
1515 break;
1516 case Stmt::BreakStmtClass:
1517 tree = pet_tree_new_break(ctx);
1518 break;
1519 case Stmt::DeclStmtClass:
1520 tree = extract(cast<DeclStmt>(stmt));
1521 break;
1522 default:
1523 unsupported(stmt);
1524 return NULL;
1527 if (partial || skip_declarations)
1528 return tree;
1530 return update_loc(tree, stmt);
1533 /* Try and construct a pet_tree corresponding to (part of)
1534 * a sequence of statements.
1536 * "block" is set if the sequence respresents the children of
1537 * a compound statement.
1538 * "skip_declarations" is set if we should skip initial declarations
1539 * in the sequence of statements.
1541 * If autodetect is set, then we allow the extraction of only a subrange
1542 * of the sequence of statements. However, if there is at least one statement
1543 * for which we could not construct a scop and the final range contains
1544 * either no statements or at least one kill, then we discard the entire
1545 * range.
1547 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
1548 bool skip_declarations)
1550 StmtIterator i;
1551 int j;
1552 bool has_kills = false;
1553 bool partial_range = false;
1554 pet_tree *tree;
1555 set<struct pet_stmt *> kills;
1556 set<struct pet_stmt *>::iterator it;
1558 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
1561 tree = pet_tree_new_block(ctx, block, j);
1563 for (i = stmt_range.first; i != stmt_range.second; ++i) {
1564 Stmt *child = *i;
1565 pet_tree *tree_i;
1567 if (pet_tree_block_n_child(tree) == 0 && skip_declarations &&
1568 child->getStmtClass() == Stmt::DeclStmtClass)
1569 continue;
1571 tree_i = extract(child);
1572 if (pet_tree_block_n_child(tree) != 0 && partial) {
1573 pet_tree_free(tree_i);
1574 break;
1576 if (tree_i && child->getStmtClass() == Stmt::DeclStmtClass &&
1577 block)
1578 has_kills = true;
1579 if (options->autodetect) {
1580 if (tree_i)
1581 tree = pet_tree_block_add_child(tree, tree_i);
1582 else
1583 partial_range = true;
1584 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
1585 partial = true;
1586 } else {
1587 tree = pet_tree_block_add_child(tree, tree_i);
1590 if (partial || !tree)
1591 break;
1594 if (tree && partial_range) {
1595 if (pet_tree_block_n_child(tree) == 0 || has_kills) {
1596 pet_tree_free(tree);
1597 return NULL;
1599 partial = true;
1602 return tree;
1605 /* Is "T" the type of a variable length array with static size?
1607 static bool is_vla_with_static_size(QualType T)
1609 const VariableArrayType *vlatype;
1611 if (!T->isVariableArrayType())
1612 return false;
1613 vlatype = cast<VariableArrayType>(T);
1614 return vlatype->getSizeModifier() == VariableArrayType::Static;
1617 /* Return the type of "decl" as an array.
1619 * In particular, if "decl" is a parameter declaration that
1620 * is a variable length array with a static size, then
1621 * return the original type (i.e., the variable length array).
1622 * Otherwise, return the type of decl.
1624 static QualType get_array_type(ValueDecl *decl)
1626 ParmVarDecl *parm;
1627 QualType T;
1629 parm = dyn_cast<ParmVarDecl>(decl);
1630 if (!parm)
1631 return decl->getType();
1633 T = parm->getOriginalType();
1634 if (!is_vla_with_static_size(T))
1635 return decl->getType();
1636 return T;
1639 extern "C" {
1640 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1641 void *user);
1642 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1643 __isl_keep pet_context *pc, void *user);
1646 /* Construct a pet_expr that holds the sizes of the array accessed
1647 * by "access".
1648 * This function is used as a callback to pet_context_add_parameters,
1649 * which is also passed a pointer to the PetScan object.
1651 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1652 void *user)
1654 PetScan *ps = (PetScan *) user;
1655 isl_id *id;
1656 ValueDecl *decl;
1657 const Type *type;
1659 id = pet_expr_access_get_id(access);
1660 decl = (ValueDecl *) isl_id_get_user(id);
1661 isl_id_free(id);
1662 type = get_array_type(decl).getTypePtr();
1663 return ps->get_array_size(type);
1666 /* Construct and return a pet_array corresponding to the variable
1667 * accessed by "access".
1668 * This function is used as a callback to pet_scop_from_pet_tree,
1669 * which is also passed a pointer to the PetScan object.
1671 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1672 __isl_keep pet_context *pc, void *user)
1674 PetScan *ps = (PetScan *) user;
1675 isl_ctx *ctx;
1676 isl_id *id;
1677 ValueDecl *iv;
1679 ctx = pet_expr_get_ctx(access);
1680 id = pet_expr_access_get_id(access);
1681 iv = (ValueDecl *) isl_id_get_user(id);
1682 isl_id_free(id);
1683 return ps->extract_array(ctx, iv, NULL, pc);
1686 /* Extract a pet_scop from "tree".
1688 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
1689 * then add pet_arrays for all accessed arrays.
1690 * We populate the pet_context with assignments for all parameters used
1691 * inside "tree" or any of the size expressions for the arrays accessed
1692 * by "tree" so that they can be used in affine expressions.
1694 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
1696 int int_size;
1697 isl_set *domain;
1698 pet_context *pc;
1699 pet_scop *scop;
1701 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
1703 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
1704 pc = pet_context_alloc(domain);
1705 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
1706 scop = pet_scop_from_pet_tree(tree, int_size,
1707 &::extract_array, this, pc);
1708 scop = scan_arrays(scop, pc);
1709 pet_context_free(pc);
1711 return scop;
1714 /* Check if the scop marked by the user is exactly this Stmt
1715 * or part of this Stmt.
1716 * If so, return a pet_scop corresponding to the marked region.
1717 * Otherwise, return NULL.
1719 struct pet_scop *PetScan::scan(Stmt *stmt)
1721 SourceManager &SM = PP.getSourceManager();
1722 unsigned start_off, end_off;
1724 start_off = getExpansionOffset(SM, stmt->getLocStart());
1725 end_off = getExpansionOffset(SM, stmt->getLocEnd());
1727 if (start_off > loc.end)
1728 return NULL;
1729 if (end_off < loc.start)
1730 return NULL;
1732 if (start_off >= loc.start && end_off <= loc.end)
1733 return extract_scop(extract(stmt));
1735 StmtIterator start;
1736 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
1737 Stmt *child = *start;
1738 if (!child)
1739 continue;
1740 start_off = getExpansionOffset(SM, child->getLocStart());
1741 end_off = getExpansionOffset(SM, child->getLocEnd());
1742 if (start_off < loc.start && end_off >= loc.end)
1743 return scan(child);
1744 if (start_off >= loc.start)
1745 break;
1748 StmtIterator end;
1749 for (end = start; end != stmt->child_end(); ++end) {
1750 Stmt *child = *end;
1751 start_off = SM.getFileOffset(child->getLocStart());
1752 if (start_off >= loc.end)
1753 break;
1756 return extract_scop(extract(StmtRange(start, end), false, false));
1759 /* Set the size of index "pos" of "array" to "size".
1760 * In particular, add a constraint of the form
1762 * i_pos < size
1764 * to array->extent and a constraint of the form
1766 * size >= 0
1768 * to array->context.
1770 static struct pet_array *update_size(struct pet_array *array, int pos,
1771 __isl_take isl_pw_aff *size)
1773 isl_set *valid;
1774 isl_set *univ;
1775 isl_set *bound;
1776 isl_space *dim;
1777 isl_aff *aff;
1778 isl_pw_aff *index;
1779 isl_id *id;
1781 if (!array)
1782 goto error;
1784 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
1785 array->context = isl_set_intersect(array->context, valid);
1787 dim = isl_set_get_space(array->extent);
1788 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1789 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
1790 univ = isl_set_universe(isl_aff_get_domain_space(aff));
1791 index = isl_pw_aff_alloc(univ, aff);
1793 size = isl_pw_aff_add_dims(size, isl_dim_in,
1794 isl_set_dim(array->extent, isl_dim_set));
1795 id = isl_set_get_tuple_id(array->extent);
1796 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
1797 bound = isl_pw_aff_lt_set(index, size);
1799 array->extent = isl_set_intersect(array->extent, bound);
1801 if (!array->context || !array->extent)
1802 return pet_array_free(array);
1804 return array;
1805 error:
1806 isl_pw_aff_free(size);
1807 return NULL;
1810 /* Figure out the size of the array at position "pos" and all
1811 * subsequent positions from "type" and update the corresponding
1812 * argument of "expr" accordingly.
1814 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
1815 const Type *type, int pos)
1817 const ArrayType *atype;
1818 pet_expr *size;
1820 if (!expr)
1821 return NULL;
1823 if (type->isPointerType()) {
1824 type = type->getPointeeType().getTypePtr();
1825 return set_upper_bounds(expr, type, pos + 1);
1827 if (!type->isArrayType())
1828 return expr;
1830 type = type->getCanonicalTypeInternal().getTypePtr();
1831 atype = cast<ArrayType>(type);
1833 if (type->isConstantArrayType()) {
1834 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
1835 size = extract_expr(ca->getSize());
1836 expr = pet_expr_set_arg(expr, pos, size);
1837 } else if (type->isVariableArrayType()) {
1838 const VariableArrayType *vla = cast<VariableArrayType>(atype);
1839 size = extract_expr(vla->getSizeExpr());
1840 expr = pet_expr_set_arg(expr, pos, size);
1843 type = atype->getElementType().getTypePtr();
1845 return set_upper_bounds(expr, type, pos + 1);
1848 /* Construct a pet_expr that holds the sizes of an array of the given type.
1849 * The returned expression is a call expression with as arguments
1850 * the sizes in each dimension. If we are unable to derive the size
1851 * in a given dimension, then the corresponding argument is set to infinity.
1852 * In fact, we initialize all arguments to infinity and then update
1853 * them if we are able to figure out the size.
1855 * The result is stored in the type_size cache so that we can reuse
1856 * it if this method gets called on the same type again later on.
1858 __isl_give pet_expr *PetScan::get_array_size(const Type *type)
1860 int depth;
1861 pet_expr *expr, *inf;
1863 if (type_size.find(type) != type_size.end())
1864 return pet_expr_copy(type_size[type]);
1866 depth = array_depth(type);
1867 inf = pet_expr_new_int(isl_val_infty(ctx));
1868 expr = pet_expr_new_call(ctx, "bounds", depth);
1869 for (int i = 0; i < depth; ++i)
1870 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
1871 pet_expr_free(inf);
1873 expr = set_upper_bounds(expr, type, 0);
1874 type_size[type] = pet_expr_copy(expr);
1876 return expr;
1879 /* Does "expr" represent the "integer" infinity?
1881 static int is_infty(__isl_keep pet_expr *expr)
1883 isl_val *v;
1884 int res;
1886 if (pet_expr_get_type(expr) != pet_expr_int)
1887 return 0;
1888 v = pet_expr_int_get_val(expr);
1889 res = isl_val_is_infty(v);
1890 isl_val_free(v);
1892 return res;
1895 /* Figure out the dimensions of an array "array" based on its type
1896 * "type" and update "array" accordingly.
1898 * We first construct a pet_expr that holds the sizes of the array
1899 * in each dimension. The resulting expression may containing
1900 * infinity values for dimension where we are unable to derive
1901 * a size expression.
1903 * The arguments of the size expression that have a value different from
1904 * infinity are then converted to an affine expression
1905 * within the context "pc" and incorporated into the size of "array".
1906 * If we are unable to convert a size expression to an affine expression,
1907 * then we leave the corresponding size of "array" untouched.
1909 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
1910 const Type *type, __isl_keep pet_context *pc)
1912 int n;
1913 pet_expr *expr;
1915 if (!array)
1916 return NULL;
1918 expr = get_array_size(type);
1920 n = pet_expr_get_n_arg(expr);
1921 for (int i = 0; i < n; ++i) {
1922 pet_expr *arg;
1923 isl_pw_aff *size;
1925 arg = pet_expr_get_arg(expr, i);
1926 if (!is_infty(arg)) {
1927 size = pet_expr_extract_affine(arg, pc);
1928 if (!size)
1929 array = pet_array_free(array);
1930 else if (isl_pw_aff_involves_nan(size))
1931 isl_pw_aff_free(size);
1932 else
1933 array = update_size(array, i, size);
1935 pet_expr_free(arg);
1937 pet_expr_free(expr);
1939 return array;
1942 /* Does "decl" have definition that we can keep track of in a pet_type?
1944 static bool has_printable_definition(RecordDecl *decl)
1946 if (!decl->getDeclName())
1947 return false;
1948 return decl->getLexicalDeclContext() == decl->getDeclContext();
1951 /* Construct and return a pet_array corresponding to the variable "decl".
1952 * In particular, initialize array->extent to
1954 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
1956 * and then call set_upper_bounds to set the upper bounds on the indices
1957 * based on the type of the variable. The upper bounds are converted
1958 * to affine expressions within the context "pc".
1960 * If the base type is that of a record with a top-level definition and
1961 * if "types" is not null, then the RecordDecl corresponding to the type
1962 * is added to "types".
1964 * If the base type is that of a record with no top-level definition,
1965 * then we replace it by "<subfield>".
1967 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
1968 lex_recorddecl_set *types, __isl_keep pet_context *pc)
1970 struct pet_array *array;
1971 QualType qt = get_array_type(decl);
1972 const Type *type = qt.getTypePtr();
1973 int depth = array_depth(type);
1974 QualType base = pet_clang_base_type(qt);
1975 string name;
1976 isl_id *id;
1977 isl_space *dim;
1979 array = isl_calloc_type(ctx, struct pet_array);
1980 if (!array)
1981 return NULL;
1983 id = create_decl_id(ctx, decl);
1984 dim = isl_space_set_alloc(ctx, 0, depth);
1985 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
1987 array->extent = isl_set_nat_universe(dim);
1989 dim = isl_space_params_alloc(ctx, 0);
1990 array->context = isl_set_universe(dim);
1992 array = set_upper_bounds(array, type, pc);
1993 if (!array)
1994 return NULL;
1996 name = base.getAsString();
1998 if (types && base->isRecordType()) {
1999 RecordDecl *decl = pet_clang_record_decl(base);
2000 if (has_printable_definition(decl))
2001 types->insert(decl);
2002 else
2003 name = "<subfield>";
2006 array->element_type = strdup(name.c_str());
2007 array->element_is_record = base->isRecordType();
2008 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
2010 return array;
2013 /* Construct and return a pet_array corresponding to the sequence
2014 * of declarations "decls".
2015 * The upper bounds of the array are converted to affine expressions
2016 * within the context "pc".
2017 * If the sequence contains a single declaration, then it corresponds
2018 * to a simple array access. Otherwise, it corresponds to a member access,
2019 * with the declaration for the substructure following that of the containing
2020 * structure in the sequence of declarations.
2021 * We start with the outermost substructure and then combine it with
2022 * information from the inner structures.
2024 * Additionally, keep track of all required types in "types".
2026 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
2027 vector<ValueDecl *> decls, lex_recorddecl_set *types,
2028 __isl_keep pet_context *pc)
2030 struct pet_array *array;
2031 vector<ValueDecl *>::iterator it;
2033 it = decls.begin();
2035 array = extract_array(ctx, *it, types, pc);
2037 for (++it; it != decls.end(); ++it) {
2038 struct pet_array *parent;
2039 const char *base_name, *field_name;
2040 char *product_name;
2042 parent = array;
2043 array = extract_array(ctx, *it, types, pc);
2044 if (!array)
2045 return pet_array_free(parent);
2047 base_name = isl_set_get_tuple_name(parent->extent);
2048 field_name = isl_set_get_tuple_name(array->extent);
2049 product_name = pet_array_member_access_name(ctx,
2050 base_name, field_name);
2052 array->extent = isl_set_product(isl_set_copy(parent->extent),
2053 array->extent);
2054 if (product_name)
2055 array->extent = isl_set_set_tuple_name(array->extent,
2056 product_name);
2057 array->context = isl_set_intersect(array->context,
2058 isl_set_copy(parent->context));
2060 pet_array_free(parent);
2061 free(product_name);
2063 if (!array->extent || !array->context || !product_name)
2064 return pet_array_free(array);
2067 return array;
2070 /* Add a pet_type corresponding to "decl" to "scop, provided
2071 * it is a member of "types" and it has not been added before
2072 * (i.e., it is not a member of "types_done".
2074 * Since we want the user to be able to print the types
2075 * in the order in which they appear in the scop, we need to
2076 * make sure that types of fields in a structure appear before
2077 * that structure. We therefore call ourselves recursively
2078 * on the types of all record subfields.
2080 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2081 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
2082 lex_recorddecl_set &types_done)
2084 string s;
2085 llvm::raw_string_ostream S(s);
2086 RecordDecl::field_iterator it;
2088 if (types.find(decl) == types.end())
2089 return scop;
2090 if (types_done.find(decl) != types_done.end())
2091 return scop;
2093 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
2094 RecordDecl *record;
2095 QualType type = it->getType();
2097 if (!type->isRecordType())
2098 continue;
2099 record = pet_clang_record_decl(type);
2100 scop = add_type(ctx, scop, record, PP, types, types_done);
2103 if (strlen(decl->getName().str().c_str()) == 0)
2104 return scop;
2106 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2107 S.str();
2109 scop->types[scop->n_type] = pet_type_alloc(ctx,
2110 decl->getName().str().c_str(), s.c_str());
2111 if (!scop->types[scop->n_type])
2112 return pet_scop_free(scop);
2114 types_done.insert(decl);
2116 scop->n_type++;
2118 return scop;
2121 /* Construct a list of pet_arrays, one for each array (or scalar)
2122 * accessed inside "scop", add this list to "scop" and return the result.
2123 * The upper bounds of the arrays are converted to affine expressions
2124 * within the context "pc".
2126 * The context of "scop" is updated with the intersection of
2127 * the contexts of all arrays, i.e., constraints on the parameters
2128 * that ensure that the arrays have a valid (non-negative) size.
2130 * If the any of the extracted arrays refers to a member access,
2131 * then also add the required types to "scop".
2133 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
2134 __isl_keep pet_context *pc)
2136 int i;
2137 array_desc_set arrays;
2138 array_desc_set::iterator it;
2139 lex_recorddecl_set types;
2140 lex_recorddecl_set types_done;
2141 lex_recorddecl_set::iterator types_it;
2142 int n_array;
2143 struct pet_array **scop_arrays;
2145 if (!scop)
2146 return NULL;
2148 pet_scop_collect_arrays(scop, arrays);
2149 if (arrays.size() == 0)
2150 return scop;
2152 n_array = scop->n_array;
2154 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2155 n_array + arrays.size());
2156 if (!scop_arrays)
2157 goto error;
2158 scop->arrays = scop_arrays;
2160 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
2161 struct pet_array *array;
2162 array = extract_array(ctx, *it, &types, pc);
2163 scop->arrays[n_array + i] = array;
2164 if (!scop->arrays[n_array + i])
2165 goto error;
2166 scop->n_array++;
2167 scop->context = isl_set_intersect(scop->context,
2168 isl_set_copy(array->context));
2169 if (!scop->context)
2170 goto error;
2173 if (types.size() == 0)
2174 return scop;
2176 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
2177 if (!scop->types)
2178 goto error;
2180 for (types_it = types.begin(); types_it != types.end(); ++types_it)
2181 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
2183 return scop;
2184 error:
2185 pet_scop_free(scop);
2186 return NULL;
2189 /* Bound all parameters in scop->context to the possible values
2190 * of the corresponding C variable.
2192 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
2194 int n;
2196 if (!scop)
2197 return NULL;
2199 n = isl_set_dim(scop->context, isl_dim_param);
2200 for (int i = 0; i < n; ++i) {
2201 isl_id *id;
2202 ValueDecl *decl;
2204 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
2205 if (pet_nested_in_id(id)) {
2206 isl_id_free(id);
2207 isl_die(isl_set_get_ctx(scop->context),
2208 isl_error_internal,
2209 "unresolved nested parameter", goto error);
2211 decl = (ValueDecl *) isl_id_get_user(id);
2212 isl_id_free(id);
2214 scop->context = set_parameter_bounds(scop->context, i, decl);
2216 if (!scop->context)
2217 goto error;
2220 return scop;
2221 error:
2222 pet_scop_free(scop);
2223 return NULL;
2226 /* Construct a pet_scop from the given function.
2228 * If the scop was delimited by scop and endscop pragmas, then we override
2229 * the file offsets by those derived from the pragmas.
2231 struct pet_scop *PetScan::scan(FunctionDecl *fd)
2233 pet_scop *scop;
2234 Stmt *stmt;
2236 stmt = fd->getBody();
2238 if (options->autodetect) {
2239 scop = extract_scop(extract(stmt, true));
2240 } else {
2241 scop = scan(stmt);
2242 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
2244 scop = add_parameter_bounds(scop);
2245 scop = pet_scop_gist(scop, value_bounds);
2247 return scop;