PetScan::extract_index_expr: extract out pet_id_create_index_expr
[pet.git] / scan.cc
blobf862ff44b0c74cbe19e53a907c87a9f73514b2f7
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;
533 if (isa<EnumConstantDecl>(decl))
534 return extract_expr(cast<EnumConstantDecl>(decl));
536 id = pet_id_from_decl(ctx, decl);
537 return pet_id_create_index_expr(id);
540 /* Construct a pet_expr representing the index expression "expr"
541 * Return NULL on error.
543 * If "expr" is a reference to an enum constant, then return
544 * an integer expression instead, representing the value of the enum constant.
546 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
548 switch (expr->getStmtClass()) {
549 case Stmt::ImplicitCastExprClass:
550 return extract_index_expr(cast<ImplicitCastExpr>(expr));
551 case Stmt::DeclRefExprClass:
552 return extract_index_expr(cast<DeclRefExpr>(expr));
553 case Stmt::ArraySubscriptExprClass:
554 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
555 case Stmt::IntegerLiteralClass:
556 return extract_expr(cast<IntegerLiteral>(expr));
557 case Stmt::MemberExprClass:
558 return extract_index_expr(cast<MemberExpr>(expr));
559 default:
560 unsupported(expr);
562 return NULL;
565 /* Extract an index expression from the given array subscript expression.
567 * We first extract an index expression from the base.
568 * This will result in an index expression with a range that corresponds
569 * to the earlier indices.
570 * We then extract the current index and let
571 * pet_expr_access_subscript combine the two.
573 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
575 Expr *base = expr->getBase();
576 Expr *idx = expr->getIdx();
577 pet_expr *index;
578 pet_expr *base_expr;
580 base_expr = extract_index_expr(base);
581 index = extract_expr(idx);
583 base_expr = pet_expr_access_subscript(base_expr, index);
585 return base_expr;
588 /* Extract an index expression from a member expression.
590 * If the base access (to the structure containing the member)
591 * is of the form
593 * A[..]
595 * and the member is called "f", then the member access is of
596 * the form
598 * A_f[A[..] -> f[]]
600 * If the member access is to an anonymous struct, then simply return
602 * A[..]
604 * If the member access in the source code is of the form
606 * A->f
608 * then it is treated as
610 * A[0].f
612 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
614 Expr *base = expr->getBase();
615 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
616 pet_expr *base_index;
617 isl_id *id;
619 base_index = extract_index_expr(base);
621 if (expr->isArrow()) {
622 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
623 base_index = pet_expr_access_subscript(base_index, index);
626 if (field->isAnonymousStructOrUnion())
627 return base_index;
629 id = pet_id_from_decl(ctx, field);
631 return pet_expr_access_member(base_index, id);
634 /* Mark the given access pet_expr as a write.
636 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
638 access = pet_expr_access_set_write(access, 1);
639 access = pet_expr_access_set_read(access, 0);
641 return access;
644 /* Mark the given (read) access pet_expr as also possibly being written.
645 * That is, initialize the may write access relation from the may read relation
646 * and initialize the must write access relation to the empty relation.
648 static __isl_give pet_expr *mark_may_write(__isl_take pet_expr *expr)
650 isl_union_map *access;
651 isl_union_map *empty;
653 access = pet_expr_access_get_dependent_access(expr,
654 pet_expr_access_may_read);
655 empty = isl_union_map_empty(isl_union_map_get_space(access));
656 expr = pet_expr_access_set_access(expr, pet_expr_access_may_write,
657 access);
658 expr = pet_expr_access_set_access(expr, pet_expr_access_must_write,
659 empty);
661 return expr;
664 /* Construct a pet_expr representing a unary operator expression.
666 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
668 int type_size;
669 pet_expr *arg;
670 enum pet_op_type op;
672 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
673 if (op == pet_op_last) {
674 report_unsupported_unary_operator(expr);
675 return NULL;
678 arg = extract_expr(expr->getSubExpr());
680 if (expr->isIncrementDecrementOp() &&
681 pet_expr_get_type(arg) == pet_expr_access) {
682 arg = mark_write(arg);
683 arg = pet_expr_access_set_read(arg, 1);
686 type_size = get_type_size(expr->getType(), ast_context);
687 return pet_expr_new_unary(type_size, op, arg);
690 /* Construct a pet_expr representing a binary operator expression.
692 * If the top level operator is an assignment and the LHS is an access,
693 * then we mark that access as a write. If the operator is a compound
694 * assignment, the access is marked as both a read and a write.
696 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
698 int type_size;
699 pet_expr *lhs, *rhs;
700 enum pet_op_type op;
702 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
703 if (op == pet_op_last) {
704 unsupported(expr);
705 return NULL;
708 lhs = extract_expr(expr->getLHS());
709 rhs = extract_expr(expr->getRHS());
711 if (expr->isAssignmentOp() &&
712 pet_expr_get_type(lhs) == pet_expr_access) {
713 lhs = mark_write(lhs);
714 if (expr->isCompoundAssignmentOp())
715 lhs = pet_expr_access_set_read(lhs, 1);
718 type_size = get_type_size(expr->getType(), ast_context);
719 return pet_expr_new_binary(type_size, op, lhs, rhs);
722 /* Construct a pet_tree for a variable declaration and
723 * add the declaration to the list of declarations
724 * inside the current compound statement.
726 __isl_give pet_tree *PetScan::extract(Decl *decl)
728 VarDecl *vd;
729 pet_expr *lhs, *rhs;
730 pet_tree *tree;
732 vd = cast<VarDecl>(decl);
733 declarations.push_back(vd);
735 lhs = extract_access_expr(vd);
736 lhs = mark_write(lhs);
737 if (!vd->getInit())
738 tree = pet_tree_new_decl(lhs);
739 else {
740 rhs = extract_expr(vd->getInit());
741 tree = pet_tree_new_decl_init(lhs, rhs);
744 return tree;
747 /* Construct a pet_tree for a variable declaration statement.
748 * If the declaration statement declares multiple variables,
749 * then return a group of pet_trees, one for each declared variable.
751 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
753 pet_tree *tree;
754 unsigned n;
756 if (!stmt->isSingleDecl()) {
757 const DeclGroup &group = stmt->getDeclGroup().getDeclGroup();
758 n = group.size();
759 tree = pet_tree_new_block(ctx, 0, n);
761 for (int i = 0; i < n; ++i) {
762 pet_tree *tree_i;
763 pet_loc *loc;
765 tree_i = extract(group[i]);
766 loc = construct_pet_loc(group[i]->getSourceRange(),
767 false);
768 tree_i = pet_tree_set_loc(tree_i, loc);
769 tree = pet_tree_block_add_child(tree, tree_i);
772 return tree;
775 return extract(stmt->getSingleDecl());
778 /* Construct a pet_expr representing a conditional operation.
780 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
782 pet_expr *cond, *lhs, *rhs;
783 isl_pw_aff *pa;
785 cond = extract_expr(expr->getCond());
786 lhs = extract_expr(expr->getTrueExpr());
787 rhs = extract_expr(expr->getFalseExpr());
789 return pet_expr_new_ternary(cond, lhs, rhs);
792 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
794 return extract_expr(expr->getSubExpr());
797 /* Construct a pet_expr representing a floating point value.
799 * If the floating point literal does not appear in a macro,
800 * then we use the original representation in the source code
801 * as the string representation. Otherwise, we use the pretty
802 * printer to produce a string representation.
804 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
806 double d;
807 string s;
808 const LangOptions &LO = PP.getLangOpts();
809 SourceLocation loc = expr->getLocation();
811 if (!loc.isMacroID()) {
812 SourceManager &SM = PP.getSourceManager();
813 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
814 s = string(SM.getCharacterData(loc), len);
815 } else {
816 llvm::raw_string_ostream S(s);
817 expr->printPretty(S, 0, PrintingPolicy(LO));
818 S.str();
820 d = expr->getValueAsApproximateDouble();
821 return pet_expr_new_double(ctx, d, s.c_str());
824 /* Convert the index expression "index" into an access pet_expr of type "qt".
826 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
827 __isl_take pet_expr *index)
829 int depth;
830 int type_size;
832 depth = extract_depth(index);
833 type_size = get_type_size(qt, ast_context);
835 index = pet_expr_set_type_size(index, type_size);
836 index = pet_expr_access_set_depth(index, depth);
838 return index;
841 /* Extract an index expression from "expr" and then convert it into
842 * an access pet_expr.
844 * If "expr" is a reference to an enum constant, then return
845 * an integer expression instead, representing the value of the enum constant.
847 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
849 pet_expr *index;
851 index = extract_index_expr(expr);
853 if (pet_expr_get_type(index) == pet_expr_int)
854 return index;
856 return extract_access_expr(expr->getType(), index);
859 /* Extract an index expression from "decl" and then convert it into
860 * an access pet_expr.
862 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
864 return extract_access_expr(decl->getType(), extract_index_expr(decl));
867 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
869 return extract_expr(expr->getSubExpr());
872 /* Extract an assume statement from the argument "expr"
873 * of a __pencil_assume statement.
875 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
877 return pet_expr_new_unary(0, pet_op_assume, extract_expr(expr));
880 /* Construct a pet_expr corresponding to the function call argument "expr".
881 * The argument appears in position "pos" of a call to function "fd".
883 * If we are passing along a pointer to an array element
884 * or an entire row or even higher dimensional slice of an array,
885 * then the function being called may write into the array.
887 * We assume here that if the function is declared to take a pointer
888 * to a const type, then the function may only perform a read
889 * and that otherwise, it may either perform a read or a write (or both).
890 * We only perform this check if "detect_writes" is set.
892 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
893 Expr *expr, bool detect_writes)
895 pet_expr *res;
896 int is_addr = 0, is_partial = 0;
898 expr = pet_clang_strip_casts(expr);
899 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
900 UnaryOperator *op = cast<UnaryOperator>(expr);
901 if (op->getOpcode() == UO_AddrOf) {
902 is_addr = 1;
903 expr = op->getSubExpr();
906 res = extract_expr(expr);
907 if (!res)
908 return NULL;
909 if (array_depth(expr->getType().getTypePtr()) > 0)
910 is_partial = 1;
911 if (detect_writes && (is_addr || is_partial) &&
912 pet_expr_get_type(res) == pet_expr_access) {
913 ParmVarDecl *parm;
914 if (!fd->hasPrototype()) {
915 report_prototype_required(expr);
916 return pet_expr_free(res);
918 parm = fd->getParamDecl(pos);
919 if (!const_base(parm->getType()))
920 res = mark_may_write(res);
923 if (is_addr)
924 res = pet_expr_new_unary(0, pet_op_address_of, res);
925 return res;
928 /* Find the first FunctionDecl with the given name.
929 * "call" is the corresponding call expression and is only used
930 * for reporting errors.
932 * Return NULL on error.
934 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
936 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
937 DeclContext::decl_iterator begin = tu->decls_begin();
938 DeclContext::decl_iterator end = tu->decls_end();
939 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
940 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
941 if (!fd)
942 continue;
943 if (fd->getName().str().compare(name) != 0)
944 continue;
945 if (fd->hasBody())
946 return fd;
947 report_missing_summary_function_body(call);
948 return NULL;
950 report_missing_summary_function(call);
951 return NULL;
954 /* Return the FunctionDecl for the summary function associated to the
955 * function called by "call".
957 * In particular, if the pencil option is set, then
958 * search for an annotate attribute formatted as
959 * "pencil_access(name)", where "name" is the name of the summary function.
961 * If no summary function was specified, then return the FunctionDecl
962 * that is actually being called.
964 * Return NULL on error.
966 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
968 FunctionDecl *decl = call->getDirectCallee();
969 if (!decl)
970 return NULL;
972 if (!options->pencil)
973 return decl;
975 specific_attr_iterator<AnnotateAttr> begin, end, i;
976 begin = decl->specific_attr_begin<AnnotateAttr>();
977 end = decl->specific_attr_end<AnnotateAttr>();
978 for (i = begin; i != end; ++i) {
979 string attr = (*i)->getAnnotation().str();
981 const char prefix[] = "pencil_access(";
982 size_t start = attr.find(prefix);
983 if (start == string::npos)
984 continue;
985 start += strlen(prefix);
986 string name = attr.substr(start, attr.find(')') - start);
988 return find_decl_from_name(call, name);
991 return decl;
994 /* Construct a pet_expr representing a function call.
996 * In the special case of a "call" to __pencil_assume,
997 * construct an assume expression instead.
999 * In the case of a "call" to __pencil_kill, the arguments
1000 * are neither read nor written (only killed), so there
1001 * is no need to check for writes to these arguments.
1003 * __pencil_assume and __pencil_kill are only recognized
1004 * when the pencil option is set.
1006 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1008 pet_expr *res = NULL;
1009 FunctionDecl *fd;
1010 string name;
1011 unsigned n_arg;
1012 bool is_kill;
1014 fd = expr->getDirectCallee();
1015 if (!fd) {
1016 unsupported(expr);
1017 return NULL;
1020 name = fd->getDeclName().getAsString();
1021 n_arg = expr->getNumArgs();
1023 if (options->pencil && n_arg == 1 && name == "__pencil_assume")
1024 return extract_assume(expr->getArg(0));
1025 is_kill = options->pencil && name == "__pencil_kill";
1027 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1028 if (!res)
1029 return NULL;
1031 for (int i = 0; i < n_arg; ++i) {
1032 Expr *arg = expr->getArg(i);
1033 res = pet_expr_set_arg(res, i,
1034 PetScan::extract_argument(fd, i, arg, !is_kill));
1037 fd = get_summary_function(expr);
1038 if (!fd)
1039 return pet_expr_free(res);
1041 res = set_summary(res, fd);
1043 return res;
1046 /* Construct a pet_expr representing a (C style) cast.
1048 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1050 pet_expr *arg;
1051 QualType type;
1053 arg = extract_expr(expr->getSubExpr());
1054 if (!arg)
1055 return NULL;
1057 type = expr->getTypeAsWritten();
1058 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1061 /* Construct a pet_expr representing an integer.
1063 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1065 return pet_expr_new_int(extract_int(expr));
1068 /* Construct a pet_expr representing the integer enum constant "ecd".
1070 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
1072 isl_val *v;
1073 const llvm::APSInt &init = ecd->getInitVal();
1074 v = ::extract_int(ctx, init.isSigned(), init);
1075 return pet_expr_new_int(v);
1078 /* Try and construct a pet_expr representing "expr".
1080 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1082 switch (expr->getStmtClass()) {
1083 case Stmt::UnaryOperatorClass:
1084 return extract_expr(cast<UnaryOperator>(expr));
1085 case Stmt::CompoundAssignOperatorClass:
1086 case Stmt::BinaryOperatorClass:
1087 return extract_expr(cast<BinaryOperator>(expr));
1088 case Stmt::ImplicitCastExprClass:
1089 return extract_expr(cast<ImplicitCastExpr>(expr));
1090 case Stmt::ArraySubscriptExprClass:
1091 case Stmt::DeclRefExprClass:
1092 case Stmt::MemberExprClass:
1093 return extract_access_expr(expr);
1094 case Stmt::IntegerLiteralClass:
1095 return extract_expr(cast<IntegerLiteral>(expr));
1096 case Stmt::FloatingLiteralClass:
1097 return extract_expr(cast<FloatingLiteral>(expr));
1098 case Stmt::ParenExprClass:
1099 return extract_expr(cast<ParenExpr>(expr));
1100 case Stmt::ConditionalOperatorClass:
1101 return extract_expr(cast<ConditionalOperator>(expr));
1102 case Stmt::CallExprClass:
1103 return extract_expr(cast<CallExpr>(expr));
1104 case Stmt::CStyleCastExprClass:
1105 return extract_expr(cast<CStyleCastExpr>(expr));
1106 default:
1107 unsupported(expr);
1109 return NULL;
1112 /* Check if the given initialization statement is an assignment.
1113 * If so, return that assignment. Otherwise return NULL.
1115 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1117 BinaryOperator *ass;
1119 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1120 return NULL;
1122 ass = cast<BinaryOperator>(init);
1123 if (ass->getOpcode() != BO_Assign)
1124 return NULL;
1126 return ass;
1129 /* Check if the given initialization statement is a declaration
1130 * of a single variable.
1131 * If so, return that declaration. Otherwise return NULL.
1133 Decl *PetScan::initialization_declaration(Stmt *init)
1135 DeclStmt *decl;
1137 if (init->getStmtClass() != Stmt::DeclStmtClass)
1138 return NULL;
1140 decl = cast<DeclStmt>(init);
1142 if (!decl->isSingleDecl())
1143 return NULL;
1145 return decl->getSingleDecl();
1148 /* Given the assignment operator in the initialization of a for loop,
1149 * extract the induction variable, i.e., the (integer)variable being
1150 * assigned.
1152 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1154 Expr *lhs;
1155 DeclRefExpr *ref;
1156 ValueDecl *decl;
1157 const Type *type;
1159 lhs = init->getLHS();
1160 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1161 unsupported(init);
1162 return NULL;
1165 ref = cast<DeclRefExpr>(lhs);
1166 decl = ref->getDecl();
1167 type = decl->getType().getTypePtr();
1169 if (!type->isIntegerType()) {
1170 unsupported(lhs);
1171 return NULL;
1174 return decl;
1177 /* Given the initialization statement of a for loop and the single
1178 * declaration in this initialization statement,
1179 * extract the induction variable, i.e., the (integer) variable being
1180 * declared.
1182 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1184 VarDecl *vd;
1186 vd = cast<VarDecl>(decl);
1188 const QualType type = vd->getType();
1189 if (!type->isIntegerType()) {
1190 unsupported(init);
1191 return NULL;
1194 if (!vd->getInit()) {
1195 unsupported(init);
1196 return NULL;
1199 return vd;
1202 /* Check that op is of the form iv++ or iv--.
1203 * Return a pet_expr representing "1" or "-1" accordingly.
1205 __isl_give pet_expr *PetScan::extract_unary_increment(
1206 clang::UnaryOperator *op, clang::ValueDecl *iv)
1208 Expr *sub;
1209 DeclRefExpr *ref;
1210 isl_val *v;
1212 if (!op->isIncrementDecrementOp()) {
1213 unsupported(op);
1214 return NULL;
1217 sub = op->getSubExpr();
1218 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1219 unsupported(op);
1220 return NULL;
1223 ref = cast<DeclRefExpr>(sub);
1224 if (ref->getDecl() != iv) {
1225 unsupported(op);
1226 return NULL;
1229 if (op->isIncrementOp())
1230 v = isl_val_one(ctx);
1231 else
1232 v = isl_val_negone(ctx);
1234 return pet_expr_new_int(v);
1237 /* Check if op is of the form
1239 * iv = expr
1241 * and return the increment "expr - iv" as a pet_expr.
1243 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1244 clang::ValueDecl *iv)
1246 int type_size;
1247 Expr *lhs;
1248 DeclRefExpr *ref;
1249 pet_expr *expr, *expr_iv;
1251 if (op->getOpcode() != BO_Assign) {
1252 unsupported(op);
1253 return NULL;
1256 lhs = op->getLHS();
1257 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1258 unsupported(op);
1259 return NULL;
1262 ref = cast<DeclRefExpr>(lhs);
1263 if (ref->getDecl() != iv) {
1264 unsupported(op);
1265 return NULL;
1268 expr = extract_expr(op->getRHS());
1269 expr_iv = extract_expr(lhs);
1271 type_size = get_type_size(iv->getType(), ast_context);
1272 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1275 /* Check that op is of the form iv += cst or iv -= cst
1276 * and return a pet_expr corresponding to cst or -cst accordingly.
1278 __isl_give pet_expr *PetScan::extract_compound_increment(
1279 CompoundAssignOperator *op, clang::ValueDecl *iv)
1281 Expr *lhs;
1282 DeclRefExpr *ref;
1283 bool neg = false;
1284 pet_expr *expr;
1285 BinaryOperatorKind opcode;
1287 opcode = op->getOpcode();
1288 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1289 unsupported(op);
1290 return NULL;
1292 if (opcode == BO_SubAssign)
1293 neg = true;
1295 lhs = op->getLHS();
1296 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1297 unsupported(op);
1298 return NULL;
1301 ref = cast<DeclRefExpr>(lhs);
1302 if (ref->getDecl() != iv) {
1303 unsupported(op);
1304 return NULL;
1307 expr = extract_expr(op->getRHS());
1308 if (neg) {
1309 int type_size;
1310 type_size = get_type_size(op->getType(), ast_context);
1311 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1314 return expr;
1317 /* Check that the increment of the given for loop increments
1318 * (or decrements) the induction variable "iv" and return
1319 * the increment as a pet_expr if successful.
1321 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1322 ValueDecl *iv)
1324 Stmt *inc = stmt->getInc();
1326 if (!inc) {
1327 report_missing_increment(stmt);
1328 return NULL;
1331 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1332 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1333 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1334 return extract_compound_increment(
1335 cast<CompoundAssignOperator>(inc), iv);
1336 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1337 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1339 unsupported(inc);
1340 return NULL;
1343 /* Construct a pet_tree for a while loop.
1345 * If we were only able to extract part of the body, then simply
1346 * return that part.
1348 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1350 pet_expr *pe_cond;
1351 pet_tree *tree;
1353 tree = extract(stmt->getBody());
1354 if (partial)
1355 return tree;
1356 pe_cond = extract_expr(stmt->getCond());
1357 tree = pet_tree_new_while(pe_cond, tree);
1359 return tree;
1362 /* Construct a pet_tree for a for statement.
1363 * The for loop is required to be of one of the following forms
1365 * for (i = init; condition; ++i)
1366 * for (i = init; condition; --i)
1367 * for (i = init; condition; i += constant)
1368 * for (i = init; condition; i -= constant)
1370 * We extract a pet_tree for the body and then include it in a pet_tree
1371 * of type pet_tree_for.
1373 * As a special case, we also allow a for loop of the form
1375 * for (;;)
1377 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1379 * If we were only able to extract part of the body, then simply
1380 * return that part.
1382 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1384 BinaryOperator *ass;
1385 Decl *decl;
1386 Stmt *init;
1387 Expr *lhs, *rhs;
1388 ValueDecl *iv;
1389 pet_tree *tree;
1390 struct pet_scop *scop;
1391 int independent;
1392 int declared;
1393 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1395 independent = is_current_stmt_marked_independent();
1397 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1398 tree = extract(stmt->getBody());
1399 if (partial)
1400 return tree;
1401 tree = pet_tree_new_infinite_loop(tree);
1402 return tree;
1405 init = stmt->getInit();
1406 if (!init) {
1407 unsupported(stmt);
1408 return NULL;
1410 if ((ass = initialization_assignment(init)) != NULL) {
1411 iv = extract_induction_variable(ass);
1412 if (!iv)
1413 return NULL;
1414 lhs = ass->getLHS();
1415 rhs = ass->getRHS();
1416 } else if ((decl = initialization_declaration(init)) != NULL) {
1417 VarDecl *var = extract_induction_variable(init, decl);
1418 if (!var)
1419 return NULL;
1420 iv = var;
1421 rhs = var->getInit();
1422 lhs = create_DeclRefExpr(var);
1423 } else {
1424 unsupported(stmt->getInit());
1425 return NULL;
1428 declared = !initialization_assignment(stmt->getInit());
1429 tree = extract(stmt->getBody());
1430 if (partial)
1431 return tree;
1432 pe_iv = extract_access_expr(iv);
1433 pe_iv = mark_write(pe_iv);
1434 pe_init = extract_expr(rhs);
1435 if (!stmt->getCond())
1436 pe_cond = pet_expr_new_int(isl_val_one(ctx));
1437 else
1438 pe_cond = extract_expr(stmt->getCond());
1439 pe_inc = extract_increment(stmt, iv);
1440 tree = pet_tree_new_for(independent, declared, pe_iv, pe_init, pe_cond,
1441 pe_inc, tree);
1442 return tree;
1445 /* Try and construct a pet_tree corresponding to a compound statement.
1447 * "skip_declarations" is set if we should skip initial declarations
1448 * in the children of the compound statements.
1450 * Collect a new set of declarations for the current compound statement.
1452 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1453 bool skip_declarations)
1455 pet_tree *tree;
1456 std::vector<VarDecl *> saved_declarations;
1458 saved_declarations = declarations;
1459 declarations.clear();
1460 tree = extract(stmt->children(), true, skip_declarations);
1461 declarations = saved_declarations;
1463 return tree;
1466 /* Return the file offset of the expansion location of "Loc".
1468 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1470 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1473 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1475 /* Return a SourceLocation for the location after the first semicolon
1476 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1477 * call it and also skip trailing spaces and newline.
1479 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1480 const LangOptions &LO)
1482 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1485 #else
1487 /* Return a SourceLocation for the location after the first semicolon
1488 * after "loc". If Lexer::findLocationAfterToken is not available,
1489 * we look in the underlying character data for the first semicolon.
1491 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1492 const LangOptions &LO)
1494 const char *semi;
1495 const char *s = SM.getCharacterData(loc);
1497 semi = strchr(s, ';');
1498 if (!semi)
1499 return SourceLocation();
1500 return loc.getFileLocWithOffset(semi + 1 - s);
1503 #endif
1505 /* If the token at "loc" is the first token on the line, then return
1506 * a location referring to the start of the line and set *indent
1507 * to the indentation of "loc"
1508 * Otherwise, return "loc" and set *indent to "".
1510 * This function is used to extend a scop to the start of the line
1511 * if the first token of the scop is also the first token on the line.
1513 * We look for the first token on the line. If its location is equal to "loc",
1514 * then the latter is the location of the first token on the line.
1516 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1517 SourceManager &SM, const LangOptions &LO, char **indent)
1519 std::pair<FileID, unsigned> file_offset_pair;
1520 llvm::StringRef file;
1521 const char *pos;
1522 Token tok;
1523 SourceLocation token_loc, line_loc;
1524 int col;
1525 const char *s;
1527 loc = SM.getExpansionLoc(loc);
1528 col = SM.getExpansionColumnNumber(loc);
1529 line_loc = loc.getLocWithOffset(1 - col);
1530 file_offset_pair = SM.getDecomposedLoc(line_loc);
1531 file = SM.getBufferData(file_offset_pair.first, NULL);
1532 pos = file.data() + file_offset_pair.second;
1534 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1535 file.begin(), pos, file.end());
1536 lexer.LexFromRawLexer(tok);
1537 token_loc = tok.getLocation();
1539 s = SM.getCharacterData(line_loc);
1540 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1542 if (token_loc == loc)
1543 return line_loc;
1544 else
1545 return loc;
1548 /* Construct a pet_loc corresponding to the region covered by "range".
1549 * If "skip_semi" is set, then we assume "range" is followed by
1550 * a semicolon and also include this semicolon.
1552 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1553 bool skip_semi)
1555 SourceLocation loc = range.getBegin();
1556 SourceManager &SM = PP.getSourceManager();
1557 const LangOptions &LO = PP.getLangOpts();
1558 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1559 unsigned start, end;
1560 char *indent;
1562 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1563 start = getExpansionOffset(SM, loc);
1564 loc = range.getEnd();
1565 if (skip_semi)
1566 loc = location_after_semi(loc, SM, LO);
1567 else
1568 loc = PP.getLocForEndOfToken(loc);
1569 end = getExpansionOffset(SM, loc);
1571 return pet_loc_alloc(ctx, start, end, line, indent);
1574 /* Convert a top-level pet_expr to an expression pet_tree.
1576 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1577 SourceRange range, bool skip_semi)
1579 pet_loc *loc;
1580 pet_tree *tree;
1582 tree = pet_tree_new_expr(expr);
1583 loc = construct_pet_loc(range, skip_semi);
1584 tree = pet_tree_set_loc(tree, loc);
1586 return tree;
1589 /* Construct a pet_tree for an if statement.
1591 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1593 pet_expr *pe_cond;
1594 pet_tree *tree, *tree_else;
1595 struct pet_scop *scop;
1596 int int_size;
1598 pe_cond = extract_expr(stmt->getCond());
1599 tree = extract(stmt->getThen());
1600 if (stmt->getElse()) {
1601 tree_else = extract(stmt->getElse());
1602 if (options->autodetect) {
1603 if (tree && !tree_else) {
1604 partial = true;
1605 pet_expr_free(pe_cond);
1606 return tree;
1608 if (!tree && tree_else) {
1609 partial = true;
1610 pet_expr_free(pe_cond);
1611 return tree_else;
1614 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1615 } else
1616 tree = pet_tree_new_if(pe_cond, tree);
1617 return tree;
1620 /* Try and construct a pet_tree for a label statement.
1622 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1624 isl_id *label;
1625 pet_tree *tree;
1627 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1629 tree = extract(stmt->getSubStmt());
1630 tree = pet_tree_set_label(tree, label);
1631 return tree;
1634 /* Update the location of "tree" to include the source range of "stmt".
1636 * Actually, we create a new location based on the source range of "stmt" and
1637 * then extend this new location to include the region of the original location.
1638 * This ensures that the line number of the final location refers to "stmt".
1640 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1642 pet_loc *loc, *tree_loc;
1644 tree_loc = pet_tree_get_loc(tree);
1645 loc = construct_pet_loc(stmt->getSourceRange(), false);
1646 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1647 pet_loc_free(tree_loc);
1649 tree = pet_tree_set_loc(tree, loc);
1650 return tree;
1653 /* Try and construct a pet_tree corresponding to "stmt".
1655 * If "stmt" is a compound statement, then "skip_declarations"
1656 * indicates whether we should skip initial declarations in the
1657 * compound statement.
1659 * If the constructed pet_tree is not a (possibly) partial representation
1660 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1661 * In particular, if skip_declarations is set, then we may have skipped
1662 * declarations inside "stmt" and so the pet_scop may not represent
1663 * the entire "stmt".
1664 * Note that this function may be called with "stmt" referring to the entire
1665 * body of the function, including the outer braces. In such cases,
1666 * skip_declarations will be set and the braces will not be taken into
1667 * account in tree->loc.
1669 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
1671 pet_tree *tree;
1673 set_current_stmt(stmt);
1675 if (isa<Expr>(stmt))
1676 return extract(extract_expr(cast<Expr>(stmt)),
1677 stmt->getSourceRange(), true);
1679 switch (stmt->getStmtClass()) {
1680 case Stmt::WhileStmtClass:
1681 tree = extract(cast<WhileStmt>(stmt));
1682 break;
1683 case Stmt::ForStmtClass:
1684 tree = extract_for(cast<ForStmt>(stmt));
1685 break;
1686 case Stmt::IfStmtClass:
1687 tree = extract(cast<IfStmt>(stmt));
1688 break;
1689 case Stmt::CompoundStmtClass:
1690 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
1691 break;
1692 case Stmt::LabelStmtClass:
1693 tree = extract(cast<LabelStmt>(stmt));
1694 break;
1695 case Stmt::ContinueStmtClass:
1696 tree = pet_tree_new_continue(ctx);
1697 break;
1698 case Stmt::BreakStmtClass:
1699 tree = pet_tree_new_break(ctx);
1700 break;
1701 case Stmt::DeclStmtClass:
1702 tree = extract(cast<DeclStmt>(stmt));
1703 break;
1704 default:
1705 report_unsupported_statement_type(stmt);
1706 return NULL;
1709 if (partial || skip_declarations)
1710 return tree;
1712 return update_loc(tree, stmt);
1715 /* Given a sequence of statements "stmt_range" of which the first "n_decl"
1716 * are declarations and of which the remaining statements are represented
1717 * by "tree", try and extend "tree" to include the last sequence of
1718 * the initial declarations that can be completely extracted.
1720 * We start collecting the initial declarations and start over
1721 * whenever we come across a declaration that we cannot extract.
1722 * If we have been able to extract any declarations, then we
1723 * copy over the contents of "tree" at the end of the declarations.
1724 * Otherwise, we simply return the original "tree".
1726 __isl_give pet_tree *PetScan::insert_initial_declarations(
1727 __isl_take pet_tree *tree, int n_decl, StmtRange stmt_range)
1729 StmtIterator i;
1730 pet_tree *res;
1731 int n_stmt;
1732 int is_block;
1733 int j;
1735 n_stmt = pet_tree_block_n_child(tree);
1736 is_block = pet_tree_block_get_block(tree);
1737 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
1739 for (i = stmt_range.first; n_decl; ++i, --n_decl) {
1740 Stmt *child = *i;
1741 pet_tree *tree_i;
1743 tree_i = extract(child);
1744 if (tree_i && !partial) {
1745 res = pet_tree_block_add_child(res, tree_i);
1746 continue;
1748 pet_tree_free(tree_i);
1749 partial = false;
1750 if (pet_tree_block_n_child(res) == 0)
1751 continue;
1752 pet_tree_free(res);
1753 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
1756 if (pet_tree_block_n_child(res) == 0) {
1757 pet_tree_free(res);
1758 return tree;
1761 for (j = 0; j < n_stmt; ++j) {
1762 pet_tree *tree_i;
1764 tree_i = pet_tree_block_get_child(tree, j);
1765 res = pet_tree_block_add_child(res, tree_i);
1767 pet_tree_free(tree);
1769 return res;
1772 /* Try and construct a pet_tree corresponding to (part of)
1773 * a sequence of statements.
1775 * "block" is set if the sequence represents the children of
1776 * a compound statement.
1777 * "skip_declarations" is set if we should skip initial declarations
1778 * in the sequence of statements.
1780 * If autodetect is set, then we allow the extraction of only a subrange
1781 * of the sequence of statements. However, if there is at least one
1782 * kill and there is some subsequent statement for which we could not
1783 * construct a tree, then turn off the "block" property of the tree
1784 * such that no extra kill will be introduced at the end of the (partial)
1785 * block. If, on the other hand, the final range contains
1786 * no statements, then we discard the entire range.
1788 * If the entire range was extracted, apart from some initial declarations,
1789 * then we try and extend the range with the latest of those initial
1790 * declarations.
1792 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
1793 bool skip_declarations)
1795 StmtIterator i;
1796 int j, skip;
1797 bool has_kills = false;
1798 bool partial_range = false;
1799 pet_tree *tree;
1801 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
1804 tree = pet_tree_new_block(ctx, block, j);
1806 skip = 0;
1807 i = stmt_range.first;
1808 if (skip_declarations)
1809 for (; i != stmt_range.second; ++i) {
1810 if ((*i)->getStmtClass() != Stmt::DeclStmtClass)
1811 break;
1812 ++skip;
1815 for (; i != stmt_range.second; ++i) {
1816 Stmt *child = *i;
1817 pet_tree *tree_i;
1819 tree_i = extract(child);
1820 if (pet_tree_block_n_child(tree) != 0 && partial) {
1821 pet_tree_free(tree_i);
1822 break;
1824 if (tree_i && child->getStmtClass() == Stmt::DeclStmtClass &&
1825 block)
1826 has_kills = true;
1827 if (options->autodetect) {
1828 if (tree_i)
1829 tree = pet_tree_block_add_child(tree, tree_i);
1830 else
1831 partial_range = true;
1832 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
1833 partial = true;
1834 } else {
1835 tree = pet_tree_block_add_child(tree, tree_i);
1838 if (partial || !tree)
1839 break;
1842 if (!tree)
1843 return NULL;
1845 if (partial) {
1846 if (has_kills)
1847 tree = pet_tree_block_set_block(tree, 0);
1848 } else if (partial_range) {
1849 if (pet_tree_block_n_child(tree) == 0) {
1850 pet_tree_free(tree);
1851 return NULL;
1853 partial = true;
1854 } else if (skip > 0)
1855 tree = insert_initial_declarations(tree, skip, stmt_range);
1857 return tree;
1860 /* Is "T" the type of a variable length array with static size?
1862 static bool is_vla_with_static_size(QualType T)
1864 const VariableArrayType *vlatype;
1866 if (!T->isVariableArrayType())
1867 return false;
1868 vlatype = cast<VariableArrayType>(T);
1869 return vlatype->getSizeModifier() == VariableArrayType::Static;
1872 /* Return the type of "decl" as an array.
1874 * In particular, if "decl" is a parameter declaration that
1875 * is a variable length array with a static size, then
1876 * return the original type (i.e., the variable length array).
1877 * Otherwise, return the type of decl.
1879 static QualType get_array_type(ValueDecl *decl)
1881 ParmVarDecl *parm;
1882 QualType T;
1884 parm = dyn_cast<ParmVarDecl>(decl);
1885 if (!parm)
1886 return decl->getType();
1888 T = parm->getOriginalType();
1889 if (!is_vla_with_static_size(T))
1890 return decl->getType();
1891 return T;
1894 extern "C" {
1895 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1896 void *user);
1897 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1898 __isl_keep pet_context *pc, void *user);
1901 /* Construct a pet_expr that holds the sizes of the array accessed
1902 * by "access".
1903 * This function is used as a callback to pet_context_add_parameters,
1904 * which is also passed a pointer to the PetScan object.
1906 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
1907 void *user)
1909 PetScan *ps = (PetScan *) user;
1910 isl_id *id;
1911 ValueDecl *decl;
1912 const Type *type;
1914 id = pet_expr_access_get_id(access);
1915 decl = pet_id_get_decl(id);
1916 isl_id_free(id);
1917 type = get_array_type(decl).getTypePtr();
1918 return ps->get_array_size(type);
1921 /* Construct and return a pet_array corresponding to the variable
1922 * accessed by "access".
1923 * This function is used as a callback to pet_scop_from_pet_tree,
1924 * which is also passed a pointer to the PetScan object.
1926 static struct pet_array *extract_array(__isl_keep pet_expr *access,
1927 __isl_keep pet_context *pc, void *user)
1929 PetScan *ps = (PetScan *) user;
1930 isl_ctx *ctx;
1931 isl_id *id;
1932 pet_array *array;
1934 ctx = pet_expr_get_ctx(access);
1935 id = pet_expr_access_get_id(access);
1936 array = ps->extract_array(id, NULL, pc);
1937 isl_id_free(id);
1939 return array;
1942 /* Extract a function summary from the body of "fd".
1944 * We extract a scop from the function body in a context with as
1945 * parameters the integer arguments of the function.
1946 * We turn off autodetection (in case it was set) to ensure that
1947 * the entire function body is considered.
1948 * We then collect the accessed array elements and attach them
1949 * to the corresponding array arguments, taking into account
1950 * that the function body may access members of array elements.
1952 * The reason for representing the integer arguments as parameters in
1953 * the context is that if we were to instead start with a context
1954 * with the function arguments as initial dimensions, then we would not
1955 * be able to refer to them from the array extents, without turning
1956 * array extents into maps.
1958 * The result is stored in the summary_cache cache so that we can reuse
1959 * it if this method gets called on the same function again later on.
1961 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
1963 isl_space *space;
1964 isl_set *domain;
1965 pet_context *pc;
1966 pet_tree *tree;
1967 pet_function_summary *summary;
1968 unsigned n;
1969 ScopLoc loc;
1970 int save_autodetect;
1971 struct pet_scop *scop;
1972 int int_size;
1973 isl_union_set *may_read, *may_write, *must_write;
1974 isl_union_map *to_inner;
1976 if (summary_cache.find(fd) != summary_cache.end())
1977 return pet_function_summary_copy(summary_cache[fd]);
1979 space = isl_space_set_alloc(ctx, 0, 0);
1981 n = fd->getNumParams();
1982 summary = pet_function_summary_alloc(ctx, n);
1983 for (int i = 0; i < n; ++i) {
1984 ParmVarDecl *parm = fd->getParamDecl(i);
1985 QualType type = parm->getType();
1986 isl_id *id;
1988 if (!type->isIntegerType())
1989 continue;
1990 id = pet_id_from_decl(ctx, parm);
1991 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
1992 space = isl_space_set_dim_id(space, isl_dim_param, 0,
1993 isl_id_copy(id));
1994 summary = pet_function_summary_set_int(summary, i, id);
1997 save_autodetect = options->autodetect;
1998 options->autodetect = 0;
1999 PetScan body_scan(PP, ast_context, fd, loc, options,
2000 isl_union_map_copy(value_bounds), independent);
2002 tree = body_scan.extract(fd->getBody(), false);
2004 domain = isl_set_universe(space);
2005 pc = pet_context_alloc(domain);
2006 pc = pet_context_add_parameters(pc, tree,
2007 &::get_array_size, &body_scan);
2008 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2009 scop = pet_scop_from_pet_tree(tree, int_size,
2010 &::extract_array, &body_scan, pc);
2011 scop = scan_arrays(scop, pc);
2012 may_read = isl_union_map_range(pet_scop_collect_may_reads(scop));
2013 may_write = isl_union_map_range(pet_scop_collect_may_writes(scop));
2014 must_write = isl_union_map_range(pet_scop_collect_must_writes(scop));
2015 to_inner = pet_scop_compute_outer_to_inner(scop);
2016 pet_scop_free(scop);
2018 for (int i = 0; i < n; ++i) {
2019 ParmVarDecl *parm = fd->getParamDecl(i);
2020 QualType type = parm->getType();
2021 struct pet_array *array;
2022 isl_space *space;
2023 isl_union_set *data_set;
2024 isl_union_set *may_read_i, *may_write_i, *must_write_i;
2026 if (array_depth(type.getTypePtr()) == 0)
2027 continue;
2029 array = body_scan.extract_array(parm, NULL, pc);
2030 space = array ? isl_set_get_space(array->extent) : NULL;
2031 pet_array_free(array);
2032 data_set = isl_union_set_from_set(isl_set_universe(space));
2033 data_set = isl_union_set_apply(data_set,
2034 isl_union_map_copy(to_inner));
2035 may_read_i = isl_union_set_intersect(
2036 isl_union_set_copy(may_read),
2037 isl_union_set_copy(data_set));
2038 may_write_i = isl_union_set_intersect(
2039 isl_union_set_copy(may_write),
2040 isl_union_set_copy(data_set));
2041 must_write_i = isl_union_set_intersect(
2042 isl_union_set_copy(must_write), data_set);
2043 summary = pet_function_summary_set_array(summary, i,
2044 may_read_i, may_write_i, must_write_i);
2047 isl_union_set_free(may_read);
2048 isl_union_set_free(may_write);
2049 isl_union_set_free(must_write);
2050 isl_union_map_free(to_inner);
2052 options->autodetect = save_autodetect;
2053 pet_context_free(pc);
2055 summary_cache[fd] = pet_function_summary_copy(summary);
2057 return summary;
2060 /* If "fd" has a function body, then extract a function summary from
2061 * this body and attach it to the call expression "expr".
2063 * Even if a function body is available, "fd" itself may point
2064 * to a declaration without function body. We therefore first
2065 * replace it by the declaration that comes with a body (if any).
2067 * It is not clear why hasBody takes a reference to a const FunctionDecl *.
2068 * It seems that it is possible to directly use the iterators to obtain
2069 * a non-const pointer.
2070 * Since we are not going to use the pointer to modify anything anyway,
2071 * it seems safe to drop the constness. The alternative would be to
2072 * modify a lot of other functions to include const qualifiers.
2074 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
2075 FunctionDecl *fd)
2077 pet_function_summary *summary;
2078 const FunctionDecl *def;
2080 if (!expr)
2081 return NULL;
2082 if (!fd->hasBody(def))
2083 return expr;
2085 fd = const_cast<FunctionDecl *>(def);
2087 summary = get_summary(fd);
2089 expr = pet_expr_call_set_summary(expr, summary);
2091 return expr;
2094 /* Extract a pet_scop from "tree".
2096 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
2097 * then add pet_arrays for all accessed arrays.
2098 * We populate the pet_context with assignments for all parameters used
2099 * inside "tree" or any of the size expressions for the arrays accessed
2100 * by "tree" so that they can be used in affine expressions.
2102 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
2104 int int_size;
2105 isl_set *domain;
2106 pet_context *pc;
2107 pet_scop *scop;
2109 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2111 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2112 pc = pet_context_alloc(domain);
2113 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
2114 scop = pet_scop_from_pet_tree(tree, int_size,
2115 &::extract_array, this, pc);
2116 scop = scan_arrays(scop, pc);
2117 pet_context_free(pc);
2119 return scop;
2122 /* Check if the scop marked by the user is exactly this Stmt
2123 * or part of this Stmt.
2124 * If so, return a pet_scop corresponding to the marked region.
2125 * Otherwise, return NULL.
2127 struct pet_scop *PetScan::scan(Stmt *stmt)
2129 SourceManager &SM = PP.getSourceManager();
2130 unsigned start_off, end_off;
2132 start_off = getExpansionOffset(SM, stmt->getLocStart());
2133 end_off = getExpansionOffset(SM, stmt->getLocEnd());
2135 if (start_off > loc.end)
2136 return NULL;
2137 if (end_off < loc.start)
2138 return NULL;
2140 if (start_off >= loc.start && end_off <= loc.end)
2141 return extract_scop(extract(stmt));
2143 StmtIterator start;
2144 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
2145 Stmt *child = *start;
2146 if (!child)
2147 continue;
2148 start_off = getExpansionOffset(SM, child->getLocStart());
2149 end_off = getExpansionOffset(SM, child->getLocEnd());
2150 if (start_off < loc.start && end_off >= loc.end)
2151 return scan(child);
2152 if (start_off >= loc.start)
2153 break;
2156 StmtIterator end;
2157 for (end = start; end != stmt->child_end(); ++end) {
2158 Stmt *child = *end;
2159 start_off = SM.getFileOffset(child->getLocStart());
2160 if (start_off >= loc.end)
2161 break;
2164 return extract_scop(extract(StmtRange(start, end), false, false));
2167 /* Set the size of index "pos" of "array" to "size".
2168 * In particular, add a constraint of the form
2170 * i_pos < size
2172 * to array->extent and a constraint of the form
2174 * size >= 0
2176 * to array->context.
2178 * The domain of "size" is assumed to be zero-dimensional.
2180 static struct pet_array *update_size(struct pet_array *array, int pos,
2181 __isl_take isl_pw_aff *size)
2183 isl_set *valid;
2184 isl_set *univ;
2185 isl_set *bound;
2186 isl_space *dim;
2187 isl_aff *aff;
2188 isl_pw_aff *index;
2189 isl_id *id;
2191 if (!array)
2192 goto error;
2194 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2195 array->context = isl_set_intersect(array->context, valid);
2197 dim = isl_set_get_space(array->extent);
2198 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2199 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2200 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2201 index = isl_pw_aff_alloc(univ, aff);
2203 size = isl_pw_aff_add_dims(size, isl_dim_in,
2204 isl_set_dim(array->extent, isl_dim_set));
2205 id = isl_set_get_tuple_id(array->extent);
2206 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2207 bound = isl_pw_aff_lt_set(index, size);
2209 array->extent = isl_set_intersect(array->extent, bound);
2211 if (!array->context || !array->extent)
2212 return pet_array_free(array);
2214 return array;
2215 error:
2216 isl_pw_aff_free(size);
2217 return NULL;
2220 #ifdef HAVE_DECAYEDTYPE
2222 /* If "type" is a decayed type, then set *decayed to true and
2223 * return the original type.
2225 static const Type *undecay(const Type *type, bool *decayed)
2227 *decayed = isa<DecayedType>(type);
2228 if (*decayed)
2229 type = cast<DecayedType>(type)->getOriginalType().getTypePtr();
2230 return type;
2233 #else
2235 /* If "type" is a decayed type, then set *decayed to true and
2236 * return the original type.
2237 * Since this version of clang does not define a DecayedType,
2238 * we cannot obtain the original type even if it had been decayed and
2239 * we set *decayed to false.
2241 static const Type *undecay(const Type *type, bool *decayed)
2243 *decayed = false;
2244 return type;
2247 #endif
2249 /* Figure out the size of the array at position "pos" and all
2250 * subsequent positions from "type" and update the corresponding
2251 * argument of "expr" accordingly.
2253 * The initial type (when pos is zero) may be a pointer type decayed
2254 * from an array type, if this initial type is the type of a function
2255 * argument. This only happens if the original array type has
2256 * a constant size in the outer dimension as otherwise we get
2257 * a VariableArrayType. Try and obtain this original type (if available) and
2258 * take the outer array size into account if it was marked static.
2260 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2261 const Type *type, int pos)
2263 const ArrayType *atype;
2264 pet_expr *size;
2265 bool decayed = false;
2267 if (!expr)
2268 return NULL;
2270 if (pos == 0)
2271 type = undecay(type, &decayed);
2273 if (type->isPointerType()) {
2274 type = type->getPointeeType().getTypePtr();
2275 return set_upper_bounds(expr, type, pos + 1);
2277 if (!type->isArrayType())
2278 return expr;
2280 type = type->getCanonicalTypeInternal().getTypePtr();
2281 atype = cast<ArrayType>(type);
2283 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2284 type = atype->getElementType().getTypePtr();
2285 return set_upper_bounds(expr, type, pos + 1);
2288 if (type->isConstantArrayType()) {
2289 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2290 size = extract_expr(ca->getSize());
2291 expr = pet_expr_set_arg(expr, pos, size);
2292 } else if (type->isVariableArrayType()) {
2293 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2294 size = extract_expr(vla->getSizeExpr());
2295 expr = pet_expr_set_arg(expr, pos, size);
2298 type = atype->getElementType().getTypePtr();
2300 return set_upper_bounds(expr, type, pos + 1);
2303 /* Construct a pet_expr that holds the sizes of an array of the given type.
2304 * The returned expression is a call expression with as arguments
2305 * the sizes in each dimension. If we are unable to derive the size
2306 * in a given dimension, then the corresponding argument is set to infinity.
2307 * In fact, we initialize all arguments to infinity and then update
2308 * them if we are able to figure out the size.
2310 * The result is stored in the type_size cache so that we can reuse
2311 * it if this method gets called on the same type again later on.
2313 __isl_give pet_expr *PetScan::get_array_size(const Type *type)
2315 int depth;
2316 pet_expr *expr, *inf;
2318 if (type_size.find(type) != type_size.end())
2319 return pet_expr_copy(type_size[type]);
2321 depth = array_depth(type);
2322 inf = pet_expr_new_int(isl_val_infty(ctx));
2323 expr = pet_expr_new_call(ctx, "bounds", depth);
2324 for (int i = 0; i < depth; ++i)
2325 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2326 pet_expr_free(inf);
2328 expr = set_upper_bounds(expr, type, 0);
2329 type_size[type] = pet_expr_copy(expr);
2331 return expr;
2334 /* Does "expr" represent the "integer" infinity?
2336 static int is_infty(__isl_keep pet_expr *expr)
2338 isl_val *v;
2339 int res;
2341 if (pet_expr_get_type(expr) != pet_expr_int)
2342 return 0;
2343 v = pet_expr_int_get_val(expr);
2344 res = isl_val_is_infty(v);
2345 isl_val_free(v);
2347 return res;
2350 /* Figure out the dimensions of an array "array" based on its type
2351 * "type" and update "array" accordingly.
2353 * We first construct a pet_expr that holds the sizes of the array
2354 * in each dimension. The resulting expression may containing
2355 * infinity values for dimension where we are unable to derive
2356 * a size expression.
2358 * The arguments of the size expression that have a value different from
2359 * infinity are then converted to an affine expression
2360 * within the context "pc" and incorporated into the size of "array".
2361 * If we are unable to convert a size expression to an affine expression or
2362 * if the size is not a (symbolic) constant,
2363 * then we leave the corresponding size of "array" untouched.
2365 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2366 const Type *type, __isl_keep pet_context *pc)
2368 int n;
2369 pet_expr *expr;
2371 if (!array)
2372 return NULL;
2374 expr = get_array_size(type);
2376 n = pet_expr_get_n_arg(expr);
2377 for (int i = 0; i < n; ++i) {
2378 pet_expr *arg;
2379 isl_pw_aff *size;
2381 arg = pet_expr_get_arg(expr, i);
2382 if (!is_infty(arg)) {
2383 int dim;
2385 size = pet_expr_extract_affine(arg, pc);
2386 dim = isl_pw_aff_dim(size, isl_dim_in);
2387 if (!size)
2388 array = pet_array_free(array);
2389 else if (isl_pw_aff_involves_nan(size) ||
2390 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2391 isl_pw_aff_free(size);
2392 else {
2393 size = isl_pw_aff_drop_dims(size,
2394 isl_dim_in, 0, dim);
2395 array = update_size(array, i, size);
2398 pet_expr_free(arg);
2400 pet_expr_free(expr);
2402 return array;
2405 /* Does "decl" have a definition that we can keep track of in a pet_type?
2407 static bool has_printable_definition(RecordDecl *decl)
2409 if (!decl->getDeclName())
2410 return false;
2411 return decl->getLexicalDeclContext() == decl->getDeclContext();
2414 /* Construct and return a pet_array corresponding to the variable
2415 * represented by "id".
2416 * In particular, initialize array->extent to
2418 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2420 * and then call set_upper_bounds to set the upper bounds on the indices
2421 * based on the type of the variable. The upper bounds are converted
2422 * to affine expressions within the context "pc".
2424 * If the base type is that of a record with a top-level definition or
2425 * of a typedef and if "types" is not null, then the RecordDecl or
2426 * TypedefType corresponding to the type
2427 * is added to "types".
2429 * If the base type is that of a record with no top-level definition,
2430 * then we replace it by "<subfield>".
2432 struct pet_array *PetScan::extract_array(__isl_keep isl_id *id,
2433 PetTypes *types, __isl_keep pet_context *pc)
2435 struct pet_array *array;
2436 QualType qt = get_array_type(pet_id_get_decl(id));
2437 const Type *type = qt.getTypePtr();
2438 int depth = array_depth(type);
2439 QualType base = pet_clang_base_type(qt);
2440 string name;
2441 isl_space *space;
2443 array = isl_calloc_type(ctx, struct pet_array);
2444 if (!array)
2445 return NULL;
2447 space = isl_space_set_alloc(ctx, 0, depth);
2448 space = isl_space_set_tuple_id(space, isl_dim_set, isl_id_copy(id));
2450 array->extent = isl_set_nat_universe(space);
2452 space = isl_space_params_alloc(ctx, 0);
2453 array->context = isl_set_universe(space);
2455 array = set_upper_bounds(array, type, pc);
2456 if (!array)
2457 return NULL;
2459 name = base.getAsString();
2461 if (types) {
2462 if (isa<TypedefType>(base)) {
2463 types->insert(cast<TypedefType>(base)->getDecl());
2464 } else if (base->isRecordType()) {
2465 RecordDecl *decl = pet_clang_record_decl(base);
2466 TypedefNameDecl *typedecl;
2467 typedecl = decl->getTypedefNameForAnonDecl();
2468 if (typedecl)
2469 types->insert(typedecl);
2470 else if (has_printable_definition(decl))
2471 types->insert(decl);
2472 else
2473 name = "<subfield>";
2477 array->element_type = strdup(name.c_str());
2478 array->element_is_record = base->isRecordType();
2479 array->element_size = size_in_bytes(ast_context, base);
2481 return array;
2484 /* Construct and return a pet_array corresponding to the variable "decl".
2486 struct pet_array *PetScan::extract_array(ValueDecl *decl,
2487 PetTypes *types, __isl_keep pet_context *pc)
2489 isl_id *id;
2490 pet_array *array;
2492 id = pet_id_from_decl(ctx, decl);
2493 array = extract_array(id, types, pc);
2494 isl_id_free(id);
2496 return array;
2499 /* Construct and return a pet_array corresponding to the sequence
2500 * of declarations "decls".
2501 * The upper bounds of the array are converted to affine expressions
2502 * within the context "pc".
2503 * If the sequence contains a single declaration, then it corresponds
2504 * to a simple array access. Otherwise, it corresponds to a member access,
2505 * with the declaration for the substructure following that of the containing
2506 * structure in the sequence of declarations.
2507 * We start with the outermost substructure and then combine it with
2508 * information from the inner structures.
2510 * Additionally, keep track of all required types in "types".
2512 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
2513 vector<ValueDecl *> decls, PetTypes *types, __isl_keep pet_context *pc)
2515 struct pet_array *array;
2516 vector<ValueDecl *>::iterator it;
2518 it = decls.begin();
2520 array = extract_array(*it, types, pc);
2522 for (++it; it != decls.end(); ++it) {
2523 struct pet_array *parent;
2524 const char *base_name, *field_name;
2525 char *product_name;
2527 parent = array;
2528 array = extract_array(*it, types, pc);
2529 if (!array)
2530 return pet_array_free(parent);
2532 base_name = isl_set_get_tuple_name(parent->extent);
2533 field_name = isl_set_get_tuple_name(array->extent);
2534 product_name = pet_array_member_access_name(ctx,
2535 base_name, field_name);
2537 array->extent = isl_set_product(isl_set_copy(parent->extent),
2538 array->extent);
2539 if (product_name)
2540 array->extent = isl_set_set_tuple_name(array->extent,
2541 product_name);
2542 array->context = isl_set_intersect(array->context,
2543 isl_set_copy(parent->context));
2545 pet_array_free(parent);
2546 free(product_name);
2548 if (!array->extent || !array->context || !product_name)
2549 return pet_array_free(array);
2552 return array;
2555 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2556 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2557 std::set<TypeDecl *> &types_done);
2558 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2559 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2560 std::set<TypeDecl *> &types_done);
2562 /* For each of the fields of "decl" that is itself a record type
2563 * or a typedef, add a corresponding pet_type to "scop".
2565 static struct pet_scop *add_field_types(isl_ctx *ctx, struct pet_scop *scop,
2566 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2567 std::set<TypeDecl *> &types_done)
2569 RecordDecl::field_iterator it;
2571 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
2572 QualType type = it->getType();
2574 if (isa<TypedefType>(type)) {
2575 TypedefNameDecl *typedefdecl;
2577 typedefdecl = cast<TypedefType>(type)->getDecl();
2578 scop = add_type(ctx, scop, typedefdecl,
2579 PP, types, types_done);
2580 } else if (type->isRecordType()) {
2581 RecordDecl *record;
2583 record = pet_clang_record_decl(type);
2584 scop = add_type(ctx, scop, record,
2585 PP, types, types_done);
2589 return scop;
2592 /* Add a pet_type corresponding to "decl" to "scop", provided
2593 * it is a member of types.records and it has not been added before
2594 * (i.e., it is not a member of "types_done").
2596 * Since we want the user to be able to print the types
2597 * in the order in which they appear in the scop, we need to
2598 * make sure that types of fields in a structure appear before
2599 * that structure. We therefore call ourselves recursively
2600 * through add_field_types on the types of all record subfields.
2602 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2603 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
2604 std::set<TypeDecl *> &types_done)
2606 string s;
2607 llvm::raw_string_ostream S(s);
2609 if (types.records.find(decl) == types.records.end())
2610 return scop;
2611 if (types_done.find(decl) != types_done.end())
2612 return scop;
2614 add_field_types(ctx, scop, decl, PP, types, types_done);
2616 if (strlen(decl->getName().str().c_str()) == 0)
2617 return scop;
2619 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2620 S.str();
2622 scop->types[scop->n_type] = pet_type_alloc(ctx,
2623 decl->getName().str().c_str(), s.c_str());
2624 if (!scop->types[scop->n_type])
2625 return pet_scop_free(scop);
2627 types_done.insert(decl);
2629 scop->n_type++;
2631 return scop;
2634 /* Add a pet_type corresponding to "decl" to "scop", provided
2635 * it is a member of types.typedefs and it has not been added before
2636 * (i.e., it is not a member of "types_done").
2638 * If the underlying type is a structure, then we print the typedef
2639 * ourselves since clang does not print the definition of the structure
2640 * in the typedef. We also make sure in this case that the types of
2641 * the fields in the structure are added first.
2643 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
2644 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
2645 std::set<TypeDecl *> &types_done)
2647 string s;
2648 llvm::raw_string_ostream S(s);
2649 QualType qt = decl->getUnderlyingType();
2651 if (types.typedefs.find(decl) == types.typedefs.end())
2652 return scop;
2653 if (types_done.find(decl) != types_done.end())
2654 return scop;
2656 if (qt->isRecordType()) {
2657 RecordDecl *rec = pet_clang_record_decl(qt);
2659 add_field_types(ctx, scop, rec, PP, types, types_done);
2660 S << "typedef ";
2661 rec->print(S, PrintingPolicy(PP.getLangOpts()));
2662 S << " ";
2663 S << decl->getName();
2664 } else {
2665 decl->print(S, PrintingPolicy(PP.getLangOpts()));
2667 S.str();
2669 scop->types[scop->n_type] = pet_type_alloc(ctx,
2670 decl->getName().str().c_str(), s.c_str());
2671 if (!scop->types[scop->n_type])
2672 return pet_scop_free(scop);
2674 types_done.insert(decl);
2676 scop->n_type++;
2678 return scop;
2681 /* Construct a list of pet_arrays, one for each array (or scalar)
2682 * accessed inside "scop", add this list to "scop" and return the result.
2683 * The upper bounds of the arrays are converted to affine expressions
2684 * within the context "pc".
2686 * The context of "scop" is updated with the intersection of
2687 * the contexts of all arrays, i.e., constraints on the parameters
2688 * that ensure that the arrays have a valid (non-negative) size.
2690 * If any of the extracted arrays refers to a member access or
2691 * has a typedef'd type as base type,
2692 * then also add the required types to "scop".
2694 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
2695 __isl_keep pet_context *pc)
2697 int i, n;
2698 array_desc_set arrays;
2699 array_desc_set::iterator it;
2700 PetTypes types;
2701 std::set<TypeDecl *> types_done;
2702 std::set<clang::RecordDecl *, less_name>::iterator records_it;
2703 std::set<clang::TypedefNameDecl *, less_name>::iterator typedefs_it;
2704 int n_array;
2705 struct pet_array **scop_arrays;
2707 if (!scop)
2708 return NULL;
2710 pet_scop_collect_arrays(scop, arrays);
2711 if (arrays.size() == 0)
2712 return scop;
2714 n_array = scop->n_array;
2716 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2717 n_array + arrays.size());
2718 if (!scop_arrays)
2719 goto error;
2720 scop->arrays = scop_arrays;
2722 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
2723 struct pet_array *array;
2724 array = extract_array(ctx, *it, &types, pc);
2725 scop->arrays[n_array + i] = array;
2726 if (!scop->arrays[n_array + i])
2727 goto error;
2728 scop->n_array++;
2729 scop->context = isl_set_intersect(scop->context,
2730 isl_set_copy(array->context));
2731 if (!scop->context)
2732 goto error;
2735 n = types.records.size() + types.typedefs.size();
2736 if (n == 0)
2737 return scop;
2739 scop->types = isl_alloc_array(ctx, struct pet_type *, n);
2740 if (!scop->types)
2741 goto error;
2743 for (records_it = types.records.begin();
2744 records_it != types.records.end(); ++records_it)
2745 scop = add_type(ctx, scop, *records_it, PP, types, types_done);
2747 for (typedefs_it = types.typedefs.begin();
2748 typedefs_it != types.typedefs.end(); ++typedefs_it)
2749 scop = add_type(ctx, scop, *typedefs_it, PP, types, types_done);
2751 return scop;
2752 error:
2753 pet_scop_free(scop);
2754 return NULL;
2757 /* Bound all parameters in scop->context to the possible values
2758 * of the corresponding C variable.
2760 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
2762 int n;
2764 if (!scop)
2765 return NULL;
2767 n = isl_set_dim(scop->context, isl_dim_param);
2768 for (int i = 0; i < n; ++i) {
2769 isl_id *id;
2770 ValueDecl *decl;
2772 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
2773 if (pet_nested_in_id(id)) {
2774 isl_id_free(id);
2775 isl_die(isl_set_get_ctx(scop->context),
2776 isl_error_internal,
2777 "unresolved nested parameter", goto error);
2779 decl = pet_id_get_decl(id);
2780 isl_id_free(id);
2782 scop->context = set_parameter_bounds(scop->context, i, decl);
2784 if (!scop->context)
2785 goto error;
2788 return scop;
2789 error:
2790 pet_scop_free(scop);
2791 return NULL;
2794 /* Construct a pet_scop from the given function.
2796 * If the scop was delimited by scop and endscop pragmas, then we override
2797 * the file offsets by those derived from the pragmas.
2799 struct pet_scop *PetScan::scan(FunctionDecl *fd)
2801 pet_scop *scop;
2802 Stmt *stmt;
2804 stmt = fd->getBody();
2806 if (options->autodetect) {
2807 set_current_stmt(stmt);
2808 scop = extract_scop(extract(stmt, true));
2809 } else {
2810 current_line = loc.start_line;
2811 scop = scan(stmt);
2812 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
2814 scop = add_parameter_bounds(scop);
2815 scop = pet_scop_gist(scop, value_bounds);
2817 return scop;
2820 /* Update this->last_line and this->current_line based on the fact
2821 * that we are about to consider "stmt".
2823 void PetScan::set_current_stmt(Stmt *stmt)
2825 SourceLocation loc = stmt->getLocStart();
2826 SourceManager &SM = PP.getSourceManager();
2828 last_line = current_line;
2829 current_line = SM.getExpansionLineNumber(loc);
2832 /* Is the current statement marked by an independent pragma?
2833 * That is, is there an independent pragma on a line between
2834 * the line of the current statement and the line of the previous statement.
2835 * The search is not implemented very efficiently. We currently
2836 * assume that there are only a few independent pragmas, if any.
2838 bool PetScan::is_current_stmt_marked_independent()
2840 for (int i = 0; i < independent.size(); ++i) {
2841 unsigned line = independent[i].line;
2843 if (last_line < line && line < current_line)
2844 return true;
2847 return false;