extract patching of index expressions and access relations to separate file
[pet.git] / scan.cc
blobcbeab17cb281aad80442d8ddaf61ee93a362808c
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 "id.h"
60 #include "nest.h"
61 #include "options.h"
62 #include "scan.h"
63 #include "scop.h"
64 #include "scop_plus.h"
65 #include "tree.h"
66 #include "tree2scop.h"
68 using namespace std;
69 using namespace clang;
71 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
73 switch (kind) {
74 case UO_Minus:
75 return pet_op_minus;
76 case UO_Not:
77 return pet_op_not;
78 case UO_LNot:
79 return pet_op_lnot;
80 case UO_PostInc:
81 return pet_op_post_inc;
82 case UO_PostDec:
83 return pet_op_post_dec;
84 case UO_PreInc:
85 return pet_op_pre_inc;
86 case UO_PreDec:
87 return pet_op_pre_dec;
88 default:
89 return pet_op_last;
93 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
95 switch (kind) {
96 case BO_AddAssign:
97 return pet_op_add_assign;
98 case BO_SubAssign:
99 return pet_op_sub_assign;
100 case BO_MulAssign:
101 return pet_op_mul_assign;
102 case BO_DivAssign:
103 return pet_op_div_assign;
104 case BO_Assign:
105 return pet_op_assign;
106 case BO_Add:
107 return pet_op_add;
108 case BO_Sub:
109 return pet_op_sub;
110 case BO_Mul:
111 return pet_op_mul;
112 case BO_Div:
113 return pet_op_div;
114 case BO_Rem:
115 return pet_op_mod;
116 case BO_Shl:
117 return pet_op_shl;
118 case BO_Shr:
119 return pet_op_shr;
120 case BO_EQ:
121 return pet_op_eq;
122 case BO_NE:
123 return pet_op_ne;
124 case BO_LE:
125 return pet_op_le;
126 case BO_GE:
127 return pet_op_ge;
128 case BO_LT:
129 return pet_op_lt;
130 case BO_GT:
131 return pet_op_gt;
132 case BO_And:
133 return pet_op_and;
134 case BO_Xor:
135 return pet_op_xor;
136 case BO_Or:
137 return pet_op_or;
138 case BO_LAnd:
139 return pet_op_land;
140 case BO_LOr:
141 return pet_op_lor;
142 default:
143 return pet_op_last;
147 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
148 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
150 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
151 SourceLocation(), var, false, var->getInnerLocStart(),
152 var->getType(), VK_LValue);
154 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
155 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
157 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
158 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
159 VK_LValue);
161 #else
162 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
164 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
165 var, var->getInnerLocStart(), var->getType(), VK_LValue);
167 #endif
169 #ifdef GETTYPEINFORETURNSTYPEINFO
171 static int size_in_bytes(ASTContext &context, QualType type)
173 return context.getTypeInfo(type).Width / 8;
176 #else
178 static int size_in_bytes(ASTContext &context, QualType type)
180 return context.getTypeInfo(type).first / 8;
183 #endif
185 /* Check if the element type corresponding to the given array type
186 * has a const qualifier.
188 static bool const_base(QualType qt)
190 const Type *type = qt.getTypePtr();
192 if (type->isPointerType())
193 return const_base(type->getPointeeType());
194 if (type->isArrayType()) {
195 const ArrayType *atype;
196 type = type->getCanonicalTypeInternal().getTypePtr();
197 atype = cast<ArrayType>(type);
198 return const_base(atype->getElementType());
201 return qt.isConstQualified();
204 PetScan::~PetScan()
206 std::map<const Type *, pet_expr *>::iterator it;
207 std::map<FunctionDecl *, pet_function_summary *>::iterator it_s;
209 for (it = type_size.begin(); it != type_size.end(); ++it)
210 pet_expr_free(it->second);
211 for (it_s = summary_cache.begin(); it_s != summary_cache.end(); ++it_s)
212 pet_function_summary_free(it_s->second);
214 isl_union_map_free(value_bounds);
217 /* Report a diagnostic, unless autodetect is set.
219 void PetScan::report(Stmt *stmt, unsigned id)
221 if (options->autodetect)
222 return;
224 SourceLocation loc = stmt->getLocStart();
225 DiagnosticsEngine &diag = PP.getDiagnostics();
226 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
229 /* Called if we found something we (currently) cannot handle.
230 * We'll provide more informative warnings later.
232 * We only actually complain if autodetect is false.
234 void PetScan::unsupported(Stmt *stmt)
236 DiagnosticsEngine &diag = PP.getDiagnostics();
237 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
238 "unsupported");
239 report(stmt, id);
242 /* Report an unsupported unary operator, unless autodetect is set.
244 void PetScan::report_unsupported_unary_operator(Stmt *stmt)
246 DiagnosticsEngine &diag = PP.getDiagnostics();
247 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
248 "this type of unary operator is not supported");
249 report(stmt, id);
252 /* Report an unsupported statement type, unless autodetect is set.
254 void PetScan::report_unsupported_statement_type(Stmt *stmt)
256 DiagnosticsEngine &diag = PP.getDiagnostics();
257 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
258 "this type of statement is not supported");
259 report(stmt, id);
262 /* Report a missing prototype, unless autodetect is set.
264 void PetScan::report_prototype_required(Stmt *stmt)
266 DiagnosticsEngine &diag = PP.getDiagnostics();
267 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
268 "prototype required");
269 report(stmt, id);
272 /* Report a missing increment, unless autodetect is set.
274 void PetScan::report_missing_increment(Stmt *stmt)
276 DiagnosticsEngine &diag = PP.getDiagnostics();
277 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
278 "missing increment");
279 report(stmt, id);
282 /* Report a missing summary function, unless autodetect is set.
284 void PetScan::report_missing_summary_function(Stmt *stmt)
286 DiagnosticsEngine &diag = PP.getDiagnostics();
287 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
288 "missing summary function");
289 report(stmt, id);
292 /* Report a missing summary function body, unless autodetect is set.
294 void PetScan::report_missing_summary_function_body(Stmt *stmt)
296 DiagnosticsEngine &diag = PP.getDiagnostics();
297 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
298 "missing summary function body");
299 report(stmt, id);
302 /* Extract an integer from "val", which is assumed to be non-negative.
304 static __isl_give isl_val *extract_unsigned(isl_ctx *ctx,
305 const llvm::APInt &val)
307 unsigned n;
308 const uint64_t *data;
310 data = val.getRawData();
311 n = val.getNumWords();
312 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
315 /* Extract an integer from "val". If "is_signed" is set, then "val"
316 * is signed. Otherwise it it unsigned.
318 static __isl_give isl_val *extract_int(isl_ctx *ctx, bool is_signed,
319 llvm::APInt val)
321 int is_negative = is_signed && val.isNegative();
322 isl_val *v;
324 if (is_negative)
325 val = -val;
327 v = extract_unsigned(ctx, val);
329 if (is_negative)
330 v = isl_val_neg(v);
331 return v;
334 /* Extract an integer from "expr".
336 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
338 const Type *type = expr->getType().getTypePtr();
339 bool is_signed = type->hasSignedIntegerRepresentation();
341 return ::extract_int(ctx, is_signed, expr->getValue());
344 /* Extract an integer from "expr".
345 * Return NULL if "expr" does not (obviously) represent an integer.
347 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
349 return extract_int(expr->getSubExpr());
352 /* Extract an integer from "expr".
353 * Return NULL if "expr" does not (obviously) represent an integer.
355 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
357 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
358 return extract_int(ctx, cast<IntegerLiteral>(expr));
359 if (expr->getStmtClass() == Stmt::ParenExprClass)
360 return extract_int(cast<ParenExpr>(expr));
362 unsupported(expr);
363 return NULL;
366 /* Extract a pet_expr from the APInt "val", which is assumed
367 * to be non-negative.
369 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
371 return pet_expr_new_int(extract_unsigned(ctx, val));
374 /* Return the number of bits needed to represent the type "qt",
375 * if it is an integer type. Otherwise return 0.
376 * If qt is signed then return the opposite of the number of bits.
378 static int get_type_size(QualType qt, ASTContext &ast_context)
380 int size;
382 if (!qt->isIntegerType())
383 return 0;
385 size = ast_context.getIntWidth(qt);
386 if (!qt->isUnsignedIntegerType())
387 size = -size;
389 return size;
392 /* Return the number of bits needed to represent the type of "decl",
393 * if it is an integer type. Otherwise return 0.
394 * If qt is signed then return the opposite of the number of bits.
396 static int get_type_size(ValueDecl *decl)
398 return get_type_size(decl->getType(), decl->getASTContext());
401 /* Bound parameter "pos" of "set" to the possible values of "decl".
403 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
404 unsigned pos, ValueDecl *decl)
406 int type_size;
407 isl_ctx *ctx;
408 isl_val *bound;
410 ctx = isl_set_get_ctx(set);
411 type_size = get_type_size(decl);
412 if (type_size == 0)
413 isl_die(ctx, isl_error_invalid, "not an integer type",
414 return isl_set_free(set));
415 if (type_size > 0) {
416 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
417 bound = isl_val_int_from_ui(ctx, type_size);
418 bound = isl_val_2exp(bound);
419 bound = isl_val_sub_ui(bound, 1);
420 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
421 } else {
422 bound = isl_val_int_from_ui(ctx, -type_size - 1);
423 bound = isl_val_2exp(bound);
424 bound = isl_val_sub_ui(bound, 1);
425 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
426 isl_val_copy(bound));
427 bound = isl_val_neg(bound);
428 bound = isl_val_sub_ui(bound, 1);
429 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
432 return set;
435 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
437 return extract_index_expr(expr->getSubExpr());
440 /* Return the depth of an array of the given type.
442 static int array_depth(const Type *type)
444 if (type->isPointerType())
445 return 1 + array_depth(type->getPointeeType().getTypePtr());
446 if (type->isArrayType()) {
447 const ArrayType *atype;
448 type = type->getCanonicalTypeInternal().getTypePtr();
449 atype = cast<ArrayType>(type);
450 return 1 + array_depth(atype->getElementType().getTypePtr());
452 return 0;
455 /* Return the depth of the array accessed by the index expression "index".
456 * If "index" is an affine expression, i.e., if it does not access
457 * any array, then return 1.
458 * If "index" represent a member access, i.e., if its range is a wrapped
459 * relation, then return the sum of the depth of the array of structures
460 * and that of the member inside the structure.
462 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
464 isl_id *id;
465 ValueDecl *decl;
467 if (!index)
468 return -1;
470 if (isl_multi_pw_aff_range_is_wrapping(index)) {
471 int domain_depth, range_depth;
472 isl_multi_pw_aff *domain, *range;
474 domain = isl_multi_pw_aff_copy(index);
475 domain = isl_multi_pw_aff_range_factor_domain(domain);
476 domain_depth = extract_depth(domain);
477 isl_multi_pw_aff_free(domain);
478 range = isl_multi_pw_aff_copy(index);
479 range = isl_multi_pw_aff_range_factor_range(range);
480 range_depth = extract_depth(range);
481 isl_multi_pw_aff_free(range);
483 return domain_depth + range_depth;
486 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
487 return 1;
489 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
490 if (!id)
491 return -1;
492 decl = pet_id_get_decl(id);
493 isl_id_free(id);
495 return array_depth(decl->getType().getTypePtr());
498 /* Return the depth of the array accessed by the access expression "expr".
500 static int extract_depth(__isl_keep pet_expr *expr)
502 isl_multi_pw_aff *index;
503 int depth;
505 index = pet_expr_access_get_index(expr);
506 depth = extract_depth(index);
507 isl_multi_pw_aff_free(index);
509 return depth;
512 /* Construct a pet_expr representing an index expression for an access
513 * to the variable referenced by "expr".
515 * If "expr" references an enum constant, then return an integer expression
516 * instead, representing the value of the enum constant.
518 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
520 return extract_index_expr(expr->getDecl());
523 /* Construct a pet_expr representing an index expression for an access
524 * to the variable "decl".
526 * If "decl" is an enum constant, then we return an integer expression
527 * instead, representing the value of the enum constant.
529 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
531 isl_id *id;
532 isl_space *space;
534 if (isa<EnumConstantDecl>(decl))
535 return extract_expr(cast<EnumConstantDecl>(decl));
537 id = pet_id_from_decl(ctx, decl);
538 space = isl_space_alloc(ctx, 0, 0, 0);
539 space = isl_space_set_tuple_id(space, isl_dim_out, id);
541 return pet_expr_from_index(isl_multi_pw_aff_zero(space));
544 /* Construct a pet_expr representing the index expression "expr"
545 * Return NULL on error.
547 * If "expr" is a reference to an enum constant, then return
548 * an integer expression instead, representing the value of the enum constant.
550 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
552 switch (expr->getStmtClass()) {
553 case Stmt::ImplicitCastExprClass:
554 return extract_index_expr(cast<ImplicitCastExpr>(expr));
555 case Stmt::DeclRefExprClass:
556 return extract_index_expr(cast<DeclRefExpr>(expr));
557 case Stmt::ArraySubscriptExprClass:
558 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
559 case Stmt::IntegerLiteralClass:
560 return extract_expr(cast<IntegerLiteral>(expr));
561 case Stmt::MemberExprClass:
562 return extract_index_expr(cast<MemberExpr>(expr));
563 default:
564 unsupported(expr);
566 return NULL;
569 /* Extract an index expression from the given array subscript expression.
571 * We first extract an index expression from the base.
572 * This will result in an index expression with a range that corresponds
573 * to the earlier indices.
574 * We then extract the current index and let
575 * pet_expr_access_subscript combine the two.
577 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
579 Expr *base = expr->getBase();
580 Expr *idx = expr->getIdx();
581 pet_expr *index;
582 pet_expr *base_expr;
584 base_expr = extract_index_expr(base);
585 index = extract_expr(idx);
587 base_expr = pet_expr_access_subscript(base_expr, index);
589 return base_expr;
592 /* Extract an index expression from a member expression.
594 * If the base access (to the structure containing the member)
595 * is of the form
597 * A[..]
599 * and the member is called "f", then the member access is of
600 * the form
602 * A_f[A[..] -> f[]]
604 * If the member access is to an anonymous struct, then simply return
606 * A[..]
608 * If the member access in the source code is of the form
610 * A->f
612 * then it is treated as
614 * A[0].f
616 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
618 Expr *base = expr->getBase();
619 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
620 pet_expr *base_index;
621 isl_id *id;
623 base_index = extract_index_expr(base);
625 if (expr->isArrow()) {
626 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
627 base_index = pet_expr_access_subscript(base_index, index);
630 if (field->isAnonymousStructOrUnion())
631 return base_index;
633 id = pet_id_from_decl(ctx, field);
635 return pet_expr_access_member(base_index, id);
638 /* Mark the given access pet_expr as a write.
640 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
642 access = pet_expr_access_set_write(access, 1);
643 access = pet_expr_access_set_read(access, 0);
645 return access;
648 /* Mark the given (read) access pet_expr as also possibly being written.
649 * That is, initialize the may write access relation from the may read relation
650 * and initialize the must write access relation to the empty relation.
652 static __isl_give pet_expr *mark_may_write(__isl_take pet_expr *expr)
654 isl_union_map *access;
655 isl_union_map *empty;
657 access = pet_expr_access_get_dependent_access(expr,
658 pet_expr_access_may_read);
659 empty = isl_union_map_empty(isl_union_map_get_space(access));
660 expr = pet_expr_access_set_access(expr, pet_expr_access_may_write,
661 access);
662 expr = pet_expr_access_set_access(expr, pet_expr_access_must_write,
663 empty);
665 return expr;
668 /* Construct a pet_expr representing a unary operator expression.
670 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
672 int type_size;
673 pet_expr *arg;
674 enum pet_op_type op;
676 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
677 if (op == pet_op_last) {
678 report_unsupported_unary_operator(expr);
679 return NULL;
682 arg = extract_expr(expr->getSubExpr());
684 if (expr->isIncrementDecrementOp() &&
685 pet_expr_get_type(arg) == pet_expr_access) {
686 arg = mark_write(arg);
687 arg = pet_expr_access_set_read(arg, 1);
690 type_size = get_type_size(expr->getType(), ast_context);
691 return pet_expr_new_unary(type_size, op, arg);
694 /* Construct a pet_expr representing a binary operator expression.
696 * If the top level operator is an assignment and the LHS is an access,
697 * then we mark that access as a write. If the operator is a compound
698 * assignment, the access is marked as both a read and a write.
700 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
702 int type_size;
703 pet_expr *lhs, *rhs;
704 enum pet_op_type op;
706 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
707 if (op == pet_op_last) {
708 unsupported(expr);
709 return NULL;
712 lhs = extract_expr(expr->getLHS());
713 rhs = extract_expr(expr->getRHS());
715 if (expr->isAssignmentOp() &&
716 pet_expr_get_type(lhs) == pet_expr_access) {
717 lhs = mark_write(lhs);
718 if (expr->isCompoundAssignmentOp())
719 lhs = pet_expr_access_set_read(lhs, 1);
722 type_size = get_type_size(expr->getType(), ast_context);
723 return pet_expr_new_binary(type_size, op, lhs, rhs);
726 /* Construct a pet_tree for a variable declaration.
728 __isl_give pet_tree *PetScan::extract(Decl *decl)
730 VarDecl *vd;
731 pet_expr *lhs, *rhs;
732 pet_tree *tree;
734 vd = cast<VarDecl>(decl);
736 lhs = extract_access_expr(vd);
737 lhs = mark_write(lhs);
738 if (!vd->getInit())
739 tree = pet_tree_new_decl(lhs);
740 else {
741 rhs = extract_expr(vd->getInit());
742 tree = pet_tree_new_decl_init(lhs, rhs);
745 return tree;
748 /* Construct a pet_tree for a variable declaration statement.
749 * If the declaration statement declares multiple variables,
750 * then return a group of pet_trees, one for each declared variable.
752 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
754 pet_tree *tree;
755 unsigned n;
757 if (!stmt->isSingleDecl()) {
758 const DeclGroup &group = stmt->getDeclGroup().getDeclGroup();
759 n = group.size();
760 tree = pet_tree_new_block(ctx, 0, n);
762 for (int i = 0; i < n; ++i) {
763 pet_tree *tree_i;
764 pet_loc *loc;
766 tree_i = extract(group[i]);
767 loc = construct_pet_loc(group[i]->getSourceRange(),
768 false);
769 tree_i = pet_tree_set_loc(tree_i, loc);
770 tree = pet_tree_block_add_child(tree, tree_i);
773 return tree;
776 return extract(stmt->getSingleDecl());
779 /* Construct a pet_expr representing a conditional operation.
781 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
783 pet_expr *cond, *lhs, *rhs;
784 isl_pw_aff *pa;
786 cond = extract_expr(expr->getCond());
787 lhs = extract_expr(expr->getTrueExpr());
788 rhs = extract_expr(expr->getFalseExpr());
790 return pet_expr_new_ternary(cond, lhs, rhs);
793 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
795 return extract_expr(expr->getSubExpr());
798 /* Construct a pet_expr representing a floating point value.
800 * If the floating point literal does not appear in a macro,
801 * then we use the original representation in the source code
802 * as the string representation. Otherwise, we use the pretty
803 * printer to produce a string representation.
805 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
807 double d;
808 string s;
809 const LangOptions &LO = PP.getLangOpts();
810 SourceLocation loc = expr->getLocation();
812 if (!loc.isMacroID()) {
813 SourceManager &SM = PP.getSourceManager();
814 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
815 s = string(SM.getCharacterData(loc), len);
816 } else {
817 llvm::raw_string_ostream S(s);
818 expr->printPretty(S, 0, PrintingPolicy(LO));
819 S.str();
821 d = expr->getValueAsApproximateDouble();
822 return pet_expr_new_double(ctx, d, s.c_str());
825 /* Convert the index expression "index" into an access pet_expr of type "qt".
827 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
828 __isl_take pet_expr *index)
830 int depth;
831 int type_size;
833 depth = extract_depth(index);
834 type_size = get_type_size(qt, ast_context);
836 index = pet_expr_set_type_size(index, type_size);
837 index = pet_expr_access_set_depth(index, depth);
839 return index;
842 /* Extract an index expression from "expr" and then convert it into
843 * an access pet_expr.
845 * If "expr" is a reference to an enum constant, then return
846 * an integer expression instead, representing the value of the enum constant.
848 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
850 pet_expr *index;
852 index = extract_index_expr(expr);
854 if (pet_expr_get_type(index) == pet_expr_int)
855 return index;
857 return extract_access_expr(expr->getType(), index);
860 /* Extract an index expression from "decl" and then convert it into
861 * an access pet_expr.
863 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
865 return extract_access_expr(decl->getType(), extract_index_expr(decl));
868 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
870 return extract_expr(expr->getSubExpr());
873 /* Extract an assume statement from the argument "expr"
874 * of a __pencil_assume statement.
876 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
878 return pet_expr_new_unary(0, pet_op_assume, extract_expr(expr));
881 /* Construct a pet_expr corresponding to the function call argument "expr".
882 * The argument appears in position "pos" of a call to function "fd".
884 * If we are passing along a pointer to an array element
885 * or an entire row or even higher dimensional slice of an array,
886 * then the function being called may write into the array.
888 * We assume here that if the function is declared to take a pointer
889 * to a const type, then the function may only perform a read
890 * and that otherwise, it may either perform a read or a write (or both).
891 * We only perform this check if "detect_writes" is set.
893 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
894 Expr *expr, bool detect_writes)
896 pet_expr *res;
897 int is_addr = 0, is_partial = 0;
899 expr = pet_clang_strip_casts(expr);
900 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
901 UnaryOperator *op = cast<UnaryOperator>(expr);
902 if (op->getOpcode() == UO_AddrOf) {
903 is_addr = 1;
904 expr = op->getSubExpr();
907 res = extract_expr(expr);
908 if (!res)
909 return NULL;
910 if (array_depth(expr->getType().getTypePtr()) > 0)
911 is_partial = 1;
912 if (detect_writes && (is_addr || is_partial) &&
913 pet_expr_get_type(res) == pet_expr_access) {
914 ParmVarDecl *parm;
915 if (!fd->hasPrototype()) {
916 report_prototype_required(expr);
917 return pet_expr_free(res);
919 parm = fd->getParamDecl(pos);
920 if (!const_base(parm->getType()))
921 res = mark_may_write(res);
924 if (is_addr)
925 res = pet_expr_new_unary(0, pet_op_address_of, res);
926 return res;
929 /* Find the first FunctionDecl with the given name.
930 * "call" is the corresponding call expression and is only used
931 * for reporting errors.
933 * Return NULL on error.
935 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
937 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
938 DeclContext::decl_iterator begin = tu->decls_begin();
939 DeclContext::decl_iterator end = tu->decls_end();
940 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
941 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
942 if (!fd)
943 continue;
944 if (fd->getName().str().compare(name) != 0)
945 continue;
946 if (fd->hasBody())
947 return fd;
948 report_missing_summary_function_body(call);
949 return NULL;
951 report_missing_summary_function(call);
952 return NULL;
955 /* Return the FunctionDecl for the summary function associated to the
956 * function called by "call".
958 * In particular, if the pencil option is set, then
959 * search for an annotate attribute formatted as
960 * "pencil_access(name)", where "name" is the name of the summary function.
962 * If no summary function was specified, then return the FunctionDecl
963 * that is actually being called.
965 * Return NULL on error.
967 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
969 FunctionDecl *decl = call->getDirectCallee();
970 if (!decl)
971 return NULL;
973 if (!options->pencil)
974 return decl;
976 specific_attr_iterator<AnnotateAttr> begin, end, i;
977 begin = decl->specific_attr_begin<AnnotateAttr>();
978 end = decl->specific_attr_end<AnnotateAttr>();
979 for (i = begin; i != end; ++i) {
980 string attr = (*i)->getAnnotation().str();
982 const char prefix[] = "pencil_access(";
983 size_t start = attr.find(prefix);
984 if (start == string::npos)
985 continue;
986 start += strlen(prefix);
987 string name = attr.substr(start, attr.find(')') - start);
989 return find_decl_from_name(call, name);
992 return decl;
995 /* Construct a pet_expr representing a function call.
997 * In the special case of a "call" to __pencil_assume,
998 * construct an assume expression instead.
1000 * In the case of a "call" to __pencil_kill, the arguments
1001 * are neither read nor written (only killed), so there
1002 * is no need to check for writes to these arguments.
1004 * __pencil_assume and __pencil_kill are only recognized
1005 * when the pencil option is set.
1007 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1009 pet_expr *res = NULL;
1010 FunctionDecl *fd;
1011 string name;
1012 unsigned n_arg;
1013 bool is_kill;
1015 fd = expr->getDirectCallee();
1016 if (!fd) {
1017 unsupported(expr);
1018 return NULL;
1021 name = fd->getDeclName().getAsString();
1022 n_arg = expr->getNumArgs();
1024 if (options->pencil && n_arg == 1 && name == "__pencil_assume")
1025 return extract_assume(expr->getArg(0));
1026 is_kill = options->pencil && name == "__pencil_kill";
1028 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1029 if (!res)
1030 return NULL;
1032 for (int i = 0; i < n_arg; ++i) {
1033 Expr *arg = expr->getArg(i);
1034 res = pet_expr_set_arg(res, i,
1035 PetScan::extract_argument(fd, i, arg, !is_kill));
1038 fd = get_summary_function(expr);
1039 if (!fd)
1040 return pet_expr_free(res);
1042 res = set_summary(res, fd);
1044 return res;
1047 /* Construct a pet_expr representing a (C style) cast.
1049 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1051 pet_expr *arg;
1052 QualType type;
1054 arg = extract_expr(expr->getSubExpr());
1055 if (!arg)
1056 return NULL;
1058 type = expr->getTypeAsWritten();
1059 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1062 /* Construct a pet_expr representing an integer.
1064 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1066 return pet_expr_new_int(extract_int(expr));
1069 /* Construct a pet_expr representing the integer enum constant "ecd".
1071 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
1073 isl_val *v;
1074 const llvm::APSInt &init = ecd->getInitVal();
1075 v = ::extract_int(ctx, init.isSigned(), init);
1076 return pet_expr_new_int(v);
1079 /* Try and construct a pet_expr representing "expr".
1081 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1083 switch (expr->getStmtClass()) {
1084 case Stmt::UnaryOperatorClass:
1085 return extract_expr(cast<UnaryOperator>(expr));
1086 case Stmt::CompoundAssignOperatorClass:
1087 case Stmt::BinaryOperatorClass:
1088 return extract_expr(cast<BinaryOperator>(expr));
1089 case Stmt::ImplicitCastExprClass:
1090 return extract_expr(cast<ImplicitCastExpr>(expr));
1091 case Stmt::ArraySubscriptExprClass:
1092 case Stmt::DeclRefExprClass:
1093 case Stmt::MemberExprClass:
1094 return extract_access_expr(expr);
1095 case Stmt::IntegerLiteralClass:
1096 return extract_expr(cast<IntegerLiteral>(expr));
1097 case Stmt::FloatingLiteralClass:
1098 return extract_expr(cast<FloatingLiteral>(expr));
1099 case Stmt::ParenExprClass:
1100 return extract_expr(cast<ParenExpr>(expr));
1101 case Stmt::ConditionalOperatorClass:
1102 return extract_expr(cast<ConditionalOperator>(expr));
1103 case Stmt::CallExprClass:
1104 return extract_expr(cast<CallExpr>(expr));
1105 case Stmt::CStyleCastExprClass:
1106 return extract_expr(cast<CStyleCastExpr>(expr));
1107 default:
1108 unsupported(expr);
1110 return NULL;
1113 /* Check if the given initialization statement is an assignment.
1114 * If so, return that assignment. Otherwise return NULL.
1116 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1118 BinaryOperator *ass;
1120 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1121 return NULL;
1123 ass = cast<BinaryOperator>(init);
1124 if (ass->getOpcode() != BO_Assign)
1125 return NULL;
1127 return ass;
1130 /* Check if the given initialization statement is a declaration
1131 * of a single variable.
1132 * If so, return that declaration. Otherwise return NULL.
1134 Decl *PetScan::initialization_declaration(Stmt *init)
1136 DeclStmt *decl;
1138 if (init->getStmtClass() != Stmt::DeclStmtClass)
1139 return NULL;
1141 decl = cast<DeclStmt>(init);
1143 if (!decl->isSingleDecl())
1144 return NULL;
1146 return decl->getSingleDecl();
1149 /* Given the assignment operator in the initialization of a for loop,
1150 * extract the induction variable, i.e., the (integer)variable being
1151 * assigned.
1153 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1155 Expr *lhs;
1156 DeclRefExpr *ref;
1157 ValueDecl *decl;
1158 const Type *type;
1160 lhs = init->getLHS();
1161 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1162 unsupported(init);
1163 return NULL;
1166 ref = cast<DeclRefExpr>(lhs);
1167 decl = ref->getDecl();
1168 type = decl->getType().getTypePtr();
1170 if (!type->isIntegerType()) {
1171 unsupported(lhs);
1172 return NULL;
1175 return decl;
1178 /* Given the initialization statement of a for loop and the single
1179 * declaration in this initialization statement,
1180 * extract the induction variable, i.e., the (integer) variable being
1181 * declared.
1183 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1185 VarDecl *vd;
1187 vd = cast<VarDecl>(decl);
1189 const QualType type = vd->getType();
1190 if (!type->isIntegerType()) {
1191 unsupported(init);
1192 return NULL;
1195 if (!vd->getInit()) {
1196 unsupported(init);
1197 return NULL;
1200 return vd;
1203 /* Check that op is of the form iv++ or iv--.
1204 * Return a pet_expr representing "1" or "-1" accordingly.
1206 __isl_give pet_expr *PetScan::extract_unary_increment(
1207 clang::UnaryOperator *op, clang::ValueDecl *iv)
1209 Expr *sub;
1210 DeclRefExpr *ref;
1211 isl_val *v;
1213 if (!op->isIncrementDecrementOp()) {
1214 unsupported(op);
1215 return NULL;
1218 sub = op->getSubExpr();
1219 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1220 unsupported(op);
1221 return NULL;
1224 ref = cast<DeclRefExpr>(sub);
1225 if (ref->getDecl() != iv) {
1226 unsupported(op);
1227 return NULL;
1230 if (op->isIncrementOp())
1231 v = isl_val_one(ctx);
1232 else
1233 v = isl_val_negone(ctx);
1235 return pet_expr_new_int(v);
1238 /* Check if op is of the form
1240 * iv = expr
1242 * and return the increment "expr - iv" as a pet_expr.
1244 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1245 clang::ValueDecl *iv)
1247 int type_size;
1248 Expr *lhs;
1249 DeclRefExpr *ref;
1250 pet_expr *expr, *expr_iv;
1252 if (op->getOpcode() != BO_Assign) {
1253 unsupported(op);
1254 return NULL;
1257 lhs = op->getLHS();
1258 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1259 unsupported(op);
1260 return NULL;
1263 ref = cast<DeclRefExpr>(lhs);
1264 if (ref->getDecl() != iv) {
1265 unsupported(op);
1266 return NULL;
1269 expr = extract_expr(op->getRHS());
1270 expr_iv = extract_expr(lhs);
1272 type_size = get_type_size(iv->getType(), ast_context);
1273 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1276 /* Check that op is of the form iv += cst or iv -= cst
1277 * and return a pet_expr corresponding to cst or -cst accordingly.
1279 __isl_give pet_expr *PetScan::extract_compound_increment(
1280 CompoundAssignOperator *op, clang::ValueDecl *iv)
1282 Expr *lhs;
1283 DeclRefExpr *ref;
1284 bool neg = false;
1285 pet_expr *expr;
1286 BinaryOperatorKind opcode;
1288 opcode = op->getOpcode();
1289 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1290 unsupported(op);
1291 return NULL;
1293 if (opcode == BO_SubAssign)
1294 neg = true;
1296 lhs = op->getLHS();
1297 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1298 unsupported(op);
1299 return NULL;
1302 ref = cast<DeclRefExpr>(lhs);
1303 if (ref->getDecl() != iv) {
1304 unsupported(op);
1305 return NULL;
1308 expr = extract_expr(op->getRHS());
1309 if (neg) {
1310 int type_size;
1311 type_size = get_type_size(op->getType(), ast_context);
1312 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1315 return expr;
1318 /* Check that the increment of the given for loop increments
1319 * (or decrements) the induction variable "iv" and return
1320 * the increment as a pet_expr if successful.
1322 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1323 ValueDecl *iv)
1325 Stmt *inc = stmt->getInc();
1327 if (!inc) {
1328 report_missing_increment(stmt);
1329 return NULL;
1332 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1333 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1334 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1335 return extract_compound_increment(
1336 cast<CompoundAssignOperator>(inc), iv);
1337 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1338 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1340 unsupported(inc);
1341 return NULL;
1344 /* Construct a pet_tree for a while loop.
1346 * If we were only able to extract part of the body, then simply
1347 * return that part.
1349 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1351 pet_expr *pe_cond;
1352 pet_tree *tree;
1354 tree = extract(stmt->getBody());
1355 if (partial)
1356 return tree;
1357 pe_cond = extract_expr(stmt->getCond());
1358 tree = pet_tree_new_while(pe_cond, tree);
1360 return tree;
1363 /* Construct a pet_tree for a for statement.
1364 * The for loop is required to be of one of the following forms
1366 * for (i = init; condition; ++i)
1367 * for (i = init; condition; --i)
1368 * for (i = init; condition; i += constant)
1369 * for (i = init; condition; i -= constant)
1371 * We extract a pet_tree for the body and then include it in a pet_tree
1372 * of type pet_tree_for.
1374 * As a special case, we also allow a for loop of the form
1376 * for (;;)
1378 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1380 * If we were only able to extract part of the body, then simply
1381 * return that part.
1383 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1385 BinaryOperator *ass;
1386 Decl *decl;
1387 Stmt *init;
1388 Expr *lhs, *rhs;
1389 ValueDecl *iv;
1390 pet_tree *tree;
1391 struct pet_scop *scop;
1392 int independent;
1393 int declared;
1394 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1396 independent = is_current_stmt_marked_independent();
1398 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1399 tree = extract(stmt->getBody());
1400 if (partial)
1401 return tree;
1402 tree = pet_tree_new_infinite_loop(tree);
1403 return tree;
1406 init = stmt->getInit();
1407 if (!init) {
1408 unsupported(stmt);
1409 return NULL;
1411 if ((ass = initialization_assignment(init)) != NULL) {
1412 iv = extract_induction_variable(ass);
1413 if (!iv)
1414 return NULL;
1415 lhs = ass->getLHS();
1416 rhs = ass->getRHS();
1417 } else if ((decl = initialization_declaration(init)) != NULL) {
1418 VarDecl *var = extract_induction_variable(init, decl);
1419 if (!var)
1420 return NULL;
1421 iv = var;
1422 rhs = var->getInit();
1423 lhs = create_DeclRefExpr(var);
1424 } else {
1425 unsupported(stmt->getInit());
1426 return NULL;
1429 declared = !initialization_assignment(stmt->getInit());
1430 tree = extract(stmt->getBody());
1431 if (partial)
1432 return tree;
1433 pe_iv = extract_access_expr(iv);
1434 pe_iv = mark_write(pe_iv);
1435 pe_init = extract_expr(rhs);
1436 if (!stmt->getCond())
1437 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1438 else
1439 pe_cond = extract_expr(stmt->getCond());
1440 pe_inc = extract_increment(stmt, iv);
1441 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1442 pe_inc, tree);
1443 return tree;
1446 /* Try and construct a pet_tree corresponding to a compound statement.
1448 * "skip_declarations" is set if we should skip initial declarations
1449 * in the children of the compound statements.
1451 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1452 bool skip_declarations)
1454 return extract(stmt->children(), true, skip_declarations);
1457 /* Return the file offset of the expansion location of "Loc".
1459 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1461 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1464 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1466 /* Return a SourceLocation for the location after the first semicolon
1467 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1468 * call it and also skip trailing spaces and newline.
1470 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1471 const LangOptions &LO)
1473 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1476 #else
1478 /* Return a SourceLocation for the location after the first semicolon
1479 * after "loc". If Lexer::findLocationAfterToken is not available,
1480 * we look in the underlying character data for the first semicolon.
1482 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1483 const LangOptions &LO)
1485 const char *semi;
1486 const char *s = SM.getCharacterData(loc);
1488 semi = strchr(s, ';');
1489 if (!semi)
1490 return SourceLocation();
1491 return loc.getFileLocWithOffset(semi + 1 - s);
1494 #endif
1496 /* If the token at "loc" is the first token on the line, then return
1497 * a location referring to the start of the line and set *indent
1498 * to the indentation of "loc"
1499 * Otherwise, return "loc" and set *indent to "".
1501 * This function is used to extend a scop to the start of the line
1502 * if the first token of the scop is also the first token on the line.
1504 * We look for the first token on the line. If its location is equal to "loc",
1505 * then the latter is the location of the first token on the line.
1507 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1508 SourceManager &SM, const LangOptions &LO, char **indent)
1510 std::pair<FileID, unsigned> file_offset_pair;
1511 llvm::StringRef file;
1512 const char *pos;
1513 Token tok;
1514 SourceLocation token_loc, line_loc;
1515 int col;
1516 const char *s;
1518 loc = SM.getExpansionLoc(loc);
1519 col = SM.getExpansionColumnNumber(loc);
1520 line_loc = loc.getLocWithOffset(1 - col);
1521 file_offset_pair = SM.getDecomposedLoc(line_loc);
1522 file = SM.getBufferData(file_offset_pair.first, NULL);
1523 pos = file.data() + file_offset_pair.second;
1525 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1526 file.begin(), pos, file.end());
1527 lexer.LexFromRawLexer(tok);
1528 token_loc = tok.getLocation();
1530 s = SM.getCharacterData(line_loc);
1531 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1533 if (token_loc == loc)
1534 return line_loc;
1535 else
1536 return loc;
1539 /* Construct a pet_loc corresponding to the region covered by "range".
1540 * If "skip_semi" is set, then we assume "range" is followed by
1541 * a semicolon and also include this semicolon.
1543 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1544 bool skip_semi)
1546 SourceLocation loc = range.getBegin();
1547 SourceManager &SM = PP.getSourceManager();
1548 const LangOptions &LO = PP.getLangOpts();
1549 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1550 unsigned start, end;
1551 char *indent;
1553 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1554 start = getExpansionOffset(SM, loc);
1555 loc = range.getEnd();
1556 if (skip_semi)
1557 loc = location_after_semi(loc, SM, LO);
1558 else
1559 loc = PP.getLocForEndOfToken(loc);
1560 end = getExpansionOffset(SM, loc);
1562 return pet_loc_alloc(ctx, start, end, line, indent);
1565 /* Convert a top-level pet_expr to an expression pet_tree.
1567 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1568 SourceRange range, bool skip_semi)
1570 pet_loc *loc;
1571 pet_tree *tree;
1573 tree = pet_tree_new_expr(expr);
1574 loc = construct_pet_loc(range, skip_semi);
1575 tree = pet_tree_set_loc(tree, loc);
1577 return tree;
1580 /* Construct a pet_tree for an if statement.
1582 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1584 pet_expr *pe_cond;
1585 pet_tree *tree, *tree_else;
1586 struct pet_scop *scop;
1587 int int_size;
1589 pe_cond = extract_expr(stmt->getCond());
1590 tree = extract(stmt->getThen());
1591 if (stmt->getElse()) {
1592 tree_else = extract(stmt->getElse());
1593 if (options->autodetect) {
1594 if (tree && !tree_else) {
1595 partial = true;
1596 pet_expr_free(pe_cond);
1597 return tree;
1599 if (!tree && tree_else) {
1600 partial = true;
1601 pet_expr_free(pe_cond);
1602 return tree_else;
1605 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1606 } else
1607 tree = pet_tree_new_if(pe_cond, tree);
1608 return tree;
1611 /* Try and construct a pet_tree for a label statement.
1613 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1615 isl_id *label;
1616 pet_tree *tree;
1618 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1620 tree = extract(stmt->getSubStmt());
1621 tree = pet_tree_set_label(tree, label);
1622 return tree;
1625 /* Update the location of "tree" to include the source range of "stmt".
1627 * Actually, we create a new location based on the source range of "stmt" and
1628 * then extend this new location to include the region of the original location.
1629 * This ensures that the line number of the final location refers to "stmt".
1631 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1633 pet_loc *loc, *tree_loc;
1635 tree_loc = pet_tree_get_loc(tree);
1636 loc = construct_pet_loc(stmt->getSourceRange(), false);
1637 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1638 pet_loc_free(tree_loc);
1640 tree = pet_tree_set_loc(tree, loc);
1641 return tree;
1644 /* Try and construct a pet_tree corresponding to "stmt".
1646 * If "stmt" is a compound statement, then "skip_declarations"
1647 * indicates whether we should skip initial declarations in the
1648 * compound statement.
1650 * If the constructed pet_tree is not a (possibly) partial representation
1651 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1652 * In particular, if skip_declarations is set, then we may have skipped
1653 * declarations inside "stmt" and so the pet_scop may not represent
1654 * the entire "stmt".
1655 * Note that this function may be called with "stmt" referring to the entire
1656 * body of the function, including the outer braces. In such cases,
1657 * skip_declarations will be set and the braces will not be taken into
1658 * account in tree->loc.
1660 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
1662 pet_tree *tree;
1664 set_current_stmt(stmt);
1666 if (isa<Expr>(stmt))
1667 return extract(extract_expr(cast<Expr>(stmt)),
1668 stmt->getSourceRange(), true);
1670 switch (stmt->getStmtClass()) {
1671 case Stmt::WhileStmtClass:
1672 tree = extract(cast<WhileStmt>(stmt));
1673 break;
1674 case Stmt::ForStmtClass:
1675 tree = extract_for(cast<ForStmt>(stmt));
1676 break;
1677 case Stmt::IfStmtClass:
1678 tree = extract(cast<IfStmt>(stmt));
1679 break;
1680 case Stmt::CompoundStmtClass:
1681 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
1682 break;
1683 case Stmt::LabelStmtClass:
1684 tree = extract(cast<LabelStmt>(stmt));
1685 break;
1686 case Stmt::ContinueStmtClass:
1687 tree = pet_tree_new_continue(ctx);
1688 break;
1689 case Stmt::BreakStmtClass:
1690 tree = pet_tree_new_break(ctx);
1691 break;
1692 case Stmt::DeclStmtClass:
1693 tree = extract(cast<DeclStmt>(stmt));
1694 break;
1695 default:
1696 report_unsupported_statement_type(stmt);
1697 return NULL;
1700 if (partial || skip_declarations)
1701 return tree;
1703 return update_loc(tree, stmt);
1706 /* Given a sequence of statements "stmt_range" of which the first "n_decl"
1707 * are declarations and of which the remaining statements are represented
1708 * by "tree", try and extend "tree" to include the last sequence of
1709 * the initial declarations that can be completely extracted.
1711 * We start collecting the initial declarations and start over
1712 * whenever we come across a declaration that we cannot extract.
1713 * If we have been able to extract any declarations, then we
1714 * copy over the contents of "tree" at the end of the declarations.
1715 * Otherwise, we simply return the original "tree".
1717 __isl_give pet_tree *PetScan::insert_initial_declarations(
1718 __isl_take pet_tree *tree, int n_decl, StmtRange stmt_range)
1720 StmtIterator i;
1721 pet_tree *res;
1722 int n_stmt;
1723 int is_block;
1724 int j;
1726 n_stmt = pet_tree_block_n_child(tree);
1727 is_block = pet_tree_block_get_block(tree);
1728 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
1730 for (i = stmt_range.first; n_decl; ++i, --n_decl) {
1731 Stmt *child = *i;
1732 pet_tree *tree_i;
1734 tree_i = extract(child);
1735 if (tree_i && !partial) {
1736 res = pet_tree_block_add_child(res, tree_i);
1737 continue;
1739 pet_tree_free(tree_i);
1740 partial = false;
1741 if (pet_tree_block_n_child(res) == 0)
1742 continue;
1743 pet_tree_free(res);
1744 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
1747 if (pet_tree_block_n_child(res) == 0) {
1748 pet_tree_free(res);
1749 return tree;
1752 for (j = 0; j < n_stmt; ++j) {
1753 pet_tree *tree_i;
1755 tree_i = pet_tree_block_get_child(tree, j);
1756 res = pet_tree_block_add_child(res, tree_i);
1758 pet_tree_free(tree);
1760 return res;
1763 /* Try and construct a pet_tree corresponding to (part of)
1764 * a sequence of statements.
1766 * "block" is set if the sequence represents the children of
1767 * a compound statement.
1768 * "skip_declarations" is set if we should skip initial declarations
1769 * in the sequence of statements.
1771 * If autodetect is set, then we allow the extraction of only a subrange
1772 * of the sequence of statements. However, if there is at least one
1773 * kill and there is some subsequent statement for which we could not
1774 * construct a tree, then turn off the "block" property of the tree
1775 * such that no extra kill will be introduced at the end of the (partial)
1776 * block. If, on the other hand, the final range contains
1777 * no statements, then we discard the entire range.
1779 * If the entire range was extracted, apart from some initial declarations,
1780 * then we try and extend the range with the latest of those initial
1781 * declarations.
1783 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
1784 bool skip_declarations)
1786 StmtIterator i;
1787 int j, skip;
1788 bool has_kills = false;
1789 bool partial_range = false;
1790 pet_tree *tree;
1792 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
1795 tree = pet_tree_new_block(ctx, block, j);
1797 skip = 0;
1798 i = stmt_range.first;
1799 if (skip_declarations)
1800 for (; i != stmt_range.second; ++i) {
1801 if ((*i)->getStmtClass() != Stmt::DeclStmtClass)
1802 break;
1803 ++skip;
1806 for (; i != stmt_range.second; ++i) {
1807 Stmt *child = *i;
1808 pet_tree *tree_i;
1810 tree_i = extract(child);
1811 if (pet_tree_block_n_child(tree) != 0 && partial) {
1812 pet_tree_free(tree_i);
1813 break;
1815 if (tree_i && child->getStmtClass() == Stmt::DeclStmtClass &&
1816 block)
1817 has_kills = true;
1818 if (options->autodetect) {
1819 if (tree_i)
1820 tree = pet_tree_block_add_child(tree, tree_i);
1821 else
1822 partial_range = true;
1823 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
1824 partial = true;
1825 } else {
1826 tree = pet_tree_block_add_child(tree, tree_i);
1829 if (partial || !tree)
1830 break;
1833 if (!tree)
1834 return NULL;
1836 if (partial) {
1837 if (has_kills)
1838 tree = pet_tree_block_set_block(tree, 0);
1839 } else if (partial_range) {
1840 if (pet_tree_block_n_child(tree) == 0) {
1841 pet_tree_free(tree);
1842 return NULL;
1844 partial = true;
1845 } else if (skip > 0)
1846 tree = insert_initial_declarations(tree, skip, stmt_range);
1848 return tree;
1851 /* Is "T" the type of a variable length array with static size?
1853 static bool is_vla_with_static_size(QualType T)
1855 const VariableArrayType *vlatype;
1857 if (!T->isVariableArrayType())
1858 return false;
1859 vlatype = cast<VariableArrayType>(T);
1860 return vlatype->getSizeModifier() == VariableArrayType::Static;
1863 /* Return the type of "decl" as an array.
1865 * In particular, if "decl" is a parameter declaration that
1866 * is a variable length array with a static size, then
1867 * return the original type (i.e., the variable length array).
1868 * Otherwise, return the type of decl.
1870 static QualType get_array_type(ValueDecl *decl)
1872 ParmVarDecl *parm;
1873 QualType T;
1875 parm = dyn_cast<ParmVarDecl>(decl);
1876 if (!parm)
1877 return decl->getType();
1879 T = parm->getOriginalType();
1880 if (!is_vla_with_static_size(T))
1881 return decl->getType();
1882 return T;
1885 extern "C" {
1886 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1887 void *user);
1888 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1889 __isl_keep pet_context *pc, void *user);
1892 /* Construct a pet_expr that holds the sizes of the array accessed
1893 * by "access".
1894 * This function is used as a callback to pet_context_add_parameters,
1895 * which is also passed a pointer to the PetScan object.
1897 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1898 void *user)
1900 PetScan *ps = (PetScan *) user;
1901 isl_id *id;
1902 ValueDecl *decl;
1903 const Type *type;
1905 id = pet_expr_access_get_id(access);
1906 decl = pet_id_get_decl(id);
1907 isl_id_free(id);
1908 type = get_array_type(decl).getTypePtr();
1909 return ps->get_array_size(type);
1912 /* Construct and return a pet_array corresponding to the variable
1913 * accessed by "access".
1914 * This function is used as a callback to pet_scop_from_pet_tree,
1915 * which is also passed a pointer to the PetScan object.
1917 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1918 __isl_keep pet_context *pc, void *user)
1920 PetScan *ps = (PetScan *) user;
1921 isl_ctx *ctx;
1922 isl_id *id;
1923 pet_array *array;
1925 ctx = pet_expr_get_ctx(access);
1926 id = pet_expr_access_get_id(access);
1927 array = ps->extract_array(id, NULL, pc);
1928 isl_id_free(id);
1930 return array;
1933 /* Extract a function summary from the body of "fd".
1935 * We extract a scop from the function body in a context with as
1936 * parameters the integer arguments of the function.
1937 * We turn off autodetection (in case it was set) to ensure that
1938 * the entire function body is considered.
1939 * We then collect the accessed array elements and attach them
1940 * to the corresponding array arguments, taking into account
1941 * that the function body may access members of array elements.
1943 * The reason for representing the integer arguments as parameters in
1944 * the context is that if we were to instead start with a context
1945 * with the function arguments as initial dimensions, then we would not
1946 * be able to refer to them from the array extents, without turning
1947 * array extents into maps.
1949 * The result is stored in the summary_cache cache so that we can reuse
1950 * it if this method gets called on the same function again later on.
1952 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
1954 isl_space *space;
1955 isl_set *domain;
1956 pet_context *pc;
1957 pet_tree *tree;
1958 pet_function_summary *summary;
1959 unsigned n;
1960 ScopLoc loc;
1961 int save_autodetect;
1962 struct pet_scop *scop;
1963 int int_size;
1964 isl_union_set *may_read, *may_write, *must_write;
1965 isl_union_map *to_inner;
1967 if (summary_cache.find(fd) != summary_cache.end())
1968 return pet_function_summary_copy(summary_cache[fd]);
1970 space = isl_space_set_alloc(ctx, 0, 0);
1972 n = fd->getNumParams();
1973 summary = pet_function_summary_alloc(ctx, n);
1974 for (int i = 0; i < n; ++i) {
1975 ParmVarDecl *parm = fd->getParamDecl(i);
1976 QualType type = parm->getType();
1977 isl_id *id;
1979 if (!type->isIntegerType())
1980 continue;
1981 id = pet_id_from_decl(ctx, parm);
1982 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
1983 space = isl_space_set_dim_id(space, isl_dim_param, 0,
1984 isl_id_copy(id));
1985 summary = pet_function_summary_set_int(summary, i, id);
1988 save_autodetect = options->autodetect;
1989 options->autodetect = 0;
1990 PetScan body_scan(PP, ast_context, loc, options,
1991 isl_union_map_copy(value_bounds), independent);
1993 tree = body_scan.extract(fd->getBody(), false);
1995 domain = isl_set_universe(space);
1996 pc = pet_context_alloc(domain);
1997 pc = pet_context_add_parameters(pc, tree,
1998 &::get_array_size, &body_scan);
1999 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2000 scop = pet_scop_from_pet_tree(tree, int_size,
2001 &::extract_array, &body_scan, pc);
2002 scop = scan_arrays(scop, pc);
2003 may_read = isl_union_map_range(pet_scop_collect_may_reads(scop));
2004 may_write = isl_union_map_range(pet_scop_collect_may_writes(scop));
2005 must_write = isl_union_map_range(pet_scop_collect_must_writes(scop));
2006 to_inner = pet_scop_compute_outer_to_inner(scop);
2007 pet_scop_free(scop);
2009 for (int i = 0; i < n; ++i) {
2010 ParmVarDecl *parm = fd->getParamDecl(i);
2011 QualType type = parm->getType();
2012 struct pet_array *array;
2013 isl_space *space;
2014 isl_union_set *data_set;
2015 isl_union_set *may_read_i, *may_write_i, *must_write_i;
2017 if (array_depth(type.getTypePtr()) == 0)
2018 continue;
2020 array = body_scan.extract_array(parm, NULL, pc);
2021 space = array ? isl_set_get_space(array->extent) : NULL;
2022 pet_array_free(array);
2023 data_set = isl_union_set_from_set(isl_set_universe(space));
2024 data_set = isl_union_set_apply(data_set,
2025 isl_union_map_copy(to_inner));
2026 may_read_i = isl_union_set_intersect(
2027 isl_union_set_copy(may_read),
2028 isl_union_set_copy(data_set));
2029 may_write_i = isl_union_set_intersect(
2030 isl_union_set_copy(may_write),
2031 isl_union_set_copy(data_set));
2032 must_write_i = isl_union_set_intersect(
2033 isl_union_set_copy(must_write), data_set);
2034 summary = pet_function_summary_set_array(summary, i,
2035 may_read_i, may_write_i, must_write_i);
2038 isl_union_set_free(may_read);
2039 isl_union_set_free(may_write);
2040 isl_union_set_free(must_write);
2041 isl_union_map_free(to_inner);
2043 options->autodetect = save_autodetect;
2044 pet_context_free(pc);
2046 summary_cache[fd] = pet_function_summary_copy(summary);
2048 return summary;
2051 /* If "fd" has a function body, then extract a function summary from
2052 * this body and attach it to the call expression "expr".
2054 * Even if a function body is available, "fd" itself may point
2055 * to a declaration without function body. We therefore first
2056 * replace it by the declaration that comes with a body (if any).
2058 * It is not clear why hasBody takes a reference to a const FunctionDecl *.
2059 * It seems that it is possible to directly use the iterators to obtain
2060 * a non-const pointer.
2061 * Since we are not going to use the pointer to modify anything anyway,
2062 * it seems safe to drop the constness. The alternative would be to
2063 * modify a lot of other functions to include const qualifiers.
2065 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
2066 FunctionDecl *fd)
2068 pet_function_summary *summary;
2069 const FunctionDecl *def;
2071 if (!expr)
2072 return NULL;
2073 if (!fd->hasBody(def))
2074 return expr;
2076 fd = const_cast<FunctionDecl *>(def);
2078 summary = get_summary(fd);
2080 expr = pet_expr_call_set_summary(expr, summary);
2082 return expr;
2085 /* Extract a pet_scop from "tree".
2087 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
2088 * then add pet_arrays for all accessed arrays.
2089 * We populate the pet_context with assignments for all parameters used
2090 * inside "tree" or any of the size expressions for the arrays accessed
2091 * by "tree" so that they can be used in affine expressions.
2093 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
2095 int int_size;
2096 isl_set *domain;
2097 pet_context *pc;
2098 pet_scop *scop;
2100 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2102 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2103 pc = pet_context_alloc(domain);
2104 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
2105 scop = pet_scop_from_pet_tree(tree, int_size,
2106 &::extract_array, this, pc);
2107 scop = scan_arrays(scop, pc);
2108 pet_context_free(pc);
2110 return scop;
2113 /* Check if the scop marked by the user is exactly this Stmt
2114 * or part of this Stmt.
2115 * If so, return a pet_scop corresponding to the marked region.
2116 * Otherwise, return NULL.
2118 struct pet_scop *PetScan::scan(Stmt *stmt)
2120 SourceManager &SM = PP.getSourceManager();
2121 unsigned start_off, end_off;
2123 start_off = getExpansionOffset(SM, stmt->getLocStart());
2124 end_off = getExpansionOffset(SM, stmt->getLocEnd());
2126 if (start_off > loc.end)
2127 return NULL;
2128 if (end_off < loc.start)
2129 return NULL;
2131 if (start_off >= loc.start && end_off <= loc.end)
2132 return extract_scop(extract(stmt));
2134 StmtIterator start;
2135 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
2136 Stmt *child = *start;
2137 if (!child)
2138 continue;
2139 start_off = getExpansionOffset(SM, child->getLocStart());
2140 end_off = getExpansionOffset(SM, child->getLocEnd());
2141 if (start_off < loc.start && end_off >= loc.end)
2142 return scan(child);
2143 if (start_off >= loc.start)
2144 break;
2147 StmtIterator end;
2148 for (end = start; end != stmt->child_end(); ++end) {
2149 Stmt *child = *end;
2150 start_off = SM.getFileOffset(child->getLocStart());
2151 if (start_off >= loc.end)
2152 break;
2155 return extract_scop(extract(StmtRange(start, end), false, false));
2158 /* Set the size of index "pos" of "array" to "size".
2159 * In particular, add a constraint of the form
2161 * i_pos < size
2163 * to array->extent and a constraint of the form
2165 * size >= 0
2167 * to array->context.
2169 * The domain of "size" is assumed to be zero-dimensional.
2171 static struct pet_array *update_size(struct pet_array *array, int pos,
2172 __isl_take isl_pw_aff *size)
2174 isl_set *valid;
2175 isl_set *univ;
2176 isl_set *bound;
2177 isl_space *dim;
2178 isl_aff *aff;
2179 isl_pw_aff *index;
2180 isl_id *id;
2182 if (!array)
2183 goto error;
2185 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2186 array->context = isl_set_intersect(array->context, valid);
2188 dim = isl_set_get_space(array->extent);
2189 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2190 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2191 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2192 index = isl_pw_aff_alloc(univ, aff);
2194 size = isl_pw_aff_add_dims(size, isl_dim_in,
2195 isl_set_dim(array->extent, isl_dim_set));
2196 id = isl_set_get_tuple_id(array->extent);
2197 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2198 bound = isl_pw_aff_lt_set(index, size);
2200 array->extent = isl_set_intersect(array->extent, bound);
2202 if (!array->context || !array->extent)
2203 return pet_array_free(array);
2205 return array;
2206 error:
2207 isl_pw_aff_free(size);
2208 return NULL;
2211 #ifdef HAVE_DECAYEDTYPE
2213 /* If "type" is a decayed type, then set *decayed to true and
2214 * return the original type.
2216 static const Type *undecay(const Type *type, bool *decayed)
2218 *decayed = isa<DecayedType>(type);
2219 if (*decayed)
2220 type = cast<DecayedType>(type)->getOriginalType().getTypePtr();
2221 return type;
2224 #else
2226 /* If "type" is a decayed type, then set *decayed to true and
2227 * return the original type.
2228 * Since this version of clang does not define a DecayedType,
2229 * we cannot obtain the original type even if it had been decayed and
2230 * we set *decayed to false.
2232 static const Type *undecay(const Type *type, bool *decayed)
2234 *decayed = false;
2235 return type;
2238 #endif
2240 /* Figure out the size of the array at position "pos" and all
2241 * subsequent positions from "type" and update the corresponding
2242 * argument of "expr" accordingly.
2244 * The initial type (when pos is zero) may be a pointer type decayed
2245 * from an array type, if this initial type is the type of a function
2246 * argument. This only happens if the original array type has
2247 * a constant size in the outer dimension as otherwise we get
2248 * a VariableArrayType. Try and obtain this original type (if available) and
2249 * take the outer array size into account if it was marked static.
2251 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2252 const Type *type, int pos)
2254 const ArrayType *atype;
2255 pet_expr *size;
2256 bool decayed = false;
2258 if (!expr)
2259 return NULL;
2261 if (pos == 0)
2262 type = undecay(type, &decayed);
2264 if (type->isPointerType()) {
2265 type = type->getPointeeType().getTypePtr();
2266 return set_upper_bounds(expr, type, pos + 1);
2268 if (!type->isArrayType())
2269 return expr;
2271 type = type->getCanonicalTypeInternal().getTypePtr();
2272 atype = cast<ArrayType>(type);
2274 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2275 type = atype->getElementType().getTypePtr();
2276 return set_upper_bounds(expr, type, pos + 1);
2279 if (type->isConstantArrayType()) {
2280 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2281 size = extract_expr(ca->getSize());
2282 expr = pet_expr_set_arg(expr, pos, size);
2283 } else if (type->isVariableArrayType()) {
2284 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2285 size = extract_expr(vla->getSizeExpr());
2286 expr = pet_expr_set_arg(expr, pos, size);
2289 type = atype->getElementType().getTypePtr();
2291 return set_upper_bounds(expr, type, pos + 1);
2294 /* Construct a pet_expr that holds the sizes of an array of the given type.
2295 * The returned expression is a call expression with as arguments
2296 * the sizes in each dimension. If we are unable to derive the size
2297 * in a given dimension, then the corresponding argument is set to infinity.
2298 * In fact, we initialize all arguments to infinity and then update
2299 * them if we are able to figure out the size.
2301 * The result is stored in the type_size cache so that we can reuse
2302 * it if this method gets called on the same type again later on.
2304 __isl_give pet_expr *PetScan::get_array_size(const Type *type)
2306 int depth;
2307 pet_expr *expr, *inf;
2309 if (type_size.find(type) != type_size.end())
2310 return pet_expr_copy(type_size[type]);
2312 depth = array_depth(type);
2313 inf = pet_expr_new_int(isl_val_infty(ctx));
2314 expr = pet_expr_new_call(ctx, "bounds", depth);
2315 for (int i = 0; i < depth; ++i)
2316 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2317 pet_expr_free(inf);
2319 expr = set_upper_bounds(expr, type, 0);
2320 type_size[type] = pet_expr_copy(expr);
2322 return expr;
2325 /* Does "expr" represent the "integer" infinity?
2327 static int is_infty(__isl_keep pet_expr *expr)
2329 isl_val *v;
2330 int res;
2332 if (pet_expr_get_type(expr) != pet_expr_int)
2333 return 0;
2334 v = pet_expr_int_get_val(expr);
2335 res = isl_val_is_infty(v);
2336 isl_val_free(v);
2338 return res;
2341 /* Figure out the dimensions of an array "array" based on its type
2342 * "type" and update "array" accordingly.
2344 * We first construct a pet_expr that holds the sizes of the array
2345 * in each dimension. The resulting expression may containing
2346 * infinity values for dimension where we are unable to derive
2347 * a size expression.
2349 * The arguments of the size expression that have a value different from
2350 * infinity are then converted to an affine expression
2351 * within the context "pc" and incorporated into the size of "array".
2352 * If we are unable to convert a size expression to an affine expression or
2353 * if the size is not a (symbolic) constant,
2354 * then we leave the corresponding size of "array" untouched.
2356 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2357 const Type *type, __isl_keep pet_context *pc)
2359 int n;
2360 pet_expr *expr;
2362 if (!array)
2363 return NULL;
2365 expr = get_array_size(type);
2367 n = pet_expr_get_n_arg(expr);
2368 for (int i = 0; i < n; ++i) {
2369 pet_expr *arg;
2370 isl_pw_aff *size;
2372 arg = pet_expr_get_arg(expr, i);
2373 if (!is_infty(arg)) {
2374 int dim;
2376 size = pet_expr_extract_affine(arg, pc);
2377 dim = isl_pw_aff_dim(size, isl_dim_in);
2378 if (!size)
2379 array = pet_array_free(array);
2380 else if (isl_pw_aff_involves_nan(size) ||
2381 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2382 isl_pw_aff_free(size);
2383 else {
2384 size = isl_pw_aff_drop_dims(size,
2385 isl_dim_in, 0, dim);
2386 array = update_size(array, i, size);
2389 pet_expr_free(arg);
2391 pet_expr_free(expr);
2393 return array;
2396 /* Does "decl" have a definition that we can keep track of in a pet_type?
2398 static bool has_printable_definition(RecordDecl *decl)
2400 if (!decl->getDeclName())
2401 return false;
2402 return decl->getLexicalDeclContext() == decl->getDeclContext();
2405 /* Construct and return a pet_array corresponding to the variable
2406 * represented by "id".
2407 * In particular, initialize array->extent to
2409 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2411 * and then call set_upper_bounds to set the upper bounds on the indices
2412 * based on the type of the variable. The upper bounds are converted
2413 * to affine expressions within the context "pc".
2415 * If the base type is that of a record with a top-level definition or
2416 * of a typedef and if "types" is not null, then the RecordDecl or
2417 * TypedefType corresponding to the type
2418 * is added to "types".
2420 * If the base type is that of a record with no top-level definition,
2421 * then we replace it by "<subfield>".
2423 struct pet_array *PetScan::extract_array(__isl_keep isl_id *id,
2424 PetTypes *types, __isl_keep pet_context *pc)
2426 struct pet_array *array;
2427 QualType qt = get_array_type(pet_id_get_decl(id));
2428 const Type *type = qt.getTypePtr();
2429 int depth = array_depth(type);
2430 QualType base = pet_clang_base_type(qt);
2431 string name;
2432 isl_space *space;
2434 array = isl_calloc_type(ctx, struct pet_array);
2435 if (!array)
2436 return NULL;
2438 space = isl_space_set_alloc(ctx, 0, depth);
2439 space = isl_space_set_tuple_id(space, isl_dim_set, isl_id_copy(id));
2441 array->extent = isl_set_nat_universe(space);
2443 space = isl_space_params_alloc(ctx, 0);
2444 array->context = isl_set_universe(space);
2446 array = set_upper_bounds(array, type, pc);
2447 if (!array)
2448 return NULL;
2450 name = base.getAsString();
2452 if (types) {
2453 if (isa<TypedefType>(base)) {
2454 types->insert(cast<TypedefType>(base)->getDecl());
2455 } else if (base->isRecordType()) {
2456 RecordDecl *decl = pet_clang_record_decl(base);
2457 TypedefNameDecl *typedecl;
2458 typedecl = decl->getTypedefNameForAnonDecl();
2459 if (typedecl)
2460 types->insert(typedecl);
2461 else if (has_printable_definition(decl))
2462 types->insert(decl);
2463 else
2464 name = "<subfield>";
2468 array->element_type = strdup(name.c_str());
2469 array->element_is_record = base->isRecordType();
2470 array->element_size = size_in_bytes(ast_context, base);
2472 return array;
2475 /* Construct and return a pet_array corresponding to the variable "decl".
2477 struct pet_array *PetScan::extract_array(ValueDecl *decl,
2478 PetTypes *types, __isl_keep pet_context *pc)
2480 isl_id *id;
2481 pet_array *array;
2483 id = pet_id_from_decl(ctx, decl);
2484 array = extract_array(id, types, pc);
2485 isl_id_free(id);
2487 return array;
2490 /* Construct and return a pet_array corresponding to the sequence
2491 * of declarations "decls".
2492 * The upper bounds of the array are converted to affine expressions
2493 * within the context "pc".
2494 * If the sequence contains a single declaration, then it corresponds
2495 * to a simple array access. Otherwise, it corresponds to a member access,
2496 * with the declaration for the substructure following that of the containing
2497 * structure in the sequence of declarations.
2498 * We start with the outermost substructure and then combine it with
2499 * information from the inner structures.
2501 * Additionally, keep track of all required types in "types".
2503 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
2504 vector<ValueDecl *> decls, PetTypes *types, __isl_keep pet_context *pc)
2506 struct pet_array *array;
2507 vector<ValueDecl *>::iterator it;
2509 it = decls.begin();
2511 array = extract_array(*it, types, pc);
2513 for (++it; it != decls.end(); ++it) {
2514 struct pet_array *parent;
2515 const char *base_name, *field_name;
2516 char *product_name;
2518 parent = array;
2519 array = extract_array(*it, types, pc);
2520 if (!array)
2521 return pet_array_free(parent);
2523 base_name = isl_set_get_tuple_name(parent->extent);
2524 field_name = isl_set_get_tuple_name(array->extent);
2525 product_name = pet_array_member_access_name(ctx,
2526 base_name, field_name);
2528 array->extent = isl_set_product(isl_set_copy(parent->extent),
2529 array->extent);
2530 if (product_name)
2531 array->extent = isl_set_set_tuple_name(array->extent,
2532 product_name);
2533 array->context = isl_set_intersect(array->context,
2534 isl_set_copy(parent->context));
2536 pet_array_free(parent);
2537 free(product_name);
2539 if (!array->extent || !array->context || !product_name)
2540 return pet_array_free(array);
2543 return array;
2546 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2547 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2548 std::set<TypeDecl *> &types_done);
2549 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2550 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2551 std::set<TypeDecl *> &types_done);
2553 /* For each of the fields of "decl" that is itself a record type
2554 * or a typedef, add a corresponding pet_type to "scop".
2556 static struct pet_scop *add_field_types(isl_ctx *ctx, struct pet_scop *scop,
2557 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2558 std::set<TypeDecl *> &types_done)
2560 RecordDecl::field_iterator it;
2562 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
2563 QualType type = it->getType();
2565 if (isa<TypedefType>(type)) {
2566 TypedefNameDecl *typedefdecl;
2568 typedefdecl = cast<TypedefType>(type)->getDecl();
2569 scop = add_type(ctx, scop, typedefdecl,
2570 PP, types, types_done);
2571 } else if (type->isRecordType()) {
2572 RecordDecl *record;
2574 record = pet_clang_record_decl(type);
2575 scop = add_type(ctx, scop, record,
2576 PP, types, types_done);
2580 return scop;
2583 /* Add a pet_type corresponding to "decl" to "scop", provided
2584 * it is a member of types.records and it has not been added before
2585 * (i.e., it is not a member of "types_done").
2587 * Since we want the user to be able to print the types
2588 * in the order in which they appear in the scop, we need to
2589 * make sure that types of fields in a structure appear before
2590 * that structure. We therefore call ourselves recursively
2591 * through add_field_types on the types of all record subfields.
2593 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2594 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2595 std::set<TypeDecl *> &types_done)
2597 string s;
2598 llvm::raw_string_ostream S(s);
2600 if (types.records.find(decl) == types.records.end())
2601 return scop;
2602 if (types_done.find(decl) != types_done.end())
2603 return scop;
2605 add_field_types(ctx, scop, decl, PP, types, types_done);
2607 if (strlen(decl->getName().str().c_str()) == 0)
2608 return scop;
2610 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2611 S.str();
2613 scop->types[scop->n_type] = pet_type_alloc(ctx,
2614 decl->getName().str().c_str(), s.c_str());
2615 if (!scop->types[scop->n_type])
2616 return pet_scop_free(scop);
2618 types_done.insert(decl);
2620 scop->n_type++;
2622 return scop;
2625 /* Add a pet_type corresponding to "decl" to "scop", provided
2626 * it is a member of types.typedefs and it has not been added before
2627 * (i.e., it is not a member of "types_done").
2629 * If the underlying type is a structure, then we print the typedef
2630 * ourselves since clang does not print the definition of the structure
2631 * in the typedef. We also make sure in this case that the types of
2632 * the fields in the structure are added first.
2634 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2635 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2636 std::set<TypeDecl *> &types_done)
2638 string s;
2639 llvm::raw_string_ostream S(s);
2640 QualType qt = decl->getUnderlyingType();
2642 if (types.typedefs.find(decl) == types.typedefs.end())
2643 return scop;
2644 if (types_done.find(decl) != types_done.end())
2645 return scop;
2647 if (qt->isRecordType()) {
2648 RecordDecl *rec = pet_clang_record_decl(qt);
2650 add_field_types(ctx, scop, rec, PP, types, types_done);
2651 S << "typedef ";
2652 rec->print(S, PrintingPolicy(PP.getLangOpts()));
2653 S << " ";
2654 S << decl->getName();
2655 } else {
2656 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2658 S.str();
2660 scop->types[scop->n_type] = pet_type_alloc(ctx,
2661 decl->getName().str().c_str(), s.c_str());
2662 if (!scop->types[scop->n_type])
2663 return pet_scop_free(scop);
2665 types_done.insert(decl);
2667 scop->n_type++;
2669 return scop;
2672 /* Construct a list of pet_arrays, one for each array (or scalar)
2673 * accessed inside "scop", add this list to "scop" and return the result.
2674 * The upper bounds of the arrays are converted to affine expressions
2675 * within the context "pc".
2677 * The context of "scop" is updated with the intersection of
2678 * the contexts of all arrays, i.e., constraints on the parameters
2679 * that ensure that the arrays have a valid (non-negative) size.
2681 * If any of the extracted arrays refers to a member access or
2682 * has a typedef'd type as base type,
2683 * then also add the required types to "scop".
2685 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
2686 __isl_keep pet_context *pc)
2688 int i, n;
2689 array_desc_set arrays;
2690 array_desc_set::iterator it;
2691 PetTypes types;
2692 std::set<TypeDecl *> types_done;
2693 std::set<clang::RecordDecl *, less_name>::iterator records_it;
2694 std::set<clang::TypedefNameDecl *, less_name>::iterator typedefs_it;
2695 int n_array;
2696 struct pet_array **scop_arrays;
2698 if (!scop)
2699 return NULL;
2701 pet_scop_collect_arrays(scop, arrays);
2702 if (arrays.size() == 0)
2703 return scop;
2705 n_array = scop->n_array;
2707 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2708 n_array + arrays.size());
2709 if (!scop_arrays)
2710 goto error;
2711 scop->arrays = scop_arrays;
2713 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
2714 struct pet_array *array;
2715 array = extract_array(ctx, *it, &types, pc);
2716 scop->arrays[n_array + i] = array;
2717 if (!scop->arrays[n_array + i])
2718 goto error;
2719 scop->n_array++;
2720 scop->context = isl_set_intersect(scop->context,
2721 isl_set_copy(array->context));
2722 if (!scop->context)
2723 goto error;
2726 n = types.records.size() + types.typedefs.size();
2727 if (n == 0)
2728 return scop;
2730 scop->types = isl_alloc_array(ctx, struct pet_type *, n);
2731 if (!scop->types)
2732 goto error;
2734 for (records_it = types.records.begin();
2735 records_it != types.records.end(); ++records_it)
2736 scop = add_type(ctx, scop, *records_it, PP, types, types_done);
2738 for (typedefs_it = types.typedefs.begin();
2739 typedefs_it != types.typedefs.end(); ++typedefs_it)
2740 scop = add_type(ctx, scop, *typedefs_it, PP, types, types_done);
2742 return scop;
2743 error:
2744 pet_scop_free(scop);
2745 return NULL;
2748 /* Bound all parameters in scop->context to the possible values
2749 * of the corresponding C variable.
2751 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
2753 int n;
2755 if (!scop)
2756 return NULL;
2758 n = isl_set_dim(scop->context, isl_dim_param);
2759 for (int i = 0; i < n; ++i) {
2760 isl_id *id;
2761 ValueDecl *decl;
2763 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
2764 if (pet_nested_in_id(id)) {
2765 isl_id_free(id);
2766 isl_die(isl_set_get_ctx(scop->context),
2767 isl_error_internal,
2768 "unresolved nested parameter", goto error);
2770 decl = pet_id_get_decl(id);
2771 isl_id_free(id);
2773 scop->context = set_parameter_bounds(scop->context, i, decl);
2775 if (!scop->context)
2776 goto error;
2779 return scop;
2780 error:
2781 pet_scop_free(scop);
2782 return NULL;
2785 /* Construct a pet_scop from the given function.
2787 * If the scop was delimited by scop and endscop pragmas, then we override
2788 * the file offsets by those derived from the pragmas.
2790 struct pet_scop *PetScan::scan(FunctionDecl *fd)
2792 pet_scop *scop;
2793 Stmt *stmt;
2795 stmt = fd->getBody();
2797 if (options->autodetect) {
2798 set_current_stmt(stmt);
2799 scop = extract_scop(extract(stmt, true));
2800 } else {
2801 current_line = loc.start_line;
2802 scop = scan(stmt);
2803 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
2805 scop = add_parameter_bounds(scop);
2806 scop = pet_scop_gist(scop, value_bounds);
2808 return scop;
2811 /* Update this->last_line and this->current_line based on the fact
2812 * that we are about to consider "stmt".
2814 void PetScan::set_current_stmt(Stmt *stmt)
2816 SourceLocation loc = stmt->getLocStart();
2817 SourceManager &SM = PP.getSourceManager();
2819 last_line = current_line;
2820 current_line = SM.getExpansionLineNumber(loc);
2823 /* Is the current statement marked by an independent pragma?
2824 * That is, is there an independent pragma on a line between
2825 * the line of the current statement and the line of the previous statement.
2826 * The search is not implemented very efficiently. We currently
2827 * assume that there are only a few independent pragmas, if any.
2829 bool PetScan::is_current_stmt_marked_independent()
2831 for (int i = 0; i < independent.size(); ++i) {
2832 unsigned line = independent[i].line;
2834 if (last_line < line && line < current_line)
2835 return true;
2838 return false;