allow return statements in summary functions
[pet.git] / scan.cc
blobc4451fc72fcfb43345695ecce76a27accc1e78a0
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2015 Ecole Normale Superieure. All rights reserved.
4 * Copyright 2015-2017 Sven Verdoolaege. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
19 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
22 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
25 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 * The views and conclusions contained in the software and documentation
31 * are those of the authors and should not be interpreted as
32 * representing official policies, either expressed or implied, of
33 * Leiden University.
34 */
36 #include "config.h"
38 #include <string.h>
39 #include <set>
40 #include <map>
41 #include <iostream>
42 #include <sstream>
43 #include <llvm/Support/raw_ostream.h>
44 #include <clang/AST/ASTContext.h>
45 #include <clang/AST/ASTDiagnostic.h>
46 #include <clang/AST/Attr.h>
47 #include <clang/AST/Expr.h>
48 #include <clang/AST/RecursiveASTVisitor.h>
50 #include <isl/id.h>
51 #include <isl/space.h>
52 #include <isl/aff.h>
53 #include <isl/set.h>
54 #include <isl/union_set.h>
56 #include "aff.h"
57 #include "array.h"
58 #include "clang.h"
59 #include "context.h"
60 #include "expr.h"
61 #include "expr_plus.h"
62 #include "id.h"
63 #include "inliner.h"
64 #include "killed_locals.h"
65 #include "nest.h"
66 #include "options.h"
67 #include "scan.h"
68 #include "scop.h"
69 #include "scop_plus.h"
70 #include "substituter.h"
71 #include "tree.h"
72 #include "tree2scop.h"
74 using namespace std;
75 using namespace clang;
77 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
79 switch (kind) {
80 case UO_Minus:
81 return pet_op_minus;
82 case UO_Not:
83 return pet_op_not;
84 case UO_LNot:
85 return pet_op_lnot;
86 case UO_PostInc:
87 return pet_op_post_inc;
88 case UO_PostDec:
89 return pet_op_post_dec;
90 case UO_PreInc:
91 return pet_op_pre_inc;
92 case UO_PreDec:
93 return pet_op_pre_dec;
94 default:
95 return pet_op_last;
99 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
101 switch (kind) {
102 case BO_AddAssign:
103 return pet_op_add_assign;
104 case BO_SubAssign:
105 return pet_op_sub_assign;
106 case BO_MulAssign:
107 return pet_op_mul_assign;
108 case BO_DivAssign:
109 return pet_op_div_assign;
110 case BO_AndAssign:
111 return pet_op_and_assign;
112 case BO_XorAssign:
113 return pet_op_xor_assign;
114 case BO_OrAssign:
115 return pet_op_or_assign;
116 case BO_Assign:
117 return pet_op_assign;
118 case BO_Add:
119 return pet_op_add;
120 case BO_Sub:
121 return pet_op_sub;
122 case BO_Mul:
123 return pet_op_mul;
124 case BO_Div:
125 return pet_op_div;
126 case BO_Rem:
127 return pet_op_mod;
128 case BO_Shl:
129 return pet_op_shl;
130 case BO_Shr:
131 return pet_op_shr;
132 case BO_EQ:
133 return pet_op_eq;
134 case BO_NE:
135 return pet_op_ne;
136 case BO_LE:
137 return pet_op_le;
138 case BO_GE:
139 return pet_op_ge;
140 case BO_LT:
141 return pet_op_lt;
142 case BO_GT:
143 return pet_op_gt;
144 case BO_And:
145 return pet_op_and;
146 case BO_Xor:
147 return pet_op_xor;
148 case BO_Or:
149 return pet_op_or;
150 case BO_LAnd:
151 return pet_op_land;
152 case BO_LOr:
153 return pet_op_lor;
154 default:
155 return pet_op_last;
159 #ifdef GETTYPEINFORETURNSTYPEINFO
161 static int size_in_bytes(ASTContext &context, QualType type)
163 return context.getTypeInfo(type).Width / 8;
166 #else
168 static int size_in_bytes(ASTContext &context, QualType type)
170 return context.getTypeInfo(type).first / 8;
173 #endif
175 /* Check if the element type corresponding to the given array type
176 * has a const qualifier.
178 static bool const_base(QualType qt)
180 const Type *type = qt.getTypePtr();
182 if (type->isPointerType())
183 return const_base(type->getPointeeType());
184 if (type->isArrayType()) {
185 const ArrayType *atype;
186 type = type->getCanonicalTypeInternal().getTypePtr();
187 atype = cast<ArrayType>(type);
188 return const_base(atype->getElementType());
191 return qt.isConstQualified();
194 PetScan::~PetScan()
196 std::map<const Type *, pet_expr *>::iterator it;
197 std::map<FunctionDecl *, pet_function_summary *>::iterator it_s;
199 for (it = type_size.begin(); it != type_size.end(); ++it)
200 pet_expr_free(it->second);
201 for (it_s = summary_cache.begin(); it_s != summary_cache.end(); ++it_s)
202 pet_function_summary_free(it_s->second);
204 isl_id_to_pet_expr_free(id_size);
205 isl_union_map_free(value_bounds);
208 /* Report a diagnostic on the range "range", unless autodetect is set.
210 void PetScan::report(SourceRange range, unsigned id)
212 if (options->autodetect)
213 return;
215 SourceLocation loc = range.getBegin();
216 DiagnosticsEngine &diag = PP.getDiagnostics();
217 DiagnosticBuilder B = diag.Report(loc, id) << range;
220 /* Report a diagnostic on "stmt", unless autodetect is set.
222 void PetScan::report(Stmt *stmt, unsigned id)
224 report(stmt->getSourceRange(), id);
227 /* Report a diagnostic on "decl", unless autodetect is set.
229 void PetScan::report(Decl *decl, unsigned id)
231 report(decl->getSourceRange(), id);
234 /* Called if we found something we (currently) cannot handle.
235 * We'll provide more informative warnings later.
237 * We only actually complain if autodetect is false.
239 void PetScan::unsupported(Stmt *stmt)
241 DiagnosticsEngine &diag = PP.getDiagnostics();
242 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
243 "unsupported");
244 report(stmt, id);
247 /* Report an unsupported unary operator, unless autodetect is set.
249 void PetScan::report_unsupported_unary_operator(Stmt *stmt)
251 DiagnosticsEngine &diag = PP.getDiagnostics();
252 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
253 "this type of unary operator is not supported");
254 report(stmt, id);
257 /* Report an unsupported binary operator, unless autodetect is set.
259 void PetScan::report_unsupported_binary_operator(Stmt *stmt)
261 DiagnosticsEngine &diag = PP.getDiagnostics();
262 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
263 "this type of binary operator is not supported");
264 report(stmt, id);
267 /* Report an unsupported statement type, unless autodetect is set.
269 void PetScan::report_unsupported_statement_type(Stmt *stmt)
271 DiagnosticsEngine &diag = PP.getDiagnostics();
272 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
273 "this type of statement is not supported");
274 report(stmt, id);
277 /* Report a missing prototype, unless autodetect is set.
279 void PetScan::report_prototype_required(Stmt *stmt)
281 DiagnosticsEngine &diag = PP.getDiagnostics();
282 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
283 "prototype required");
284 report(stmt, id);
287 /* Report a missing increment, unless autodetect is set.
289 void PetScan::report_missing_increment(Stmt *stmt)
291 DiagnosticsEngine &diag = PP.getDiagnostics();
292 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
293 "missing increment");
294 report(stmt, id);
297 /* Report a missing summary function, unless autodetect is set.
299 void PetScan::report_missing_summary_function(Stmt *stmt)
301 DiagnosticsEngine &diag = PP.getDiagnostics();
302 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
303 "missing summary function");
304 report(stmt, id);
307 /* Report a missing summary function body, unless autodetect is set.
309 void PetScan::report_missing_summary_function_body(Stmt *stmt)
311 DiagnosticsEngine &diag = PP.getDiagnostics();
312 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
313 "missing summary function body");
314 report(stmt, id);
317 /* Report an unsupported argument in a call to an inlined function,
318 * unless autodetect is set.
320 void PetScan::report_unsupported_inline_function_argument(Stmt *stmt)
322 DiagnosticsEngine &diag = PP.getDiagnostics();
323 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
324 "unsupported inline function call argument");
325 report(stmt, id);
328 /* Report an unsupported type of declaration, unless autodetect is set.
330 void PetScan::report_unsupported_declaration(Decl *decl)
332 DiagnosticsEngine &diag = PP.getDiagnostics();
333 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
334 "unsupported declaration");
335 report(decl, id);
338 /* Report an unbalanced pair of scop/endscop pragmas, unless autodetect is set.
340 void PetScan::report_unbalanced_pragmas(SourceLocation scop,
341 SourceLocation endscop)
343 if (options->autodetect)
344 return;
346 DiagnosticsEngine &diag = PP.getDiagnostics();
348 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
349 "unbalanced endscop pragma");
350 DiagnosticBuilder B2 = diag.Report(endscop, id);
353 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Note,
354 "corresponding scop pragma");
355 DiagnosticBuilder B = diag.Report(scop, id);
359 /* Report a return statement in an unsupported context,
360 * unless autodetect is set.
362 void PetScan::report_unsupported_return(Stmt *stmt)
364 DiagnosticsEngine &diag = PP.getDiagnostics();
365 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
366 "return statements not supported in this context");
367 report(stmt, id);
370 /* Report a return statement that does not appear at the end of a function,
371 * unless autodetect is set.
373 void PetScan::report_return_not_at_end_of_function(Stmt *stmt)
375 DiagnosticsEngine &diag = PP.getDiagnostics();
376 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
377 "return statement must be final statement in function");
378 report(stmt, id);
381 /* Extract an integer from "val", which is assumed to be non-negative.
383 static __isl_give isl_val *extract_unsigned(isl_ctx *ctx,
384 const llvm::APInt &val)
386 unsigned n;
387 const uint64_t *data;
389 data = val.getRawData();
390 n = val.getNumWords();
391 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
394 /* Extract an integer from "val". If "is_signed" is set, then "val"
395 * is signed. Otherwise it it unsigned.
397 static __isl_give isl_val *extract_int(isl_ctx *ctx, bool is_signed,
398 llvm::APInt val)
400 int is_negative = is_signed && val.isNegative();
401 isl_val *v;
403 if (is_negative)
404 val = -val;
406 v = extract_unsigned(ctx, val);
408 if (is_negative)
409 v = isl_val_neg(v);
410 return v;
413 /* Extract an integer from "expr".
415 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
417 const Type *type = expr->getType().getTypePtr();
418 bool is_signed = type->hasSignedIntegerRepresentation();
420 return ::extract_int(ctx, is_signed, expr->getValue());
423 /* Extract an integer from "expr".
424 * Return NULL if "expr" does not (obviously) represent an integer.
426 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
428 return extract_int(expr->getSubExpr());
431 /* Extract an integer from "expr".
432 * Return NULL if "expr" does not (obviously) represent an integer.
434 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
436 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
437 return extract_int(ctx, cast<IntegerLiteral>(expr));
438 if (expr->getStmtClass() == Stmt::ParenExprClass)
439 return extract_int(cast<ParenExpr>(expr));
441 unsupported(expr);
442 return NULL;
445 /* Extract a pet_expr from the APInt "val", which is assumed
446 * to be non-negative.
448 __isl_give pet_expr *PetScan::extract_expr(const llvm::APInt &val)
450 return pet_expr_new_int(extract_unsigned(ctx, val));
453 /* Return the number of bits needed to represent the type of "decl",
454 * if it is an integer type. Otherwise return 0.
455 * If qt is signed then return the opposite of the number of bits.
457 static int get_type_size(ValueDecl *decl)
459 return pet_clang_get_type_size(decl->getType(), decl->getASTContext());
462 /* Bound parameter "pos" of "set" to the possible values of "decl".
464 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
465 unsigned pos, ValueDecl *decl)
467 int type_size;
468 isl_ctx *ctx;
469 isl_val *bound;
471 ctx = isl_set_get_ctx(set);
472 type_size = get_type_size(decl);
473 if (type_size == 0)
474 isl_die(ctx, isl_error_invalid, "not an integer type",
475 return isl_set_free(set));
476 if (type_size > 0) {
477 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
478 bound = isl_val_int_from_ui(ctx, type_size);
479 bound = isl_val_2exp(bound);
480 bound = isl_val_sub_ui(bound, 1);
481 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
482 } else {
483 bound = isl_val_int_from_ui(ctx, -type_size - 1);
484 bound = isl_val_2exp(bound);
485 bound = isl_val_sub_ui(bound, 1);
486 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
487 isl_val_copy(bound));
488 bound = isl_val_neg(bound);
489 bound = isl_val_sub_ui(bound, 1);
490 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
493 return set;
496 __isl_give pet_expr *PetScan::extract_index_expr(ImplicitCastExpr *expr)
498 return extract_index_expr(expr->getSubExpr());
501 /* Construct a pet_expr representing an index expression for an access
502 * to the variable referenced by "expr".
504 * If "expr" references an enum constant, then return an integer expression
505 * instead, representing the value of the enum constant.
507 __isl_give pet_expr *PetScan::extract_index_expr(DeclRefExpr *expr)
509 return extract_index_expr(expr->getDecl());
512 /* Construct a pet_expr representing an index expression for an access
513 * to the variable "decl".
515 * If "decl" is an enum constant, then we return an integer expression
516 * instead, representing the value of the enum constant.
518 __isl_give pet_expr *PetScan::extract_index_expr(ValueDecl *decl)
520 isl_id *id;
522 if (isa<EnumConstantDecl>(decl))
523 return extract_expr(cast<EnumConstantDecl>(decl));
525 id = pet_id_from_decl(ctx, decl);
526 return pet_id_create_index_expr(id);
529 /* Construct a pet_expr representing the index expression "expr"
530 * Return NULL on error.
532 * If "expr" is a reference to an enum constant, then return
533 * an integer expression instead, representing the value of the enum constant.
535 __isl_give pet_expr *PetScan::extract_index_expr(Expr *expr)
537 switch (expr->getStmtClass()) {
538 case Stmt::ImplicitCastExprClass:
539 return extract_index_expr(cast<ImplicitCastExpr>(expr));
540 case Stmt::DeclRefExprClass:
541 return extract_index_expr(cast<DeclRefExpr>(expr));
542 case Stmt::ArraySubscriptExprClass:
543 return extract_index_expr(cast<ArraySubscriptExpr>(expr));
544 case Stmt::IntegerLiteralClass:
545 return extract_expr(cast<IntegerLiteral>(expr));
546 case Stmt::MemberExprClass:
547 return extract_index_expr(cast<MemberExpr>(expr));
548 default:
549 unsupported(expr);
551 return NULL;
554 /* Extract an index expression from the given array subscript expression.
556 * We first extract an index expression from the base.
557 * This will result in an index expression with a range that corresponds
558 * to the earlier indices.
559 * We then extract the current index and let
560 * pet_expr_access_subscript combine the two.
562 __isl_give pet_expr *PetScan::extract_index_expr(ArraySubscriptExpr *expr)
564 Expr *base = expr->getBase();
565 Expr *idx = expr->getIdx();
566 pet_expr *index;
567 pet_expr *base_expr;
569 base_expr = extract_index_expr(base);
570 index = extract_expr(idx);
572 base_expr = pet_expr_access_subscript(base_expr, index);
574 return base_expr;
577 /* Extract an index expression from a member expression.
579 * If the base access (to the structure containing the member)
580 * is of the form
582 * A[..]
584 * and the member is called "f", then the member access is of
585 * the form
587 * A_f[A[..] -> f[]]
589 * If the member access is to an anonymous struct, then simply return
591 * A[..]
593 * If the member access in the source code is of the form
595 * A->f
597 * then it is treated as
599 * A[0].f
601 __isl_give pet_expr *PetScan::extract_index_expr(MemberExpr *expr)
603 Expr *base = expr->getBase();
604 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
605 pet_expr *base_index;
606 isl_id *id;
608 base_index = extract_index_expr(base);
610 if (expr->isArrow()) {
611 pet_expr *index = pet_expr_new_int(isl_val_zero(ctx));
612 base_index = pet_expr_access_subscript(base_index, index);
615 if (field->isAnonymousStructOrUnion())
616 return base_index;
618 id = pet_id_from_decl(ctx, field);
620 return pet_expr_access_member(base_index, id);
623 /* Mark the given access pet_expr as a write.
625 static __isl_give pet_expr *mark_write(__isl_take pet_expr *access)
627 access = pet_expr_access_set_write(access, 1);
628 access = pet_expr_access_set_read(access, 0);
630 return access;
633 /* Mark the given (read) access pet_expr as also possibly being written.
634 * That is, initialize the may write access relation from the may read relation
635 * and initialize the must write access relation to the empty relation.
637 static __isl_give pet_expr *mark_may_write(__isl_take pet_expr *expr)
639 isl_union_map *access;
640 isl_union_map *empty;
642 access = pet_expr_access_get_dependent_access(expr,
643 pet_expr_access_may_read);
644 empty = isl_union_map_empty(isl_union_map_get_space(access));
645 expr = pet_expr_access_set_access(expr, pet_expr_access_may_write,
646 access);
647 expr = pet_expr_access_set_access(expr, pet_expr_access_must_write,
648 empty);
650 return expr;
653 /* Construct a pet_expr representing a unary operator expression.
655 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
657 int type_size;
658 pet_expr *arg;
659 enum pet_op_type op;
661 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
662 if (op == pet_op_last) {
663 report_unsupported_unary_operator(expr);
664 return NULL;
667 arg = extract_expr(expr->getSubExpr());
669 if (expr->isIncrementDecrementOp() &&
670 pet_expr_get_type(arg) == pet_expr_access) {
671 arg = mark_write(arg);
672 arg = pet_expr_access_set_read(arg, 1);
675 type_size = pet_clang_get_type_size(expr->getType(), ast_context);
676 return pet_expr_new_unary(type_size, op, arg);
679 /* Construct a pet_expr representing a binary operator expression.
681 * If the top level operator is an assignment and the LHS is an access,
682 * then we mark that access as a write. If the operator is a compound
683 * assignment, the access is marked as both a read and a write.
685 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
687 int type_size;
688 pet_expr *lhs, *rhs;
689 enum pet_op_type op;
691 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
692 if (op == pet_op_last) {
693 report_unsupported_binary_operator(expr);
694 return NULL;
697 lhs = extract_expr(expr->getLHS());
698 rhs = extract_expr(expr->getRHS());
700 if (expr->isAssignmentOp() &&
701 pet_expr_get_type(lhs) == pet_expr_access) {
702 lhs = mark_write(lhs);
703 if (expr->isCompoundAssignmentOp())
704 lhs = pet_expr_access_set_read(lhs, 1);
707 type_size = pet_clang_get_type_size(expr->getType(), ast_context);
708 return pet_expr_new_binary(type_size, op, lhs, rhs);
711 /* Construct a pet_tree for a variable declaration and
712 * add the declaration to the list of declarations
713 * inside the current compound statement.
715 __isl_give pet_tree *PetScan::extract(Decl *decl)
717 VarDecl *vd;
718 pet_expr *lhs, *rhs;
719 pet_tree *tree;
721 if (!isa<VarDecl>(decl)) {
722 report_unsupported_declaration(decl);
723 return NULL;
726 vd = cast<VarDecl>(decl);
727 declarations.push_back(vd);
729 lhs = extract_access_expr(vd);
730 lhs = mark_write(lhs);
731 if (!vd->getInit())
732 tree = pet_tree_new_decl(lhs);
733 else {
734 rhs = extract_expr(vd->getInit());
735 tree = pet_tree_new_decl_init(lhs, rhs);
738 return tree;
741 /* Construct a pet_tree for a variable declaration statement.
742 * If the declaration statement declares multiple variables,
743 * then return a group of pet_trees, one for each declared variable.
745 __isl_give pet_tree *PetScan::extract(DeclStmt *stmt)
747 pet_tree *tree;
748 unsigned n;
750 if (!stmt->isSingleDecl()) {
751 const DeclGroup &group = stmt->getDeclGroup().getDeclGroup();
752 n = group.size();
753 tree = pet_tree_new_block(ctx, 0, n);
755 for (unsigned i = 0; i < n; ++i) {
756 pet_tree *tree_i;
757 pet_loc *loc;
759 tree_i = extract(group[i]);
760 loc = construct_pet_loc(group[i]->getSourceRange(),
761 false);
762 tree_i = pet_tree_set_loc(tree_i, loc);
763 tree = pet_tree_block_add_child(tree, tree_i);
766 return tree;
769 return extract(stmt->getSingleDecl());
772 /* Construct a pet_expr representing a conditional operation.
774 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
776 pet_expr *cond, *lhs, *rhs;
778 cond = extract_expr(expr->getCond());
779 lhs = extract_expr(expr->getTrueExpr());
780 rhs = extract_expr(expr->getFalseExpr());
782 return pet_expr_new_ternary(cond, lhs, rhs);
785 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
787 return extract_expr(expr->getSubExpr());
790 /* Construct a pet_expr representing a floating point value.
792 * If the floating point literal does not appear in a macro,
793 * then we use the original representation in the source code
794 * as the string representation. Otherwise, we use the pretty
795 * printer to produce a string representation.
797 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
799 double d;
800 string s;
801 const LangOptions &LO = PP.getLangOpts();
802 SourceLocation loc = expr->getLocation();
804 if (!loc.isMacroID()) {
805 SourceManager &SM = PP.getSourceManager();
806 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
807 s = string(SM.getCharacterData(loc), len);
808 } else {
809 llvm::raw_string_ostream S(s);
810 expr->printPretty(S, 0, PrintingPolicy(LO));
811 S.str();
813 d = expr->getValueAsApproximateDouble();
814 return pet_expr_new_double(ctx, d, s.c_str());
817 /* Extract an index expression from "expr" and then convert it into
818 * an access pet_expr.
820 * If "expr" is a reference to an enum constant, then return
821 * an integer expression instead, representing the value of the enum constant.
823 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
825 pet_expr *index;
827 index = extract_index_expr(expr);
829 if (pet_expr_get_type(index) == pet_expr_int)
830 return index;
832 return pet_expr_access_from_index(expr->getType(), index, ast_context);
835 /* Extract an index expression from "decl" and then convert it into
836 * an access pet_expr.
838 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
840 return pet_expr_access_from_index(decl->getType(),
841 extract_index_expr(decl), ast_context);
844 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
846 return extract_expr(expr->getSubExpr());
849 /* Extract an assume statement from the argument "expr"
850 * of a __builtin_assume or __pencil_assume statement.
852 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
854 return pet_expr_new_unary(0, pet_op_assume, extract_expr(expr));
857 /* If "expr" is an address-of operator, then return its argument.
858 * Otherwise, return NULL.
860 static Expr *extract_addr_of_arg(Expr *expr)
862 UnaryOperator *op;
864 if (expr->getStmtClass() != Stmt::UnaryOperatorClass)
865 return NULL;
866 op = cast<UnaryOperator>(expr);
867 if (op->getOpcode() != UO_AddrOf)
868 return NULL;
869 return op->getSubExpr();
872 /* Construct a pet_expr corresponding to the function call argument "expr".
873 * The argument appears in position "pos" of a call to function "fd".
875 * If we are passing along a pointer to an array element
876 * or an entire row or even higher dimensional slice of an array,
877 * then the function being called may write into the array.
879 * We assume here that if the function is declared to take a pointer
880 * to a const type, then the function may only perform a read
881 * and that otherwise, it may either perform a read or a write (or both).
882 * We only perform this check if "detect_writes" is set.
884 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
885 Expr *expr, bool detect_writes)
887 Expr *arg;
888 pet_expr *res;
889 int is_addr = 0, is_partial = 0;
891 expr = pet_clang_strip_casts(expr);
892 arg = extract_addr_of_arg(expr);
893 if (arg) {
894 is_addr = 1;
895 expr = arg;
897 res = extract_expr(expr);
898 if (!res)
899 return NULL;
900 if (pet_clang_array_depth(expr->getType()) > 0)
901 is_partial = 1;
902 if (detect_writes && (is_addr || is_partial) &&
903 pet_expr_get_type(res) == pet_expr_access) {
904 ParmVarDecl *parm;
905 if (!fd->hasPrototype()) {
906 report_prototype_required(expr);
907 return pet_expr_free(res);
909 parm = fd->getParamDecl(pos);
910 if (!const_base(parm->getType()))
911 res = mark_may_write(res);
914 if (is_addr)
915 res = pet_expr_new_unary(0, pet_op_address_of, res);
916 return res;
919 /* Find the first FunctionDecl with the given name.
920 * "call" is the corresponding call expression and is only used
921 * for reporting errors.
923 * Return NULL on error.
925 FunctionDecl *PetScan::find_decl_from_name(CallExpr *call, string name)
927 TranslationUnitDecl *tu = ast_context.getTranslationUnitDecl();
928 DeclContext::decl_iterator begin = tu->decls_begin();
929 DeclContext::decl_iterator end = tu->decls_end();
930 for (DeclContext::decl_iterator i = begin; i != end; ++i) {
931 FunctionDecl *fd = dyn_cast<FunctionDecl>(*i);
932 if (!fd)
933 continue;
934 if (fd->getName().str().compare(name) != 0)
935 continue;
936 if (fd->hasBody())
937 return fd;
938 report_missing_summary_function_body(call);
939 return NULL;
941 report_missing_summary_function(call);
942 return NULL;
945 /* Return the FunctionDecl for the summary function associated to the
946 * function called by "call".
948 * In particular, if the pencil option is set, then
949 * search for an annotate attribute formatted as
950 * "pencil_access(name)", where "name" is the name of the summary function.
952 * If no summary function was specified, then return the FunctionDecl
953 * that is actually being called.
955 * Return NULL on error.
957 FunctionDecl *PetScan::get_summary_function(CallExpr *call)
959 FunctionDecl *decl = call->getDirectCallee();
960 if (!decl)
961 return NULL;
963 if (!options->pencil)
964 return decl;
966 specific_attr_iterator<AnnotateAttr> begin, end, i;
967 begin = decl->specific_attr_begin<AnnotateAttr>();
968 end = decl->specific_attr_end<AnnotateAttr>();
969 for (i = begin; i != end; ++i) {
970 string attr = (*i)->getAnnotation().str();
972 const char prefix[] = "pencil_access(";
973 size_t start = attr.find(prefix);
974 if (start == string::npos)
975 continue;
976 start += strlen(prefix);
977 string name = attr.substr(start, attr.find(')') - start);
979 return find_decl_from_name(call, name);
982 return decl;
985 /* Is "name" the name of an assume statement?
986 * "pencil" indicates whether pencil builtins and pragmas should be supported.
987 * "__builtin_assume" is always accepted.
988 * If "pencil" is set, then "__pencil_assume" is also accepted.
990 static bool is_assume(int pencil, const string &name)
992 if (name == "__builtin_assume")
993 return true;
994 return pencil && name == "__pencil_assume";
997 /* Construct a pet_expr representing a function call.
999 * In the special case of a "call" to __builtin_assume or __pencil_assume,
1000 * construct an assume expression instead.
1002 * In the case of a "call" to __pencil_kill, the arguments
1003 * are neither read nor written (only killed), so there
1004 * is no need to check for writes to these arguments.
1006 * __pencil_assume and __pencil_kill are only recognized
1007 * when the pencil option is set.
1009 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1011 pet_expr *res = NULL;
1012 FunctionDecl *fd;
1013 string name;
1014 unsigned n_arg;
1015 bool is_kill;
1017 fd = expr->getDirectCallee();
1018 if (!fd) {
1019 unsupported(expr);
1020 return NULL;
1023 name = fd->getDeclName().getAsString();
1024 n_arg = expr->getNumArgs();
1026 if (n_arg == 1 && is_assume(options->pencil, name))
1027 return extract_assume(expr->getArg(0));
1028 is_kill = options->pencil && name == "__pencil_kill";
1030 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1031 if (!res)
1032 return NULL;
1034 for (unsigned i = 0; i < n_arg; ++i) {
1035 Expr *arg = expr->getArg(i);
1036 res = pet_expr_set_arg(res, i,
1037 PetScan::extract_argument(fd, i, arg, !is_kill));
1040 fd = get_summary_function(expr);
1041 if (!fd)
1042 return pet_expr_free(res);
1044 res = set_summary(res, fd);
1046 return res;
1049 /* Construct a pet_expr representing a (C style) cast.
1051 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1053 pet_expr *arg;
1054 QualType type;
1056 arg = extract_expr(expr->getSubExpr());
1057 if (!arg)
1058 return NULL;
1060 type = expr->getTypeAsWritten();
1061 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1064 /* Construct a pet_expr representing an integer.
1066 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1068 return pet_expr_new_int(extract_int(expr));
1071 /* Construct a pet_expr representing the integer enum constant "ecd".
1073 __isl_give pet_expr *PetScan::extract_expr(EnumConstantDecl *ecd)
1075 isl_val *v;
1076 const llvm::APSInt &init = ecd->getInitVal();
1077 v = ::extract_int(ctx, init.isSigned(), init);
1078 return pet_expr_new_int(v);
1081 /* Try and construct a pet_expr representing "expr".
1083 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1085 switch (expr->getStmtClass()) {
1086 case Stmt::UnaryOperatorClass:
1087 return extract_expr(cast<UnaryOperator>(expr));
1088 case Stmt::CompoundAssignOperatorClass:
1089 case Stmt::BinaryOperatorClass:
1090 return extract_expr(cast<BinaryOperator>(expr));
1091 case Stmt::ImplicitCastExprClass:
1092 return extract_expr(cast<ImplicitCastExpr>(expr));
1093 case Stmt::ArraySubscriptExprClass:
1094 case Stmt::DeclRefExprClass:
1095 case Stmt::MemberExprClass:
1096 return extract_access_expr(expr);
1097 case Stmt::IntegerLiteralClass:
1098 return extract_expr(cast<IntegerLiteral>(expr));
1099 case Stmt::FloatingLiteralClass:
1100 return extract_expr(cast<FloatingLiteral>(expr));
1101 case Stmt::ParenExprClass:
1102 return extract_expr(cast<ParenExpr>(expr));
1103 case Stmt::ConditionalOperatorClass:
1104 return extract_expr(cast<ConditionalOperator>(expr));
1105 case Stmt::CallExprClass:
1106 return extract_expr(cast<CallExpr>(expr));
1107 case Stmt::CStyleCastExprClass:
1108 return extract_expr(cast<CStyleCastExpr>(expr));
1109 default:
1110 unsupported(expr);
1112 return NULL;
1115 /* Check if the given initialization statement is an assignment.
1116 * If so, return that assignment. Otherwise return NULL.
1118 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1120 BinaryOperator *ass;
1122 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1123 return NULL;
1125 ass = cast<BinaryOperator>(init);
1126 if (ass->getOpcode() != BO_Assign)
1127 return NULL;
1129 return ass;
1132 /* Check if the given initialization statement is a declaration
1133 * of a single variable.
1134 * If so, return that declaration. Otherwise return NULL.
1136 Decl *PetScan::initialization_declaration(Stmt *init)
1138 DeclStmt *decl;
1140 if (init->getStmtClass() != Stmt::DeclStmtClass)
1141 return NULL;
1143 decl = cast<DeclStmt>(init);
1145 if (!decl->isSingleDecl())
1146 return NULL;
1148 return decl->getSingleDecl();
1151 /* Given the assignment operator in the initialization of a for loop,
1152 * extract the induction variable, i.e., the (integer)variable being
1153 * assigned.
1155 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1157 Expr *lhs;
1158 DeclRefExpr *ref;
1159 ValueDecl *decl;
1160 const Type *type;
1162 lhs = init->getLHS();
1163 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1164 unsupported(init);
1165 return NULL;
1168 ref = cast<DeclRefExpr>(lhs);
1169 decl = ref->getDecl();
1170 type = decl->getType().getTypePtr();
1172 if (!type->isIntegerType()) {
1173 unsupported(lhs);
1174 return NULL;
1177 return decl;
1180 /* Given the initialization statement of a for loop and the single
1181 * declaration in this initialization statement,
1182 * extract the induction variable, i.e., the (integer) variable being
1183 * declared.
1185 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1187 VarDecl *vd;
1189 vd = cast<VarDecl>(decl);
1191 const QualType type = vd->getType();
1192 if (!type->isIntegerType()) {
1193 unsupported(init);
1194 return NULL;
1197 if (!vd->getInit()) {
1198 unsupported(init);
1199 return NULL;
1202 return vd;
1205 /* Check that op is of the form iv++ or iv--.
1206 * Return a pet_expr representing "1" or "-1" accordingly.
1208 __isl_give pet_expr *PetScan::extract_unary_increment(
1209 clang::UnaryOperator *op, clang::ValueDecl *iv)
1211 Expr *sub;
1212 DeclRefExpr *ref;
1213 isl_val *v;
1215 if (!op->isIncrementDecrementOp()) {
1216 unsupported(op);
1217 return NULL;
1220 sub = op->getSubExpr();
1221 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1222 unsupported(op);
1223 return NULL;
1226 ref = cast<DeclRefExpr>(sub);
1227 if (ref->getDecl() != iv) {
1228 unsupported(op);
1229 return NULL;
1232 if (op->isIncrementOp())
1233 v = isl_val_one(ctx);
1234 else
1235 v = isl_val_negone(ctx);
1237 return pet_expr_new_int(v);
1240 /* Check if op is of the form
1242 * iv = expr
1244 * and return the increment "expr - iv" as a pet_expr.
1246 __isl_give pet_expr *PetScan::extract_binary_increment(BinaryOperator *op,
1247 clang::ValueDecl *iv)
1249 int type_size;
1250 Expr *lhs;
1251 DeclRefExpr *ref;
1252 pet_expr *expr, *expr_iv;
1254 if (op->getOpcode() != BO_Assign) {
1255 unsupported(op);
1256 return NULL;
1259 lhs = op->getLHS();
1260 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1261 unsupported(op);
1262 return NULL;
1265 ref = cast<DeclRefExpr>(lhs);
1266 if (ref->getDecl() != iv) {
1267 unsupported(op);
1268 return NULL;
1271 expr = extract_expr(op->getRHS());
1272 expr_iv = extract_expr(lhs);
1274 type_size = pet_clang_get_type_size(iv->getType(), ast_context);
1275 return pet_expr_new_binary(type_size, pet_op_sub, expr, expr_iv);
1278 /* Check that op is of the form iv += cst or iv -= cst
1279 * and return a pet_expr corresponding to cst or -cst accordingly.
1281 __isl_give pet_expr *PetScan::extract_compound_increment(
1282 CompoundAssignOperator *op, clang::ValueDecl *iv)
1284 Expr *lhs;
1285 DeclRefExpr *ref;
1286 bool neg = false;
1287 pet_expr *expr;
1288 BinaryOperatorKind opcode;
1290 opcode = op->getOpcode();
1291 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1292 unsupported(op);
1293 return NULL;
1295 if (opcode == BO_SubAssign)
1296 neg = true;
1298 lhs = op->getLHS();
1299 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1300 unsupported(op);
1301 return NULL;
1304 ref = cast<DeclRefExpr>(lhs);
1305 if (ref->getDecl() != iv) {
1306 unsupported(op);
1307 return NULL;
1310 expr = extract_expr(op->getRHS());
1311 if (neg) {
1312 int type_size;
1313 type_size = pet_clang_get_type_size(op->getType(), ast_context);
1314 expr = pet_expr_new_unary(type_size, pet_op_minus, expr);
1317 return expr;
1320 /* Check that the increment of the given for loop increments
1321 * (or decrements) the induction variable "iv" and return
1322 * the increment as a pet_expr if successful.
1324 __isl_give pet_expr *PetScan::extract_increment(clang::ForStmt *stmt,
1325 ValueDecl *iv)
1327 Stmt *inc = stmt->getInc();
1329 if (!inc) {
1330 report_missing_increment(stmt);
1331 return NULL;
1334 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1335 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1336 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1337 return extract_compound_increment(
1338 cast<CompoundAssignOperator>(inc), iv);
1339 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1340 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1342 unsupported(inc);
1343 return NULL;
1346 /* Construct a pet_tree for a while loop.
1348 * If we were only able to extract part of the body, then simply
1349 * return that part.
1351 __isl_give pet_tree *PetScan::extract(WhileStmt *stmt)
1353 pet_expr *pe_cond;
1354 pet_tree *tree;
1356 tree = extract(stmt->getBody());
1357 if (partial)
1358 return tree;
1359 pe_cond = extract_expr(stmt->getCond());
1360 tree = pet_tree_new_while(pe_cond, tree);
1362 return tree;
1365 /* Construct a pet_tree for a for statement.
1366 * The for loop is required to be of one of the following forms
1368 * for (i = init; condition; ++i)
1369 * for (i = init; condition; --i)
1370 * for (i = init; condition; i += constant)
1371 * for (i = init; condition; i -= constant)
1373 * We extract a pet_tree for the body and then include it in a pet_tree
1374 * of type pet_tree_for.
1376 * As a special case, we also allow a for loop of the form
1378 * for (;;)
1380 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1382 * If we were only able to extract part of the body, then simply
1383 * return that part.
1385 __isl_give pet_tree *PetScan::extract_for(ForStmt *stmt)
1387 BinaryOperator *ass;
1388 Decl *decl;
1389 Stmt *init;
1390 Expr *rhs;
1391 ValueDecl *iv;
1392 pet_tree *tree;
1393 int independent;
1394 int declared;
1395 pet_expr *pe_init, *pe_inc, *pe_iv, *pe_cond;
1397 independent = is_current_stmt_marked_independent();
1399 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc()) {
1400 tree = extract(stmt->getBody());
1401 if (partial)
1402 return tree;
1403 tree = pet_tree_new_infinite_loop(tree);
1404 return tree;
1407 init = stmt->getInit();
1408 if (!init) {
1409 unsupported(stmt);
1410 return NULL;
1412 if ((ass = initialization_assignment(init)) != NULL) {
1413 iv = extract_induction_variable(ass);
1414 if (!iv)
1415 return NULL;
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 } 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 /* Store the names of the variables declared in decl_context
1446 * in the set declared_names. Make sure to only do this once by
1447 * setting declared_names_collected.
1449 void PetScan::collect_declared_names()
1451 DeclContext *DC = decl_context;
1452 DeclContext::decl_iterator it;
1454 if (declared_names_collected)
1455 return;
1457 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1458 Decl *D = *it;
1459 NamedDecl *named;
1461 if (!isa<NamedDecl>(D))
1462 continue;
1463 named = cast<NamedDecl>(D);
1464 declared_names.insert(named->getName().str());
1467 declared_names_collected = true;
1470 /* Add the names in "names" that are not also in this->declared_names
1471 * to this->used_names.
1472 * It is up to the caller to make sure that declared_names has been
1473 * populated, if needed.
1475 void PetScan::add_new_used_names(const std::set<std::string> &names)
1477 std::set<std::string>::const_iterator it;
1479 for (it = names.begin(); it != names.end(); ++it) {
1480 if (declared_names.find(*it) != declared_names.end())
1481 continue;
1482 used_names.insert(*it);
1486 /* Is the name "name" used in any declaration other than "decl"?
1488 * If the name was found to be in use before, the consider it to be in use.
1489 * Otherwise, check the DeclContext of the function containing the scop
1490 * as well as all ancestors of this DeclContext for declarations
1491 * other than "decl" that declare something called "name".
1493 bool PetScan::name_in_use(const string &name, Decl *decl)
1495 DeclContext *DC;
1496 DeclContext::decl_iterator it;
1498 if (used_names.find(name) != used_names.end())
1499 return true;
1501 for (DC = decl_context; DC; DC = DC->getParent()) {
1502 for (it = DC->decls_begin(); it != DC->decls_end(); ++it) {
1503 Decl *D = *it;
1504 NamedDecl *named;
1506 if (D == decl)
1507 continue;
1508 if (!isa<NamedDecl>(D))
1509 continue;
1510 named = cast<NamedDecl>(D);
1511 if (named->getName().str() == name)
1512 return true;
1516 return false;
1519 /* Generate a new name based on "name" that is not in use.
1520 * Do so by adding a suffix _i, with i an integer.
1522 string PetScan::generate_new_name(const string &name)
1524 string new_name;
1526 do {
1527 std::ostringstream oss;
1528 oss << name << "_" << n_rename++;
1529 new_name = oss.str();
1530 } while (name_in_use(new_name, NULL));
1532 return new_name;
1535 /* Try and construct a pet_tree corresponding to a compound statement.
1537 * "skip_declarations" is set if we should skip initial declarations
1538 * in the children of the compound statements.
1540 * Collect a new set of declarations for the current compound statement.
1541 * If any of the names in these declarations is also used by another
1542 * declaration reachable from the current function, then rename it
1543 * to a name that is not already in use.
1544 * In particular, keep track of the old and new names in a pet_substituter
1545 * and apply the substitutions to the pet_tree corresponding to the
1546 * compound statement.
1548 __isl_give pet_tree *PetScan::extract(CompoundStmt *stmt,
1549 bool skip_declarations)
1551 pet_tree *tree;
1552 std::vector<VarDecl *> saved_declarations;
1553 std::vector<VarDecl *>::iterator it;
1554 pet_substituter substituter;
1556 saved_declarations = declarations;
1557 declarations.clear();
1558 tree = extract(stmt->children(), true, skip_declarations, stmt);
1559 for (it = declarations.begin(); it != declarations.end(); ++it) {
1560 isl_id *id;
1561 pet_expr *expr;
1562 VarDecl *decl = *it;
1563 string name = decl->getName().str();
1564 bool in_use = name_in_use(name, decl);
1566 used_names.insert(name);
1567 if (!in_use)
1568 continue;
1570 name = generate_new_name(name);
1571 id = pet_id_from_name_and_decl(ctx, name.c_str(), decl);
1572 expr = pet_expr_access_from_id(id, ast_context);
1573 id = pet_id_from_decl(ctx, decl);
1574 substituter.add_sub(id, expr);
1575 used_names.insert(name);
1577 tree = substituter.substitute(tree);
1578 declarations = saved_declarations;
1580 return tree;
1583 /* Return the file offset of the expansion location of "Loc".
1585 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
1587 return SM.getFileOffset(SM.getExpansionLoc(Loc));
1590 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1592 /* Return a SourceLocation for the location after the first semicolon
1593 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1594 * call it and also skip trailing spaces and newline.
1596 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1597 const LangOptions &LO)
1599 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
1602 #else
1604 /* Return a SourceLocation for the location after the first semicolon
1605 * after "loc". If Lexer::findLocationAfterToken is not available,
1606 * we look in the underlying character data for the first semicolon.
1608 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
1609 const LangOptions &LO)
1611 const char *semi;
1612 const char *s = SM.getCharacterData(loc);
1614 semi = strchr(s, ';');
1615 if (!semi)
1616 return SourceLocation();
1617 return loc.getFileLocWithOffset(semi + 1 - s);
1620 #endif
1622 /* If the token at "loc" is the first token on the line, then return
1623 * a location referring to the start of the line and set *indent
1624 * to the indentation of "loc"
1625 * Otherwise, return "loc" and set *indent to "".
1627 * This function is used to extend a scop to the start of the line
1628 * if the first token of the scop is also the first token on the line.
1630 * We look for the first token on the line. If its location is equal to "loc",
1631 * then the latter is the location of the first token on the line.
1633 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
1634 SourceManager &SM, const LangOptions &LO, char **indent)
1636 std::pair<FileID, unsigned> file_offset_pair;
1637 llvm::StringRef file;
1638 const char *pos;
1639 Token tok;
1640 SourceLocation token_loc, line_loc;
1641 int col;
1642 const char *s;
1644 loc = SM.getExpansionLoc(loc);
1645 col = SM.getExpansionColumnNumber(loc);
1646 line_loc = loc.getLocWithOffset(1 - col);
1647 file_offset_pair = SM.getDecomposedLoc(line_loc);
1648 file = SM.getBufferData(file_offset_pair.first, NULL);
1649 pos = file.data() + file_offset_pair.second;
1651 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
1652 file.begin(), pos, file.end());
1653 lexer.LexFromRawLexer(tok);
1654 token_loc = tok.getLocation();
1656 s = SM.getCharacterData(line_loc);
1657 *indent = strndup(s, token_loc == loc ? col - 1 : 0);
1659 if (token_loc == loc)
1660 return line_loc;
1661 else
1662 return loc;
1665 /* Construct a pet_loc corresponding to the region covered by "range".
1666 * If "skip_semi" is set, then we assume "range" is followed by
1667 * a semicolon and also include this semicolon.
1669 __isl_give pet_loc *PetScan::construct_pet_loc(SourceRange range,
1670 bool skip_semi)
1672 SourceLocation loc = range.getBegin();
1673 SourceManager &SM = PP.getSourceManager();
1674 const LangOptions &LO = PP.getLangOpts();
1675 int line = PP.getSourceManager().getExpansionLineNumber(loc);
1676 unsigned start, end;
1677 char *indent;
1679 loc = move_to_start_of_line_if_first_token(loc, SM, LO, &indent);
1680 start = getExpansionOffset(SM, loc);
1681 loc = range.getEnd();
1682 if (skip_semi)
1683 loc = location_after_semi(loc, SM, LO);
1684 else
1685 loc = PP.getLocForEndOfToken(loc);
1686 end = getExpansionOffset(SM, loc);
1688 return pet_loc_alloc(ctx, start, end, line, indent);
1691 /* Convert a top-level pet_expr to an expression pet_tree.
1693 __isl_give pet_tree *PetScan::extract(__isl_take pet_expr *expr,
1694 SourceRange range, bool skip_semi)
1696 pet_loc *loc;
1697 pet_tree *tree;
1699 tree = pet_tree_new_expr(expr);
1700 loc = construct_pet_loc(range, skip_semi);
1701 tree = pet_tree_set_loc(tree, loc);
1703 return tree;
1706 /* Construct a pet_tree for an if statement.
1708 __isl_give pet_tree *PetScan::extract(IfStmt *stmt)
1710 pet_expr *pe_cond;
1711 pet_tree *tree, *tree_else;
1713 pe_cond = extract_expr(stmt->getCond());
1714 tree = extract(stmt->getThen());
1715 if (stmt->getElse()) {
1716 tree_else = extract(stmt->getElse());
1717 if (options->autodetect) {
1718 if (tree && !tree_else) {
1719 partial = true;
1720 pet_expr_free(pe_cond);
1721 return tree;
1723 if (!tree && tree_else) {
1724 partial = true;
1725 pet_expr_free(pe_cond);
1726 return tree_else;
1729 tree = pet_tree_new_if_else(pe_cond, tree, tree_else);
1730 } else
1731 tree = pet_tree_new_if(pe_cond, tree);
1732 return tree;
1735 /* Is "parent" a compound statement that has "stmt" as its final child?
1737 static bool final_in_compound(ReturnStmt *stmt, Stmt *parent)
1739 CompoundStmt *c;
1741 c = dyn_cast<CompoundStmt>(parent);
1742 if (c) {
1743 StmtIterator i;
1744 Stmt *last;
1745 StmtRange range = c->children();
1747 for (i = range.first; i != range.second; ++i)
1748 last = *i;
1749 return last == stmt;
1751 return false;
1754 /* Try and construct a pet_tree for a return statement "stmt".
1756 * Return statements are only allowed in a context where
1757 * this->return_root has been set.
1758 * Furthermore, "stmt" should appear as the last child
1759 * in the compound statement this->return_root.
1761 __isl_give pet_tree *PetScan::extract(ReturnStmt *stmt)
1763 pet_expr *val;
1765 if (!return_root) {
1766 report_unsupported_return(stmt);
1767 return NULL;
1769 if (!final_in_compound(stmt, return_root)) {
1770 report_return_not_at_end_of_function(stmt);
1771 return NULL;
1774 val = extract_expr(stmt->getRetValue());
1775 return pet_tree_new_return(val);
1778 /* Try and construct a pet_tree for a label statement.
1780 __isl_give pet_tree *PetScan::extract(LabelStmt *stmt)
1782 isl_id *label;
1783 pet_tree *tree;
1785 label = isl_id_alloc(ctx, stmt->getName(), NULL);
1787 tree = extract(stmt->getSubStmt());
1788 tree = pet_tree_set_label(tree, label);
1789 return tree;
1792 /* Update the location of "tree" to include the source range of "stmt".
1794 * Actually, we create a new location based on the source range of "stmt" and
1795 * then extend this new location to include the region of the original location.
1796 * This ensures that the line number of the final location refers to "stmt".
1798 __isl_give pet_tree *PetScan::update_loc(__isl_take pet_tree *tree, Stmt *stmt)
1800 pet_loc *loc, *tree_loc;
1802 tree_loc = pet_tree_get_loc(tree);
1803 loc = construct_pet_loc(stmt->getSourceRange(), false);
1804 loc = pet_loc_update_start_end_from_loc(loc, tree_loc);
1805 pet_loc_free(tree_loc);
1807 tree = pet_tree_set_loc(tree, loc);
1808 return tree;
1811 /* Is "expr" of a type that can be converted to an access expression?
1813 static bool is_access_expr_type(Expr *expr)
1815 switch (expr->getStmtClass()) {
1816 case Stmt::ArraySubscriptExprClass:
1817 case Stmt::DeclRefExprClass:
1818 case Stmt::MemberExprClass:
1819 return true;
1820 default:
1821 return false;
1825 /* Tell the pet_inliner "inliner" about the formal arguments
1826 * in "fd" and the corresponding actual arguments in "call".
1827 * Return 0 if this was successful and -1 otherwise.
1829 * Any pointer argument is treated as an array.
1830 * The other arguments are treated as scalars.
1832 * In case of scalars, there is no restriction on the actual argument.
1833 * This actual argument is assigned to a variable with a name
1834 * that is derived from the name of the corresponding formal argument,
1835 * but made not to conflict with any variable names that are
1836 * already in use.
1838 * In case of arrays, the actual argument needs to be an expression
1839 * of a type that can be converted to an access expression or the address
1840 * of such an expression, ignoring implicit and redundant casts.
1842 int PetScan::set_inliner_arguments(pet_inliner &inliner, CallExpr *call,
1843 FunctionDecl *fd)
1845 unsigned n;
1847 n = fd->getNumParams();
1848 for (unsigned i = 0; i < n; ++i) {
1849 ParmVarDecl *parm = fd->getParamDecl(i);
1850 QualType type = parm->getType();
1851 Expr *arg, *sub;
1852 pet_expr *expr;
1853 int is_addr = 0;
1855 arg = call->getArg(i);
1856 if (pet_clang_array_depth(type) == 0) {
1857 string name = parm->getName().str();
1858 if (name_in_use(name, NULL))
1859 name = generate_new_name(name);
1860 used_names.insert(name);
1861 inliner.add_scalar_arg(parm, name, extract_expr(arg));
1862 continue;
1864 arg = pet_clang_strip_casts(arg);
1865 sub = extract_addr_of_arg(arg);
1866 if (sub) {
1867 is_addr = 1;
1868 arg = pet_clang_strip_casts(sub);
1870 if (!is_access_expr_type(arg)) {
1871 report_unsupported_inline_function_argument(arg);
1872 return -1;
1874 expr = extract_access_expr(arg);
1875 if (!expr)
1876 return -1;
1877 inliner.add_array_arg(parm, expr, is_addr);
1880 return 0;
1883 /* Internal data structure for PetScan::substitute_array_sizes.
1884 * ps is the PetScan on which the method was called.
1885 * substituter is the substituter that is used to substitute variables
1886 * in the size expressions.
1888 struct pet_substitute_array_sizes_data {
1889 PetScan *ps;
1890 pet_substituter *substituter;
1893 extern "C" {
1894 static int substitute_array_size(__isl_keep pet_tree *tree, void *user);
1897 /* If "tree" is a declaration, then perform the substitutions
1898 * in data->substituter on its size expression and store the result
1899 * in the size expression cache of data->ps such that the modified expression
1900 * will be used in subsequent calls to get_array_size.
1902 static int substitute_array_size(__isl_keep pet_tree *tree, void *user)
1904 struct pet_substitute_array_sizes_data *data;
1905 isl_id *id;
1906 pet_expr *var, *size;
1908 if (!pet_tree_is_decl(tree))
1909 return 0;
1911 data = (struct pet_substitute_array_sizes_data *) user;
1912 var = pet_tree_decl_get_var(tree);
1913 id = pet_expr_access_get_id(var);
1914 pet_expr_free(var);
1916 size = data->ps->get_array_size(id);
1917 size = data->substituter->substitute(size);
1918 data->ps->set_array_size(id, size);
1920 return 0;
1923 /* Perform the substitutions in "substituter" on all the arrays declared
1924 * inside "tree" and store the results in the size expression cache
1925 * such that the modified expressions will be used in subsequent calls
1926 * to get_array_size.
1928 int PetScan::substitute_array_sizes(__isl_keep pet_tree *tree,
1929 pet_substituter *substituter)
1931 struct pet_substitute_array_sizes_data data = { this, substituter };
1933 return pet_tree_foreach_sub_tree(tree, &substitute_array_size, &data);
1936 /* Try and construct a pet_tree from the body of "fd" using the actual
1937 * arguments in "call" in place of the formal arguments.
1938 * "fd" is assumed to point to the declaration with a function body.
1939 * In particular, construct a block that consists of assignments
1940 * of (parts of) the actual arguments to temporary variables
1941 * followed by the inlined function body with the formal arguments
1942 * replaced by (expressions containing) these temporary variables.
1944 * The actual inlining is taken care of by the pet_inliner object.
1945 * This function merely calls set_inliner_arguments to tell
1946 * the pet_inliner about the actual arguments, extracts a pet_tree
1947 * from the body of the called function and then passes this pet_tree
1948 * to the pet_inliner.
1949 * The substitutions performed by the inliner are also applied
1950 * to the size expressions of the arrays declared in the inlined
1951 * function. These size expressions are not stored in the tree
1952 * itself, but rather in the size expression cache.
1954 * During the extraction of the function body, all variables names
1955 * that are declared in the calling function as well all variable
1956 * names that are known to be in use are considered to be in use
1957 * in the called function to ensure that there is no naming conflict.
1958 * Similarly, the additional names that are in use in the called function
1959 * are considered to be in use in the calling function as well.
1961 * The location of the pet_tree is reset to the call site to ensure
1962 * that the extent of the scop does not include the body of the called
1963 * function.
1965 __isl_give pet_tree *PetScan::extract_inlined_call(CallExpr *call,
1966 FunctionDecl *fd)
1968 int save_autodetect;
1969 pet_tree *tree;
1970 pet_loc *tree_loc;
1971 pet_inliner inliner(ctx, n_arg, ast_context);
1973 if (set_inliner_arguments(inliner, call, fd) < 0)
1974 return NULL;
1976 save_autodetect = options->autodetect;
1977 options->autodetect = 0;
1978 PetScan body_scan(PP, ast_context, fd, loc, options,
1979 isl_union_map_copy(value_bounds), independent);
1980 collect_declared_names();
1981 body_scan.add_new_used_names(declared_names);
1982 body_scan.add_new_used_names(used_names);
1983 tree = body_scan.extract(fd->getBody(), false);
1984 add_new_used_names(body_scan.used_names);
1985 options->autodetect = save_autodetect;
1987 tree_loc = construct_pet_loc(call->getSourceRange(), true);
1988 tree = pet_tree_set_loc(tree, tree_loc);
1990 substitute_array_sizes(tree, &inliner);
1992 return inliner.inline_tree(tree);
1995 /* Try and construct a pet_tree corresponding
1996 * to the expression statement "stmt".
1998 * If the outer expression is a function call and if the corresponding
1999 * function body is marked "inline", then return a pet_tree
2000 * corresponding to the inlined function.
2002 __isl_give pet_tree *PetScan::extract_expr_stmt(Stmt *stmt)
2004 pet_expr *expr;
2006 if (stmt->getStmtClass() == Stmt::CallExprClass) {
2007 CallExpr *call = cast<CallExpr>(stmt);
2008 FunctionDecl *fd = call->getDirectCallee();
2009 fd = pet_clang_find_function_decl_with_body(fd);
2010 if (fd && fd->isInlineSpecified())
2011 return extract_inlined_call(call, fd);
2014 expr = extract_expr(cast<Expr>(stmt));
2015 return extract(expr, stmt->getSourceRange(), true);
2018 /* Try and construct a pet_tree corresponding to "stmt".
2020 * If "stmt" is a compound statement, then "skip_declarations"
2021 * indicates whether we should skip initial declarations in the
2022 * compound statement.
2024 * If the constructed pet_tree is not a (possibly) partial representation
2025 * of "stmt", we update start and end of the pet_scop to those of "stmt".
2026 * In particular, if skip_declarations is set, then we may have skipped
2027 * declarations inside "stmt" and so the pet_scop may not represent
2028 * the entire "stmt".
2029 * Note that this function may be called with "stmt" referring to the entire
2030 * body of the function, including the outer braces. In such cases,
2031 * skip_declarations will be set and the braces will not be taken into
2032 * account in tree->loc.
2034 __isl_give pet_tree *PetScan::extract(Stmt *stmt, bool skip_declarations)
2036 pet_tree *tree;
2038 set_current_stmt(stmt);
2040 if (isa<Expr>(stmt))
2041 return extract_expr_stmt(cast<Expr>(stmt));
2043 switch (stmt->getStmtClass()) {
2044 case Stmt::WhileStmtClass:
2045 tree = extract(cast<WhileStmt>(stmt));
2046 break;
2047 case Stmt::ForStmtClass:
2048 tree = extract_for(cast<ForStmt>(stmt));
2049 break;
2050 case Stmt::IfStmtClass:
2051 tree = extract(cast<IfStmt>(stmt));
2052 break;
2053 case Stmt::CompoundStmtClass:
2054 tree = extract(cast<CompoundStmt>(stmt), skip_declarations);
2055 break;
2056 case Stmt::LabelStmtClass:
2057 tree = extract(cast<LabelStmt>(stmt));
2058 break;
2059 case Stmt::ContinueStmtClass:
2060 tree = pet_tree_new_continue(ctx);
2061 break;
2062 case Stmt::BreakStmtClass:
2063 tree = pet_tree_new_break(ctx);
2064 break;
2065 case Stmt::DeclStmtClass:
2066 tree = extract(cast<DeclStmt>(stmt));
2067 break;
2068 case Stmt::NullStmtClass:
2069 tree = pet_tree_new_block(ctx, 0, 0);
2070 break;
2071 case Stmt::ReturnStmtClass:
2072 tree = extract(cast<ReturnStmt>(stmt));
2073 break;
2074 default:
2075 report_unsupported_statement_type(stmt);
2076 return NULL;
2079 if (partial || skip_declarations)
2080 return tree;
2082 return update_loc(tree, stmt);
2085 /* Given a sequence of statements "stmt_range" of which the first "n_decl"
2086 * are declarations and of which the remaining statements are represented
2087 * by "tree", try and extend "tree" to include the last sequence of
2088 * the initial declarations that can be completely extracted.
2090 * We start collecting the initial declarations and start over
2091 * whenever we come across a declaration that we cannot extract.
2092 * If we have been able to extract any declarations, then we
2093 * copy over the contents of "tree" at the end of the declarations.
2094 * Otherwise, we simply return the original "tree".
2096 __isl_give pet_tree *PetScan::insert_initial_declarations(
2097 __isl_take pet_tree *tree, int n_decl, StmtRange stmt_range)
2099 StmtIterator i;
2100 pet_tree *res;
2101 int n_stmt;
2102 int is_block;
2103 int j;
2105 n_stmt = pet_tree_block_n_child(tree);
2106 is_block = pet_tree_block_get_block(tree);
2107 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2109 for (i = stmt_range.first; n_decl; ++i, --n_decl) {
2110 Stmt *child = *i;
2111 pet_tree *tree_i;
2113 tree_i = extract(child);
2114 if (tree_i && !partial) {
2115 res = pet_tree_block_add_child(res, tree_i);
2116 continue;
2118 pet_tree_free(tree_i);
2119 partial = false;
2120 if (pet_tree_block_n_child(res) == 0)
2121 continue;
2122 pet_tree_free(res);
2123 res = pet_tree_new_block(ctx, is_block, n_decl + n_stmt);
2126 if (pet_tree_block_n_child(res) == 0) {
2127 pet_tree_free(res);
2128 return tree;
2131 for (j = 0; j < n_stmt; ++j) {
2132 pet_tree *tree_i;
2134 tree_i = pet_tree_block_get_child(tree, j);
2135 res = pet_tree_block_add_child(res, tree_i);
2137 pet_tree_free(tree);
2139 return res;
2142 /* Try and construct a pet_tree corresponding to (part of)
2143 * a sequence of statements.
2145 * "block" is set if the sequence represents the children of
2146 * a compound statement.
2147 * "skip_declarations" is set if we should skip initial declarations
2148 * in the sequence of statements.
2149 * "parent" is the statement that has stmt_range as (some of) its children.
2151 * If autodetect is set, then we allow the extraction of only a subrange
2152 * of the sequence of statements. However, if there is at least one
2153 * kill and there is some subsequent statement for which we could not
2154 * construct a tree, then turn off the "block" property of the tree
2155 * such that no extra kill will be introduced at the end of the (partial)
2156 * block. If, on the other hand, the final range contains
2157 * no statements, then we discard the entire range.
2158 * If only a subrange of the sequence was extracted, but each statement
2159 * in the sequence was extracted completely, and if there are some
2160 * variable declarations in the sequence before or inside
2161 * the extracted subrange, then check if any of these variables are
2162 * not used after the extracted subrange. If so, add kills to these
2163 * variables.
2165 * If the entire range was extracted, apart from some initial declarations,
2166 * then we try and extend the range with the latest of those initial
2167 * declarations.
2169 __isl_give pet_tree *PetScan::extract(StmtRange stmt_range, bool block,
2170 bool skip_declarations, Stmt *parent)
2172 StmtIterator i;
2173 int j, skip;
2174 bool has_kills = false;
2175 bool partial_range = false;
2176 bool outer_partial = false;
2177 pet_tree *tree;
2178 SourceManager &SM = PP.getSourceManager();
2179 pet_killed_locals kl(SM);
2180 unsigned range_start, range_end;
2182 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j)
2185 tree = pet_tree_new_block(ctx, block, j);
2187 skip = 0;
2188 i = stmt_range.first;
2189 if (skip_declarations)
2190 for (; i != stmt_range.second; ++i) {
2191 if ((*i)->getStmtClass() != Stmt::DeclStmtClass)
2192 break;
2193 if (options->autodetect)
2194 kl.add_locals(cast<DeclStmt>(*i));
2195 ++skip;
2198 for (; i != stmt_range.second; ++i) {
2199 Stmt *child = *i;
2200 pet_tree *tree_i;
2202 tree_i = extract(child);
2203 if (pet_tree_block_n_child(tree) != 0 && partial) {
2204 pet_tree_free(tree_i);
2205 break;
2207 if (child->getStmtClass() == Stmt::DeclStmtClass) {
2208 if (options->autodetect)
2209 kl.add_locals(cast<DeclStmt>(child));
2210 if (tree_i && block)
2211 has_kills = true;
2213 if (options->autodetect) {
2214 if (tree_i) {
2215 range_end = getExpansionOffset(SM,
2216 child->getLocEnd());
2217 if (pet_tree_block_n_child(tree) == 0)
2218 range_start = getExpansionOffset(SM,
2219 child->getLocStart());
2220 tree = pet_tree_block_add_child(tree, tree_i);
2221 } else {
2222 partial_range = true;
2224 if (pet_tree_block_n_child(tree) != 0 && !tree_i)
2225 outer_partial = partial = true;
2226 } else {
2227 tree = pet_tree_block_add_child(tree, tree_i);
2230 if (partial || !tree)
2231 break;
2234 if (!tree)
2235 return NULL;
2237 if (partial) {
2238 if (has_kills)
2239 tree = pet_tree_block_set_block(tree, 0);
2240 if (outer_partial) {
2241 kl.remove_accessed_after(parent,
2242 range_start, range_end);
2243 tree = add_kills(tree, kl.locals);
2245 } else if (partial_range) {
2246 if (pet_tree_block_n_child(tree) == 0) {
2247 pet_tree_free(tree);
2248 return NULL;
2250 partial = true;
2251 } else if (skip > 0)
2252 tree = insert_initial_declarations(tree, skip, stmt_range);
2254 return tree;
2257 extern "C" {
2258 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2259 void *user);
2260 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2261 __isl_keep pet_context *pc, void *user);
2264 /* Construct a pet_expr that holds the sizes of the array accessed
2265 * by "access".
2266 * This function is used as a callback to pet_context_add_parameters,
2267 * which is also passed a pointer to the PetScan object.
2269 static __isl_give pet_expr *get_array_size(__isl_keep pet_expr *access,
2270 void *user)
2272 PetScan *ps = (PetScan *) user;
2273 isl_id *id;
2274 pet_expr *size;
2276 id = pet_expr_access_get_id(access);
2277 size = ps->get_array_size(id);
2278 isl_id_free(id);
2280 return size;
2283 /* Construct and return a pet_array corresponding to the variable
2284 * accessed by "access".
2285 * This function is used as a callback to pet_scop_from_pet_tree,
2286 * which is also passed a pointer to the PetScan object.
2288 static struct pet_array *extract_array(__isl_keep pet_expr *access,
2289 __isl_keep pet_context *pc, void *user)
2291 PetScan *ps = (PetScan *) user;
2292 isl_id *id;
2293 pet_array *array;
2295 id = pet_expr_access_get_id(access);
2296 array = ps->extract_array(id, NULL, pc);
2297 isl_id_free(id);
2299 return array;
2302 /* Extract a function summary from the body of "fd".
2304 * We extract a scop from the function body in a context with as
2305 * parameters the integer arguments of the function.
2306 * We turn off autodetection (in case it was set) to ensure that
2307 * the entire function body is considered.
2308 * We then collect the accessed array elements and attach them
2309 * to the corresponding array arguments, taking into account
2310 * that the function body may access members of array elements.
2311 * The function body is allowed to have a return statement at the end.
2313 * The reason for representing the integer arguments as parameters in
2314 * the context is that if we were to instead start with a context
2315 * with the function arguments as initial dimensions, then we would not
2316 * be able to refer to them from the array extents, without turning
2317 * array extents into maps.
2319 * The result is stored in the summary_cache cache so that we can reuse
2320 * it if this method gets called on the same function again later on.
2322 __isl_give pet_function_summary *PetScan::get_summary(FunctionDecl *fd)
2324 isl_space *space;
2325 isl_set *domain;
2326 pet_context *pc;
2327 pet_tree *tree;
2328 pet_function_summary *summary;
2329 unsigned n;
2330 ScopLoc loc;
2331 int save_autodetect;
2332 struct pet_scop *scop;
2333 int int_size;
2334 isl_union_set *may_read, *may_write, *must_write;
2335 isl_union_map *to_inner;
2337 if (summary_cache.find(fd) != summary_cache.end())
2338 return pet_function_summary_copy(summary_cache[fd]);
2340 space = isl_space_set_alloc(ctx, 0, 0);
2342 n = fd->getNumParams();
2343 summary = pet_function_summary_alloc(ctx, n);
2344 for (unsigned i = 0; i < n; ++i) {
2345 ParmVarDecl *parm = fd->getParamDecl(i);
2346 QualType type = parm->getType();
2347 isl_id *id;
2349 if (!type->isIntegerType())
2350 continue;
2351 id = pet_id_from_decl(ctx, parm);
2352 space = isl_space_insert_dims(space, isl_dim_param, 0, 1);
2353 space = isl_space_set_dim_id(space, isl_dim_param, 0,
2354 isl_id_copy(id));
2355 summary = pet_function_summary_set_int(summary, i, id);
2358 save_autodetect = options->autodetect;
2359 options->autodetect = 0;
2360 PetScan body_scan(PP, ast_context, fd, loc, options,
2361 isl_union_map_copy(value_bounds), independent);
2363 body_scan.return_root = fd->getBody();
2364 tree = body_scan.extract(fd->getBody(), false);
2366 domain = isl_set_universe(space);
2367 pc = pet_context_alloc(domain);
2368 pc = pet_context_add_parameters(pc, tree,
2369 &::get_array_size, &body_scan);
2370 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2371 scop = pet_scop_from_pet_tree(tree, int_size,
2372 &::extract_array, &body_scan, pc);
2373 scop = scan_arrays(scop, pc);
2374 may_read = isl_union_map_range(pet_scop_get_may_reads(scop));
2375 may_write = isl_union_map_range(pet_scop_get_may_writes(scop));
2376 must_write = isl_union_map_range(pet_scop_get_must_writes(scop));
2377 to_inner = pet_scop_compute_outer_to_inner(scop);
2378 pet_scop_free(scop);
2380 for (unsigned i = 0; i < n; ++i) {
2381 ParmVarDecl *parm = fd->getParamDecl(i);
2382 QualType type = parm->getType();
2383 struct pet_array *array;
2384 isl_space *space;
2385 isl_union_set *data_set;
2386 isl_union_set *may_read_i, *may_write_i, *must_write_i;
2388 if (pet_clang_array_depth(type) == 0)
2389 continue;
2391 array = body_scan.extract_array(parm, NULL, pc);
2392 space = array ? isl_set_get_space(array->extent) : NULL;
2393 pet_array_free(array);
2394 data_set = isl_union_set_from_set(isl_set_universe(space));
2395 data_set = isl_union_set_apply(data_set,
2396 isl_union_map_copy(to_inner));
2397 may_read_i = isl_union_set_intersect(
2398 isl_union_set_copy(may_read),
2399 isl_union_set_copy(data_set));
2400 may_write_i = isl_union_set_intersect(
2401 isl_union_set_copy(may_write),
2402 isl_union_set_copy(data_set));
2403 must_write_i = isl_union_set_intersect(
2404 isl_union_set_copy(must_write), data_set);
2405 summary = pet_function_summary_set_array(summary, i,
2406 may_read_i, may_write_i, must_write_i);
2409 isl_union_set_free(may_read);
2410 isl_union_set_free(may_write);
2411 isl_union_set_free(must_write);
2412 isl_union_map_free(to_inner);
2414 options->autodetect = save_autodetect;
2415 pet_context_free(pc);
2417 summary_cache[fd] = pet_function_summary_copy(summary);
2419 return summary;
2422 /* If "fd" has a function body, then extract a function summary from
2423 * this body and attach it to the call expression "expr".
2425 * Even if a function body is available, "fd" itself may point
2426 * to a declaration without function body. We therefore first
2427 * replace it by the declaration that comes with a body (if any).
2429 __isl_give pet_expr *PetScan::set_summary(__isl_take pet_expr *expr,
2430 FunctionDecl *fd)
2432 pet_function_summary *summary;
2434 if (!expr)
2435 return NULL;
2436 fd = pet_clang_find_function_decl_with_body(fd);
2437 if (!fd)
2438 return expr;
2440 summary = get_summary(fd);
2442 expr = pet_expr_call_set_summary(expr, summary);
2444 return expr;
2447 /* Extract a pet_scop from "tree".
2449 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
2450 * then add pet_arrays for all accessed arrays.
2451 * We populate the pet_context with assignments for all parameters used
2452 * inside "tree" or any of the size expressions for the arrays accessed
2453 * by "tree" so that they can be used in affine expressions.
2455 struct pet_scop *PetScan::extract_scop(__isl_take pet_tree *tree)
2457 int int_size;
2458 isl_set *domain;
2459 pet_context *pc;
2460 pet_scop *scop;
2462 int_size = size_in_bytes(ast_context, ast_context.IntTy);
2464 domain = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2465 pc = pet_context_alloc(domain);
2466 pc = pet_context_add_parameters(pc, tree, &::get_array_size, this);
2467 scop = pet_scop_from_pet_tree(tree, int_size,
2468 &::extract_array, this, pc);
2469 scop = scan_arrays(scop, pc);
2470 pet_context_free(pc);
2472 return scop;
2475 /* Add a call to __pencil_kill to the end of "tree" that kills
2476 * all the variables in "locals" and return the result.
2478 * No location is added to the kill because the most natural
2479 * location would lie outside the scop. Attaching such a location
2480 * to this tree would extend the scope of the final result
2481 * to include the location.
2483 __isl_give pet_tree *PetScan::add_kills(__isl_take pet_tree *tree,
2484 set<ValueDecl *> locals)
2486 int i;
2487 pet_expr *expr;
2488 pet_tree *kill, *block;
2489 set<ValueDecl *>::iterator it;
2491 if (locals.size() == 0)
2492 return tree;
2493 expr = pet_expr_new_call(ctx, "__pencil_kill", locals.size());
2494 i = 0;
2495 for (it = locals.begin(); it != locals.end(); ++it) {
2496 pet_expr *arg;
2497 arg = extract_access_expr(*it);
2498 expr = pet_expr_set_arg(expr, i++, arg);
2500 kill = pet_tree_new_expr(expr);
2501 block = pet_tree_new_block(ctx, 0, 2);
2502 block = pet_tree_block_add_child(block, tree);
2503 block = pet_tree_block_add_child(block, kill);
2505 return block;
2508 /* Check if the scop marked by the user is exactly this Stmt
2509 * or part of this Stmt.
2510 * If so, return a pet_scop corresponding to the marked region.
2511 * Otherwise, return NULL.
2513 * If the scop is not further nested inside a child of "stmt",
2514 * then check if there are any variable declarations before the scop
2515 * inside "stmt". If so, and if these variables are not used
2516 * after the scop, then add kills to the variables.
2518 * If the scop starts in the middle of one of the children, without
2519 * also ending in that child, then report an error.
2521 struct pet_scop *PetScan::scan(Stmt *stmt)
2523 SourceManager &SM = PP.getSourceManager();
2524 unsigned start_off, end_off;
2525 pet_tree *tree;
2527 start_off = getExpansionOffset(SM, stmt->getLocStart());
2528 end_off = getExpansionOffset(SM, stmt->getLocEnd());
2530 if (start_off > loc.end)
2531 return NULL;
2532 if (end_off < loc.start)
2533 return NULL;
2535 if (start_off >= loc.start && end_off <= loc.end)
2536 return extract_scop(extract(stmt));
2538 pet_killed_locals kl(SM);
2539 StmtIterator start;
2540 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
2541 Stmt *child = *start;
2542 if (!child)
2543 continue;
2544 start_off = getExpansionOffset(SM, child->getLocStart());
2545 end_off = getExpansionOffset(SM, child->getLocEnd());
2546 if (start_off < loc.start && end_off >= loc.end)
2547 return scan(child);
2548 if (start_off >= loc.start)
2549 break;
2550 if (loc.start < end_off) {
2551 report_unbalanced_pragmas(loc.scop, loc.endscop);
2552 return NULL;
2554 if (isa<DeclStmt>(child))
2555 kl.add_locals(cast<DeclStmt>(child));
2558 StmtIterator end;
2559 for (end = start; end != stmt->child_end(); ++end) {
2560 Stmt *child = *end;
2561 start_off = SM.getFileOffset(child->getLocStart());
2562 if (start_off >= loc.end)
2563 break;
2566 kl.remove_accessed_after(stmt, loc.start, loc.end);
2568 tree = extract(StmtRange(start, end), false, false, stmt);
2569 tree = add_kills(tree, kl.locals);
2570 return extract_scop(tree);
2573 /* Set the size of index "pos" of "array" to "size".
2574 * In particular, add a constraint of the form
2576 * i_pos < size
2578 * to array->extent and a constraint of the form
2580 * size >= 0
2582 * to array->context.
2584 * The domain of "size" is assumed to be zero-dimensional.
2586 static struct pet_array *update_size(struct pet_array *array, int pos,
2587 __isl_take isl_pw_aff *size)
2589 isl_set *valid;
2590 isl_set *univ;
2591 isl_set *bound;
2592 isl_space *dim;
2593 isl_aff *aff;
2594 isl_pw_aff *index;
2595 isl_id *id;
2597 if (!array)
2598 goto error;
2600 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
2601 array->context = isl_set_intersect(array->context, valid);
2603 dim = isl_set_get_space(array->extent);
2604 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2605 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2606 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2607 index = isl_pw_aff_alloc(univ, aff);
2609 size = isl_pw_aff_add_dims(size, isl_dim_in,
2610 isl_set_dim(array->extent, isl_dim_set));
2611 id = isl_set_get_tuple_id(array->extent);
2612 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2613 bound = isl_pw_aff_lt_set(index, size);
2615 array->extent = isl_set_intersect(array->extent, bound);
2617 if (!array->context || !array->extent)
2618 return pet_array_free(array);
2620 return array;
2621 error:
2622 isl_pw_aff_free(size);
2623 return NULL;
2626 #ifdef HAVE_DECAYEDTYPE
2628 /* If "qt" is a decayed type, then set *decayed to true and
2629 * return the original type.
2631 static QualType undecay(QualType qt, bool *decayed)
2633 const Type *type = qt.getTypePtr();
2635 *decayed = isa<DecayedType>(type);
2636 if (*decayed)
2637 qt = cast<DecayedType>(type)->getOriginalType();
2638 return qt;
2641 #else
2643 /* If "qt" is a decayed type, then set *decayed to true and
2644 * return the original type.
2645 * Since this version of clang does not define a DecayedType,
2646 * we cannot obtain the original type even if it had been decayed and
2647 * we set *decayed to false.
2649 static QualType undecay(QualType qt, bool *decayed)
2651 *decayed = false;
2652 return qt;
2655 #endif
2657 /* Figure out the size of the array at position "pos" and all
2658 * subsequent positions from "qt" and update the corresponding
2659 * argument of "expr" accordingly.
2661 * The initial type (when pos is zero) may be a pointer type decayed
2662 * from an array type, if this initial type is the type of a function
2663 * argument. This only happens if the original array type has
2664 * a constant size in the outer dimension as otherwise we get
2665 * a VariableArrayType. Try and obtain this original type (if available) and
2666 * take the outer array size into account if it was marked static.
2668 __isl_give pet_expr *PetScan::set_upper_bounds(__isl_take pet_expr *expr,
2669 QualType qt, int pos)
2671 const ArrayType *atype;
2672 pet_expr *size;
2673 bool decayed = false;
2675 if (!expr)
2676 return NULL;
2678 if (pos == 0)
2679 qt = undecay(qt, &decayed);
2681 if (qt->isPointerType()) {
2682 qt = qt->getPointeeType();
2683 return set_upper_bounds(expr, qt, pos + 1);
2685 if (!qt->isArrayType())
2686 return expr;
2688 qt = qt->getCanonicalTypeInternal();
2689 atype = cast<ArrayType>(qt.getTypePtr());
2691 if (decayed && atype->getSizeModifier() != ArrayType::Static) {
2692 qt = atype->getElementType();
2693 return set_upper_bounds(expr, qt, pos + 1);
2696 if (qt->isConstantArrayType()) {
2697 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2698 size = extract_expr(ca->getSize());
2699 expr = pet_expr_set_arg(expr, pos, size);
2700 } else if (qt->isVariableArrayType()) {
2701 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2702 size = extract_expr(vla->getSizeExpr());
2703 expr = pet_expr_set_arg(expr, pos, size);
2706 qt = atype->getElementType();
2708 return set_upper_bounds(expr, qt, pos + 1);
2711 /* Construct a pet_expr that holds the sizes of the array represented by "id".
2712 * The returned expression is a call expression with as arguments
2713 * the sizes in each dimension. If we are unable to derive the size
2714 * in a given dimension, then the corresponding argument is set to infinity.
2715 * In fact, we initialize all arguments to infinity and then update
2716 * them if we are able to figure out the size.
2718 * The result is stored in the id_size cache so that it can be reused
2719 * if this method is called on the same array identifier later.
2720 * The result is also stored in the type_size cache in case
2721 * it gets called on a different array identifier with the same type.
2723 __isl_give pet_expr *PetScan::get_array_size(__isl_keep isl_id *id)
2725 QualType qt = pet_id_get_array_type(id);
2726 int depth;
2727 pet_expr *expr, *inf;
2728 const Type *type = qt.getTypePtr();
2729 isl_maybe_pet_expr m;
2731 m = isl_id_to_pet_expr_try_get(id_size, id);
2732 if (m.valid < 0 || m.valid)
2733 return m.value;
2734 if (type_size.find(type) != type_size.end())
2735 return pet_expr_copy(type_size[type]);
2737 depth = pet_clang_array_depth(qt);
2738 inf = pet_expr_new_int(isl_val_infty(ctx));
2739 expr = pet_expr_new_call(ctx, "bounds", depth);
2740 for (int i = 0; i < depth; ++i)
2741 expr = pet_expr_set_arg(expr, i, pet_expr_copy(inf));
2742 pet_expr_free(inf);
2744 expr = set_upper_bounds(expr, qt, 0);
2745 type_size[type] = pet_expr_copy(expr);
2746 id_size = isl_id_to_pet_expr_set(id_size, isl_id_copy(id),
2747 pet_expr_copy(expr));
2749 return expr;
2752 /* Set the array size of the array identified by "id" to "size",
2753 * replacing any previously stored value.
2755 void PetScan::set_array_size(__isl_take isl_id *id, __isl_take pet_expr *size)
2757 id_size = isl_id_to_pet_expr_set(id_size, id, size);
2760 /* Does "expr" represent the "integer" infinity?
2762 static int is_infty(__isl_keep pet_expr *expr)
2764 isl_val *v;
2765 int res;
2767 if (pet_expr_get_type(expr) != pet_expr_int)
2768 return 0;
2769 v = pet_expr_int_get_val(expr);
2770 res = isl_val_is_infty(v);
2771 isl_val_free(v);
2773 return res;
2776 /* Figure out the dimensions of an array "array" and
2777 * update "array" accordingly.
2779 * We first construct a pet_expr that holds the sizes of the array
2780 * in each dimension. The resulting expression may containing
2781 * infinity values for dimension where we are unable to derive
2782 * a size expression.
2784 * The arguments of the size expression that have a value different from
2785 * infinity are then converted to an affine expression
2786 * within the context "pc" and incorporated into the size of "array".
2787 * If we are unable to convert a size expression to an affine expression or
2788 * if the size is not a (symbolic) constant,
2789 * then we leave the corresponding size of "array" untouched.
2791 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2792 __isl_keep pet_context *pc)
2794 int n;
2795 isl_id *id;
2796 pet_expr *expr;
2798 if (!array)
2799 return NULL;
2801 id = isl_set_get_tuple_id(array->extent);
2802 expr = get_array_size(id);
2803 isl_id_free(id);
2805 n = pet_expr_get_n_arg(expr);
2806 for (int i = 0; i < n; ++i) {
2807 pet_expr *arg;
2808 isl_pw_aff *size;
2810 arg = pet_expr_get_arg(expr, i);
2811 if (!is_infty(arg)) {
2812 int dim;
2814 size = pet_expr_extract_affine(arg, pc);
2815 dim = isl_pw_aff_dim(size, isl_dim_in);
2816 if (!size)
2817 array = pet_array_free(array);
2818 else if (isl_pw_aff_involves_nan(size) ||
2819 isl_pw_aff_involves_dims(size, isl_dim_in, 0, dim))
2820 isl_pw_aff_free(size);
2821 else {
2822 size = isl_pw_aff_drop_dims(size,
2823 isl_dim_in, 0, dim);
2824 array = update_size(array, i, size);
2827 pet_expr_free(arg);
2829 pet_expr_free(expr);
2831 return array;
2834 /* Does "decl" have a definition that we can keep track of in a pet_type?
2836 static bool has_printable_definition(RecordDecl *decl)
2838 if (!decl->getDeclName())
2839 return false;
2840 return decl->getLexicalDeclContext() == decl->getDeclContext();
2843 /* Add all TypedefType objects that appear when dereferencing "type"
2844 * to "types".
2846 static void insert_intermediate_typedefs(PetTypes *types, QualType type)
2848 type = pet_clang_base_or_typedef_type(type);
2849 while (isa<TypedefType>(type)) {
2850 const TypedefType *tt;
2852 tt = cast<TypedefType>(type);
2853 types->insert(tt->getDecl());
2854 type = tt->desugar();
2855 type = pet_clang_base_or_typedef_type(type);
2859 /* Construct and return a pet_array corresponding to the variable
2860 * represented by "id".
2861 * In particular, initialize array->extent to
2863 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2865 * and then call set_upper_bounds to set the upper bounds on the indices
2866 * based on the type of the variable. The upper bounds are converted
2867 * to affine expressions within the context "pc".
2869 * If the base type is that of a record with a top-level definition or
2870 * of a typedef and if "types" is not null, then the RecordDecl or
2871 * TypedefType corresponding to the type, as well as any intermediate
2872 * TypedefType, is added to "types".
2874 * If the base type is that of a record with no top-level definition,
2875 * then we replace it by "<subfield>".
2877 * If the variable is a scalar, i.e., a zero-dimensional array,
2878 * then the "const" qualifier, if any, is removed from the base type.
2879 * This makes it easier for users of pet to turn initializations
2880 * into assignments.
2882 struct pet_array *PetScan::extract_array(__isl_keep isl_id *id,
2883 PetTypes *types, __isl_keep pet_context *pc)
2885 struct pet_array *array;
2886 QualType qt = pet_id_get_array_type(id);
2887 int depth = pet_clang_array_depth(qt);
2888 QualType base = pet_clang_base_type(qt);
2889 string name;
2890 isl_space *space;
2892 array = isl_calloc_type(ctx, struct pet_array);
2893 if (!array)
2894 return NULL;
2896 space = isl_space_set_alloc(ctx, 0, depth);
2897 space = isl_space_set_tuple_id(space, isl_dim_set, isl_id_copy(id));
2899 array->extent = isl_set_nat_universe(space);
2901 space = isl_space_params_alloc(ctx, 0);
2902 array->context = isl_set_universe(space);
2904 array = set_upper_bounds(array, pc);
2905 if (!array)
2906 return NULL;
2908 if (depth == 0)
2909 base.removeLocalConst();
2910 name = base.getAsString();
2912 if (types) {
2913 insert_intermediate_typedefs(types, qt);
2914 if (isa<TypedefType>(base)) {
2915 types->insert(cast<TypedefType>(base)->getDecl());
2916 } else if (base->isRecordType()) {
2917 RecordDecl *decl = pet_clang_record_decl(base);
2918 TypedefNameDecl *typedecl;
2919 typedecl = decl->getTypedefNameForAnonDecl();
2920 if (typedecl)
2921 types->insert(typedecl);
2922 else if (has_printable_definition(decl))
2923 types->insert(decl);
2924 else
2925 name = "<subfield>";
2929 array->element_type = strdup(name.c_str());
2930 array->element_is_record = base->isRecordType();
2931 array->element_size = size_in_bytes(ast_context, base);
2933 return array;
2936 /* Construct and return a pet_array corresponding to the variable "decl".
2938 struct pet_array *PetScan::extract_array(ValueDecl *decl,
2939 PetTypes *types, __isl_keep pet_context *pc)
2941 isl_id *id;
2942 pet_array *array;
2944 id = pet_id_from_decl(ctx, decl);
2945 array = extract_array(id, types, pc);
2946 isl_id_free(id);
2948 return array;
2951 /* Construct and return a pet_array corresponding to the sequence
2952 * of declarations represented by "decls".
2953 * The upper bounds of the array are converted to affine expressions
2954 * within the context "pc".
2955 * If the sequence contains a single declaration, then it corresponds
2956 * to a simple array access. Otherwise, it corresponds to a member access,
2957 * with the declaration for the substructure following that of the containing
2958 * structure in the sequence of declarations.
2959 * We start with the outermost substructure and then combine it with
2960 * information from the inner structures.
2962 * Additionally, keep track of all required types in "types".
2964 struct pet_array *PetScan::extract_array(__isl_keep isl_id_list *decls,
2965 PetTypes *types, __isl_keep pet_context *pc)
2967 int i, n;
2968 isl_id *id;
2969 struct pet_array *array;
2971 id = isl_id_list_get_id(decls, 0);
2972 array = extract_array(id, types, pc);
2973 isl_id_free(id);
2975 n = isl_id_list_n_id(decls);
2976 for (i = 1; i < n; ++i) {
2977 struct pet_array *parent;
2978 const char *base_name, *field_name;
2979 char *product_name;
2981 parent = array;
2982 id = isl_id_list_get_id(decls, i);
2983 array = extract_array(id, types, pc);
2984 isl_id_free(id);
2985 if (!array)
2986 return pet_array_free(parent);
2988 base_name = isl_set_get_tuple_name(parent->extent);
2989 field_name = isl_set_get_tuple_name(array->extent);
2990 product_name = pet_array_member_access_name(ctx,
2991 base_name, field_name);
2993 array->extent = isl_set_product(isl_set_copy(parent->extent),
2994 array->extent);
2995 if (product_name)
2996 array->extent = isl_set_set_tuple_name(array->extent,
2997 product_name);
2998 array->context = isl_set_intersect(array->context,
2999 isl_set_copy(parent->context));
3001 pet_array_free(parent);
3002 free(product_name);
3004 if (!array->extent || !array->context || !product_name)
3005 return pet_array_free(array);
3008 return array;
3011 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3012 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
3013 std::set<TypeDecl *> &types_done);
3014 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3015 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
3016 std::set<TypeDecl *> &types_done);
3018 /* For each of the fields of "decl" that is itself a record type
3019 * or a typedef, or an array of such type, add a corresponding pet_type
3020 * to "scop".
3022 static struct pet_scop *add_field_types(isl_ctx *ctx, struct pet_scop *scop,
3023 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
3024 std::set<TypeDecl *> &types_done)
3026 RecordDecl::field_iterator it;
3028 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
3029 QualType type = it->getType();
3031 type = pet_clang_base_or_typedef_type(type);
3032 if (isa<TypedefType>(type)) {
3033 TypedefNameDecl *typedefdecl;
3035 typedefdecl = cast<TypedefType>(type)->getDecl();
3036 scop = add_type(ctx, scop, typedefdecl,
3037 PP, types, types_done);
3038 } else if (type->isRecordType()) {
3039 RecordDecl *record;
3041 record = pet_clang_record_decl(type);
3042 scop = add_type(ctx, scop, record,
3043 PP, types, types_done);
3047 return scop;
3050 /* Add a pet_type corresponding to "decl" to "scop", provided
3051 * it is a member of types.records and it has not been added before
3052 * (i.e., it is not a member of "types_done").
3054 * Since we want the user to be able to print the types
3055 * in the order in which they appear in the scop, we need to
3056 * make sure that types of fields in a structure appear before
3057 * that structure. We therefore call ourselves recursively
3058 * through add_field_types on the types of all record subfields.
3060 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3061 RecordDecl *decl, Preprocessor &PP, PetTypes &types,
3062 std::set<TypeDecl *> &types_done)
3064 string s;
3065 llvm::raw_string_ostream S(s);
3067 if (types.records.find(decl) == types.records.end())
3068 return scop;
3069 if (types_done.find(decl) != types_done.end())
3070 return scop;
3072 add_field_types(ctx, scop, decl, PP, types, types_done);
3074 if (strlen(decl->getName().str().c_str()) == 0)
3075 return scop;
3077 decl->print(S, PrintingPolicy(PP.getLangOpts()));
3078 S.str();
3080 scop->types[scop->n_type] = pet_type_alloc(ctx,
3081 decl->getName().str().c_str(), s.c_str());
3082 if (!scop->types[scop->n_type])
3083 return pet_scop_free(scop);
3085 types_done.insert(decl);
3087 scop->n_type++;
3089 return scop;
3092 /* Add a pet_type corresponding to "decl" to "scop", provided
3093 * it is a member of types.typedefs and it has not been added before
3094 * (i.e., it is not a member of "types_done").
3096 * If the underlying type is a structure, then we print the typedef
3097 * ourselves since clang does not print the definition of the structure
3098 * in the typedef. We also make sure in this case that the types of
3099 * the fields in the structure are added first.
3100 * Since the definition of the structure also gets printed this way,
3101 * add it to types_done such that it will not be printed again,
3102 * not even without the typedef.
3104 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
3105 TypedefNameDecl *decl, Preprocessor &PP, PetTypes &types,
3106 std::set<TypeDecl *> &types_done)
3108 string s;
3109 llvm::raw_string_ostream S(s);
3110 QualType qt = decl->getUnderlyingType();
3112 if (types.typedefs.find(decl) == types.typedefs.end())
3113 return scop;
3114 if (types_done.find(decl) != types_done.end())
3115 return scop;
3117 if (qt->isRecordType()) {
3118 RecordDecl *rec = pet_clang_record_decl(qt);
3120 add_field_types(ctx, scop, rec, PP, types, types_done);
3121 S << "typedef ";
3122 rec->print(S, PrintingPolicy(PP.getLangOpts()));
3123 S << " ";
3124 S << decl->getName();
3125 types_done.insert(rec);
3126 } else {
3127 decl->print(S, PrintingPolicy(PP.getLangOpts()));
3129 S.str();
3131 scop->types[scop->n_type] = pet_type_alloc(ctx,
3132 decl->getName().str().c_str(), s.c_str());
3133 if (!scop->types[scop->n_type])
3134 return pet_scop_free(scop);
3136 types_done.insert(decl);
3138 scop->n_type++;
3140 return scop;
3143 /* Construct a list of pet_arrays, one for each array (or scalar)
3144 * accessed inside "scop", add this list to "scop" and return the result.
3145 * The upper bounds of the arrays are converted to affine expressions
3146 * within the context "pc".
3148 * The context of "scop" is updated with the intersection of
3149 * the contexts of all arrays, i.e., constraints on the parameters
3150 * that ensure that the arrays have a valid (non-negative) size.
3152 * If any of the extracted arrays refers to a member access or
3153 * has a typedef'd type as base type,
3154 * then also add the required types to "scop".
3155 * The typedef types are printed first because their definitions
3156 * may include the definition of a struct and these struct definitions
3157 * should not be printed separately. While the typedef definition
3158 * is being printed, the struct is marked as having been printed as well,
3159 * such that the later printing of the struct by itself can be prevented.
3161 * If the sequence of nested array declarations from which the pet_array
3162 * is extracted appears as the prefix of some other sequence,
3163 * then the pet_array is marked as "outer".
3164 * The arrays that already appear in scop->arrays at the start of
3165 * this function are assumed to be simple arrays, so they are not marked
3166 * as outer.
3168 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop,
3169 __isl_keep pet_context *pc)
3171 int i, n;
3172 array_desc_set arrays, has_sub;
3173 array_desc_set::iterator it;
3174 PetTypes types;
3175 std::set<TypeDecl *> types_done;
3176 std::set<clang::RecordDecl *, less_name>::iterator records_it;
3177 std::set<clang::TypedefNameDecl *, less_name>::iterator typedefs_it;
3178 int n_array;
3179 struct pet_array **scop_arrays;
3181 if (!scop)
3182 return NULL;
3184 pet_scop_collect_arrays(scop, arrays);
3185 if (arrays.size() == 0)
3186 return scop;
3188 n_array = scop->n_array;
3190 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3191 n_array + arrays.size());
3192 if (!scop_arrays)
3193 goto error;
3194 scop->arrays = scop_arrays;
3196 for (it = arrays.begin(); it != arrays.end(); ++it) {
3197 isl_id_list *list = isl_id_list_copy(*it);
3198 int n = isl_id_list_n_id(list);
3199 list = isl_id_list_drop(list, n - 1, 1);
3200 has_sub.insert(list);
3203 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3204 struct pet_array *array;
3205 array = extract_array(*it, &types, pc);
3206 scop->arrays[n_array + i] = array;
3207 if (!scop->arrays[n_array + i])
3208 goto error;
3209 if (has_sub.find(*it) != has_sub.end())
3210 array->outer = 1;
3211 scop->n_array++;
3212 scop->context = isl_set_intersect(scop->context,
3213 isl_set_copy(array->context));
3214 if (!scop->context)
3215 goto error;
3218 n = types.records.size() + types.typedefs.size();
3219 if (n == 0)
3220 return scop;
3222 scop->types = isl_alloc_array(ctx, struct pet_type *, n);
3223 if (!scop->types)
3224 goto error;
3226 for (typedefs_it = types.typedefs.begin();
3227 typedefs_it != types.typedefs.end(); ++typedefs_it)
3228 scop = add_type(ctx, scop, *typedefs_it, PP, types, types_done);
3230 for (records_it = types.records.begin();
3231 records_it != types.records.end(); ++records_it)
3232 scop = add_type(ctx, scop, *records_it, PP, types, types_done);
3234 return scop;
3235 error:
3236 pet_scop_free(scop);
3237 return NULL;
3240 /* Bound all parameters in scop->context to the possible values
3241 * of the corresponding C variable.
3243 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
3245 int n;
3247 if (!scop)
3248 return NULL;
3250 n = isl_set_dim(scop->context, isl_dim_param);
3251 for (int i = 0; i < n; ++i) {
3252 isl_id *id;
3253 ValueDecl *decl;
3255 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
3256 if (pet_nested_in_id(id)) {
3257 isl_id_free(id);
3258 isl_die(isl_set_get_ctx(scop->context),
3259 isl_error_internal,
3260 "unresolved nested parameter", goto error);
3262 decl = pet_id_get_decl(id);
3263 isl_id_free(id);
3265 scop->context = set_parameter_bounds(scop->context, i, decl);
3267 if (!scop->context)
3268 goto error;
3271 return scop;
3272 error:
3273 pet_scop_free(scop);
3274 return NULL;
3277 /* Construct a pet_scop from the given function.
3279 * If the scop was delimited by scop and endscop pragmas, then we override
3280 * the file offsets by those derived from the pragmas.
3282 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3284 pet_scop *scop;
3285 Stmt *stmt;
3287 stmt = fd->getBody();
3289 if (options->autodetect) {
3290 set_current_stmt(stmt);
3291 scop = extract_scop(extract(stmt, true));
3292 } else {
3293 current_line = loc.start_line;
3294 scop = scan(stmt);
3295 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
3297 scop = add_parameter_bounds(scop);
3298 scop = pet_scop_gist(scop, value_bounds);
3300 return scop;
3303 /* Update this->last_line and this->current_line based on the fact
3304 * that we are about to consider "stmt".
3306 void PetScan::set_current_stmt(Stmt *stmt)
3308 SourceLocation loc = stmt->getLocStart();
3309 SourceManager &SM = PP.getSourceManager();
3311 last_line = current_line;
3312 current_line = SM.getExpansionLineNumber(loc);
3315 /* Is the current statement marked by an independent pragma?
3316 * That is, is there an independent pragma on a line between
3317 * the line of the current statement and the line of the previous statement.
3318 * The search is not implemented very efficiently. We currently
3319 * assume that there are only a few independent pragmas, if any.
3321 bool PetScan::is_current_stmt_marked_independent()
3323 for (unsigned i = 0; i < independent.size(); ++i) {
3324 unsigned line = independent[i].line;
3326 if (last_line < line && line < current_line)
3327 return true;
3330 return false;