2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2015 Ecole Normale Superieure. All rights reserved.
4 * Copyright 2015-2016 Sven Verdoolaege. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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
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>
51 #include <isl/space.h>
54 #include <isl/union_set.h>
63 #include "killed_locals.h"
68 #include "scop_plus.h"
69 #include "substituter.h"
71 #include "tree2scop.h"
74 using namespace clang
;
76 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
86 return pet_op_post_inc
;
88 return pet_op_post_dec
;
90 return pet_op_pre_inc
;
92 return pet_op_pre_dec
;
98 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
102 return pet_op_add_assign
;
104 return pet_op_sub_assign
;
106 return pet_op_mul_assign
;
108 return pet_op_div_assign
;
110 return pet_op_assign
;
152 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
153 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
155 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
156 SourceLocation(), var
, false, var
->getInnerLocStart(),
157 var
->getType(), VK_LValue
);
159 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
160 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
162 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
163 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
167 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
169 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
170 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
174 #ifdef GETTYPEINFORETURNSTYPEINFO
176 static int size_in_bytes(ASTContext
&context
, QualType type
)
178 return context
.getTypeInfo(type
).Width
/ 8;
183 static int size_in_bytes(ASTContext
&context
, QualType type
)
185 return context
.getTypeInfo(type
).first
/ 8;
190 /* Check if the element type corresponding to the given array type
191 * has a const qualifier.
193 static bool const_base(QualType qt
)
195 const Type
*type
= qt
.getTypePtr();
197 if (type
->isPointerType())
198 return const_base(type
->getPointeeType());
199 if (type
->isArrayType()) {
200 const ArrayType
*atype
;
201 type
= type
->getCanonicalTypeInternal().getTypePtr();
202 atype
= cast
<ArrayType
>(type
);
203 return const_base(atype
->getElementType());
206 return qt
.isConstQualified();
211 std::map
<const Type
*, pet_expr
*>::iterator it
;
212 std::map
<FunctionDecl
*, pet_function_summary
*>::iterator it_s
;
214 for (it
= type_size
.begin(); it
!= type_size
.end(); ++it
)
215 pet_expr_free(it
->second
);
216 for (it_s
= summary_cache
.begin(); it_s
!= summary_cache
.end(); ++it_s
)
217 pet_function_summary_free(it_s
->second
);
219 isl_union_map_free(value_bounds
);
222 /* Report a diagnostic on the range "range", unless autodetect is set.
224 void PetScan::report(SourceRange range
, unsigned id
)
226 if (options
->autodetect
)
229 SourceLocation loc
= range
.getBegin();
230 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
231 DiagnosticBuilder B
= diag
.Report(loc
, id
) << range
;
234 /* Report a diagnostic on "stmt", unless autodetect is set.
236 void PetScan::report(Stmt
*stmt
, unsigned id
)
238 report(stmt
->getSourceRange(), id
);
241 /* Report a diagnostic on "decl", unless autodetect is set.
243 void PetScan::report(Decl
*decl
, unsigned id
)
245 report(decl
->getSourceRange(), id
);
248 /* Called if we found something we (currently) cannot handle.
249 * We'll provide more informative warnings later.
251 * We only actually complain if autodetect is false.
253 void PetScan::unsupported(Stmt
*stmt
)
255 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
256 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
261 /* Report an unsupported unary operator, unless autodetect is set.
263 void PetScan::report_unsupported_unary_operator(Stmt
*stmt
)
265 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
266 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
267 "this type of unary operator is not supported");
271 /* Report an unsupported statement type, unless autodetect is set.
273 void PetScan::report_unsupported_statement_type(Stmt
*stmt
)
275 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
276 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
277 "this type of statement is not supported");
281 /* Report a missing prototype, unless autodetect is set.
283 void PetScan::report_prototype_required(Stmt
*stmt
)
285 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
286 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
287 "prototype required");
291 /* Report a missing increment, unless autodetect is set.
293 void PetScan::report_missing_increment(Stmt
*stmt
)
295 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
296 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
297 "missing increment");
301 /* Report a missing summary function, unless autodetect is set.
303 void PetScan::report_missing_summary_function(Stmt
*stmt
)
305 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
306 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
307 "missing summary function");
311 /* Report a missing summary function body, unless autodetect is set.
313 void PetScan::report_missing_summary_function_body(Stmt
*stmt
)
315 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
316 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
317 "missing summary function body");
321 /* Report an unsupported argument in a call to an inlined function,
322 * unless autodetect is set.
324 void PetScan::report_unsupported_inline_function_argument(Stmt
*stmt
)
326 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
327 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
328 "unsupported inline function call argument");
332 /* Report an unsupported type of declaration, unless autodetect is set.
334 void PetScan::report_unsupported_declaration(Decl
*decl
)
336 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
337 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
338 "unsupported declaration");
342 /* Extract an integer from "val", which is assumed to be non-negative.
344 static __isl_give isl_val
*extract_unsigned(isl_ctx
*ctx
,
345 const llvm::APInt
&val
)
348 const uint64_t *data
;
350 data
= val
.getRawData();
351 n
= val
.getNumWords();
352 return isl_val_int_from_chunks(ctx
, n
, sizeof(uint64_t), data
);
355 /* Extract an integer from "val". If "is_signed" is set, then "val"
356 * is signed. Otherwise it it unsigned.
358 static __isl_give isl_val
*extract_int(isl_ctx
*ctx
, bool is_signed
,
361 int is_negative
= is_signed
&& val
.isNegative();
367 v
= extract_unsigned(ctx
, val
);
374 /* Extract an integer from "expr".
376 __isl_give isl_val
*PetScan::extract_int(isl_ctx
*ctx
, IntegerLiteral
*expr
)
378 const Type
*type
= expr
->getType().getTypePtr();
379 bool is_signed
= type
->hasSignedIntegerRepresentation();
381 return ::extract_int(ctx
, is_signed
, expr
->getValue());
384 /* Extract an integer from "expr".
385 * Return NULL if "expr" does not (obviously) represent an integer.
387 __isl_give isl_val
*PetScan::extract_int(clang::ParenExpr
*expr
)
389 return extract_int(expr
->getSubExpr());
392 /* Extract an integer from "expr".
393 * Return NULL if "expr" does not (obviously) represent an integer.
395 __isl_give isl_val
*PetScan::extract_int(clang::Expr
*expr
)
397 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
398 return extract_int(ctx
, cast
<IntegerLiteral
>(expr
));
399 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
400 return extract_int(cast
<ParenExpr
>(expr
));
406 /* Extract a pet_expr from the APInt "val", which is assumed
407 * to be non-negative.
409 __isl_give pet_expr
*PetScan::extract_expr(const llvm::APInt
&val
)
411 return pet_expr_new_int(extract_unsigned(ctx
, val
));
414 /* Return the number of bits needed to represent the type of "decl",
415 * if it is an integer type. Otherwise return 0.
416 * If qt is signed then return the opposite of the number of bits.
418 static int get_type_size(ValueDecl
*decl
)
420 return pet_clang_get_type_size(decl
->getType(), decl
->getASTContext());
423 /* Bound parameter "pos" of "set" to the possible values of "decl".
425 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
426 unsigned pos
, ValueDecl
*decl
)
432 ctx
= isl_set_get_ctx(set
);
433 type_size
= get_type_size(decl
);
435 isl_die(ctx
, isl_error_invalid
, "not an integer type",
436 return isl_set_free(set
));
438 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
439 bound
= isl_val_int_from_ui(ctx
, type_size
);
440 bound
= isl_val_2exp(bound
);
441 bound
= isl_val_sub_ui(bound
, 1);
442 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
, bound
);
444 bound
= isl_val_int_from_ui(ctx
, -type_size
- 1);
445 bound
= isl_val_2exp(bound
);
446 bound
= isl_val_sub_ui(bound
, 1);
447 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
,
448 isl_val_copy(bound
));
449 bound
= isl_val_neg(bound
);
450 bound
= isl_val_sub_ui(bound
, 1);
451 set
= isl_set_lower_bound_val(set
, isl_dim_param
, pos
, bound
);
457 __isl_give pet_expr
*PetScan::extract_index_expr(ImplicitCastExpr
*expr
)
459 return extract_index_expr(expr
->getSubExpr());
462 /* Return the depth of the array accessed by the index expression "index".
463 * If "index" is an affine expression, i.e., if it does not access
464 * any array, then return 1.
465 * If "index" represent a member access, i.e., if its range is a wrapped
466 * relation, then return the sum of the depth of the array of structures
467 * and that of the member inside the structure.
469 static int extract_depth(__isl_keep isl_multi_pw_aff
*index
)
477 if (isl_multi_pw_aff_range_is_wrapping(index
)) {
478 int domain_depth
, range_depth
;
479 isl_multi_pw_aff
*domain
, *range
;
481 domain
= isl_multi_pw_aff_copy(index
);
482 domain
= isl_multi_pw_aff_range_factor_domain(domain
);
483 domain_depth
= extract_depth(domain
);
484 isl_multi_pw_aff_free(domain
);
485 range
= isl_multi_pw_aff_copy(index
);
486 range
= isl_multi_pw_aff_range_factor_range(range
);
487 range_depth
= extract_depth(range
);
488 isl_multi_pw_aff_free(range
);
490 return domain_depth
+ range_depth
;
493 if (!isl_multi_pw_aff_has_tuple_id(index
, isl_dim_out
))
496 id
= isl_multi_pw_aff_get_tuple_id(index
, isl_dim_out
);
499 decl
= pet_id_get_decl(id
);
502 return pet_clang_array_depth(decl
->getType());
505 /* Return the depth of the array accessed by the access expression "expr".
507 static int extract_depth(__isl_keep pet_expr
*expr
)
509 isl_multi_pw_aff
*index
;
512 index
= pet_expr_access_get_index(expr
);
513 depth
= extract_depth(index
);
514 isl_multi_pw_aff_free(index
);
519 /* Construct a pet_expr representing an index expression for an access
520 * to the variable referenced by "expr".
522 * If "expr" references an enum constant, then return an integer expression
523 * instead, representing the value of the enum constant.
525 __isl_give pet_expr
*PetScan::extract_index_expr(DeclRefExpr
*expr
)
527 return extract_index_expr(expr
->getDecl());
530 /* Construct a pet_expr representing an index expression for an access
531 * to the variable "decl".
533 * If "decl" is an enum constant, then we return an integer expression
534 * instead, representing the value of the enum constant.
536 __isl_give pet_expr
*PetScan::extract_index_expr(ValueDecl
*decl
)
540 if (isa
<EnumConstantDecl
>(decl
))
541 return extract_expr(cast
<EnumConstantDecl
>(decl
));
543 id
= pet_id_from_decl(ctx
, decl
);
544 return pet_id_create_index_expr(id
);
547 /* Construct a pet_expr representing the index expression "expr"
548 * Return NULL on error.
550 * If "expr" is a reference to an enum constant, then return
551 * an integer expression instead, representing the value of the enum constant.
553 __isl_give pet_expr
*PetScan::extract_index_expr(Expr
*expr
)
555 switch (expr
->getStmtClass()) {
556 case Stmt::ImplicitCastExprClass
:
557 return extract_index_expr(cast
<ImplicitCastExpr
>(expr
));
558 case Stmt::DeclRefExprClass
:
559 return extract_index_expr(cast
<DeclRefExpr
>(expr
));
560 case Stmt::ArraySubscriptExprClass
:
561 return extract_index_expr(cast
<ArraySubscriptExpr
>(expr
));
562 case Stmt::IntegerLiteralClass
:
563 return extract_expr(cast
<IntegerLiteral
>(expr
));
564 case Stmt::MemberExprClass
:
565 return extract_index_expr(cast
<MemberExpr
>(expr
));
572 /* Extract an index expression from the given array subscript expression.
574 * We first extract an index expression from the base.
575 * This will result in an index expression with a range that corresponds
576 * to the earlier indices.
577 * We then extract the current index and let
578 * pet_expr_access_subscript combine the two.
580 __isl_give pet_expr
*PetScan::extract_index_expr(ArraySubscriptExpr
*expr
)
582 Expr
*base
= expr
->getBase();
583 Expr
*idx
= expr
->getIdx();
587 base_expr
= extract_index_expr(base
);
588 index
= extract_expr(idx
);
590 base_expr
= pet_expr_access_subscript(base_expr
, index
);
595 /* Extract an index expression from a member expression.
597 * If the base access (to the structure containing the member)
602 * and the member is called "f", then the member access is of
607 * If the member access is to an anonymous struct, then simply return
611 * If the member access in the source code is of the form
615 * then it is treated as
619 __isl_give pet_expr
*PetScan::extract_index_expr(MemberExpr
*expr
)
621 Expr
*base
= expr
->getBase();
622 FieldDecl
*field
= cast
<FieldDecl
>(expr
->getMemberDecl());
623 pet_expr
*base_index
;
626 base_index
= extract_index_expr(base
);
628 if (expr
->isArrow()) {
629 pet_expr
*index
= pet_expr_new_int(isl_val_zero(ctx
));
630 base_index
= pet_expr_access_subscript(base_index
, index
);
633 if (field
->isAnonymousStructOrUnion())
636 id
= pet_id_from_decl(ctx
, field
);
638 return pet_expr_access_member(base_index
, id
);
641 /* Mark the given access pet_expr as a write.
643 static __isl_give pet_expr
*mark_write(__isl_take pet_expr
*access
)
645 access
= pet_expr_access_set_write(access
, 1);
646 access
= pet_expr_access_set_read(access
, 0);
651 /* Mark the given (read) access pet_expr as also possibly being written.
652 * That is, initialize the may write access relation from the may read relation
653 * and initialize the must write access relation to the empty relation.
655 static __isl_give pet_expr
*mark_may_write(__isl_take pet_expr
*expr
)
657 isl_union_map
*access
;
658 isl_union_map
*empty
;
660 access
= pet_expr_access_get_dependent_access(expr
,
661 pet_expr_access_may_read
);
662 empty
= isl_union_map_empty(isl_union_map_get_space(access
));
663 expr
= pet_expr_access_set_access(expr
, pet_expr_access_may_write
,
665 expr
= pet_expr_access_set_access(expr
, pet_expr_access_must_write
,
671 /* Construct a pet_expr representing a unary operator expression.
673 __isl_give pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
679 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
680 if (op
== pet_op_last
) {
681 report_unsupported_unary_operator(expr
);
685 arg
= extract_expr(expr
->getSubExpr());
687 if (expr
->isIncrementDecrementOp() &&
688 pet_expr_get_type(arg
) == pet_expr_access
) {
689 arg
= mark_write(arg
);
690 arg
= pet_expr_access_set_read(arg
, 1);
693 type_size
= pet_clang_get_type_size(expr
->getType(), ast_context
);
694 return pet_expr_new_unary(type_size
, op
, arg
);
697 /* Construct a pet_expr representing a binary operator expression.
699 * If the top level operator is an assignment and the LHS is an access,
700 * then we mark that access as a write. If the operator is a compound
701 * assignment, the access is marked as both a read and a write.
703 __isl_give pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
709 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
710 if (op
== pet_op_last
) {
715 lhs
= extract_expr(expr
->getLHS());
716 rhs
= extract_expr(expr
->getRHS());
718 if (expr
->isAssignmentOp() &&
719 pet_expr_get_type(lhs
) == pet_expr_access
) {
720 lhs
= mark_write(lhs
);
721 if (expr
->isCompoundAssignmentOp())
722 lhs
= pet_expr_access_set_read(lhs
, 1);
725 type_size
= pet_clang_get_type_size(expr
->getType(), ast_context
);
726 return pet_expr_new_binary(type_size
, op
, lhs
, rhs
);
729 /* Construct a pet_tree for a variable declaration and
730 * add the declaration to the list of declarations
731 * inside the current compound statement.
733 __isl_give pet_tree
*PetScan::extract(Decl
*decl
)
739 if (!isa
<VarDecl
>(decl
)) {
740 report_unsupported_declaration(decl
);
744 vd
= cast
<VarDecl
>(decl
);
745 declarations
.push_back(vd
);
747 lhs
= extract_access_expr(vd
);
748 lhs
= mark_write(lhs
);
750 tree
= pet_tree_new_decl(lhs
);
752 rhs
= extract_expr(vd
->getInit());
753 tree
= pet_tree_new_decl_init(lhs
, rhs
);
759 /* Construct a pet_tree for a variable declaration statement.
760 * If the declaration statement declares multiple variables,
761 * then return a group of pet_trees, one for each declared variable.
763 __isl_give pet_tree
*PetScan::extract(DeclStmt
*stmt
)
768 if (!stmt
->isSingleDecl()) {
769 const DeclGroup
&group
= stmt
->getDeclGroup().getDeclGroup();
771 tree
= pet_tree_new_block(ctx
, 0, n
);
773 for (unsigned i
= 0; i
< n
; ++i
) {
777 tree_i
= extract(group
[i
]);
778 loc
= construct_pet_loc(group
[i
]->getSourceRange(),
780 tree_i
= pet_tree_set_loc(tree_i
, loc
);
781 tree
= pet_tree_block_add_child(tree
, tree_i
);
787 return extract(stmt
->getSingleDecl());
790 /* Construct a pet_expr representing a conditional operation.
792 __isl_give pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
794 pet_expr
*cond
, *lhs
, *rhs
;
796 cond
= extract_expr(expr
->getCond());
797 lhs
= extract_expr(expr
->getTrueExpr());
798 rhs
= extract_expr(expr
->getFalseExpr());
800 return pet_expr_new_ternary(cond
, lhs
, rhs
);
803 __isl_give pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
805 return extract_expr(expr
->getSubExpr());
808 /* Construct a pet_expr representing a floating point value.
810 * If the floating point literal does not appear in a macro,
811 * then we use the original representation in the source code
812 * as the string representation. Otherwise, we use the pretty
813 * printer to produce a string representation.
815 __isl_give pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
819 const LangOptions
&LO
= PP
.getLangOpts();
820 SourceLocation loc
= expr
->getLocation();
822 if (!loc
.isMacroID()) {
823 SourceManager
&SM
= PP
.getSourceManager();
824 unsigned len
= Lexer::MeasureTokenLength(loc
, SM
, LO
);
825 s
= string(SM
.getCharacterData(loc
), len
);
827 llvm::raw_string_ostream
S(s
);
828 expr
->printPretty(S
, 0, PrintingPolicy(LO
));
831 d
= expr
->getValueAsApproximateDouble();
832 return pet_expr_new_double(ctx
, d
, s
.c_str());
835 /* Convert the index expression "index" into an access pet_expr of type "qt".
837 __isl_give pet_expr
*PetScan::extract_access_expr(QualType qt
,
838 __isl_take pet_expr
*index
)
843 depth
= extract_depth(index
);
844 type_size
= pet_clang_get_type_size(qt
, ast_context
);
846 index
= pet_expr_set_type_size(index
, type_size
);
847 index
= pet_expr_access_set_depth(index
, depth
);
852 /* Extract an index expression from "expr" and then convert it into
853 * an access pet_expr.
855 * If "expr" is a reference to an enum constant, then return
856 * an integer expression instead, representing the value of the enum constant.
858 __isl_give pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
862 index
= extract_index_expr(expr
);
864 if (pet_expr_get_type(index
) == pet_expr_int
)
867 return extract_access_expr(expr
->getType(), index
);
870 /* Extract an index expression from "decl" and then convert it into
871 * an access pet_expr.
873 __isl_give pet_expr
*PetScan::extract_access_expr(ValueDecl
*decl
)
875 return extract_access_expr(decl
->getType(), extract_index_expr(decl
));
878 __isl_give pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
880 return extract_expr(expr
->getSubExpr());
883 /* Extract an assume statement from the argument "expr"
884 * of a __pencil_assume statement.
886 __isl_give pet_expr
*PetScan::extract_assume(Expr
*expr
)
888 return pet_expr_new_unary(0, pet_op_assume
, extract_expr(expr
));
891 /* If "expr" is an address-of operator, then return its argument.
892 * Otherwise, return NULL.
894 static Expr
*extract_addr_of_arg(Expr
*expr
)
898 if (expr
->getStmtClass() != Stmt::UnaryOperatorClass
)
900 op
= cast
<UnaryOperator
>(expr
);
901 if (op
->getOpcode() != UO_AddrOf
)
903 return op
->getSubExpr();
906 /* Construct a pet_expr corresponding to the function call argument "expr".
907 * The argument appears in position "pos" of a call to function "fd".
909 * If we are passing along a pointer to an array element
910 * or an entire row or even higher dimensional slice of an array,
911 * then the function being called may write into the array.
913 * We assume here that if the function is declared to take a pointer
914 * to a const type, then the function may only perform a read
915 * and that otherwise, it may either perform a read or a write (or both).
916 * We only perform this check if "detect_writes" is set.
918 __isl_give pet_expr
*PetScan::extract_argument(FunctionDecl
*fd
, int pos
,
919 Expr
*expr
, bool detect_writes
)
923 int is_addr
= 0, is_partial
= 0;
925 expr
= pet_clang_strip_casts(expr
);
926 arg
= extract_addr_of_arg(expr
);
931 res
= extract_expr(expr
);
934 if (pet_clang_array_depth(expr
->getType()) > 0)
936 if (detect_writes
&& (is_addr
|| is_partial
) &&
937 pet_expr_get_type(res
) == pet_expr_access
) {
939 if (!fd
->hasPrototype()) {
940 report_prototype_required(expr
);
941 return pet_expr_free(res
);
943 parm
= fd
->getParamDecl(pos
);
944 if (!const_base(parm
->getType()))
945 res
= mark_may_write(res
);
949 res
= pet_expr_new_unary(0, pet_op_address_of
, res
);
953 /* Find the first FunctionDecl with the given name.
954 * "call" is the corresponding call expression and is only used
955 * for reporting errors.
957 * Return NULL on error.
959 FunctionDecl
*PetScan::find_decl_from_name(CallExpr
*call
, string name
)
961 TranslationUnitDecl
*tu
= ast_context
.getTranslationUnitDecl();
962 DeclContext::decl_iterator begin
= tu
->decls_begin();
963 DeclContext::decl_iterator end
= tu
->decls_end();
964 for (DeclContext::decl_iterator i
= begin
; i
!= end
; ++i
) {
965 FunctionDecl
*fd
= dyn_cast
<FunctionDecl
>(*i
);
968 if (fd
->getName().str().compare(name
) != 0)
972 report_missing_summary_function_body(call
);
975 report_missing_summary_function(call
);
979 /* Return the FunctionDecl for the summary function associated to the
980 * function called by "call".
982 * In particular, if the pencil option is set, then
983 * search for an annotate attribute formatted as
984 * "pencil_access(name)", where "name" is the name of the summary function.
986 * If no summary function was specified, then return the FunctionDecl
987 * that is actually being called.
989 * Return NULL on error.
991 FunctionDecl
*PetScan::get_summary_function(CallExpr
*call
)
993 FunctionDecl
*decl
= call
->getDirectCallee();
997 if (!options
->pencil
)
1000 specific_attr_iterator
<AnnotateAttr
> begin
, end
, i
;
1001 begin
= decl
->specific_attr_begin
<AnnotateAttr
>();
1002 end
= decl
->specific_attr_end
<AnnotateAttr
>();
1003 for (i
= begin
; i
!= end
; ++i
) {
1004 string attr
= (*i
)->getAnnotation().str();
1006 const char prefix
[] = "pencil_access(";
1007 size_t start
= attr
.find(prefix
);
1008 if (start
== string::npos
)
1010 start
+= strlen(prefix
);
1011 string name
= attr
.substr(start
, attr
.find(')') - start
);
1013 return find_decl_from_name(call
, name
);
1019 /* Construct a pet_expr representing a function call.
1021 * In the special case of a "call" to __pencil_assume,
1022 * construct an assume expression instead.
1024 * In the case of a "call" to __pencil_kill, the arguments
1025 * are neither read nor written (only killed), so there
1026 * is no need to check for writes to these arguments.
1028 * __pencil_assume and __pencil_kill are only recognized
1029 * when the pencil option is set.
1031 __isl_give pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1033 pet_expr
*res
= NULL
;
1039 fd
= expr
->getDirectCallee();
1045 name
= fd
->getDeclName().getAsString();
1046 n_arg
= expr
->getNumArgs();
1048 if (options
->pencil
&& n_arg
== 1 && name
== "__pencil_assume")
1049 return extract_assume(expr
->getArg(0));
1050 is_kill
= options
->pencil
&& name
== "__pencil_kill";
1052 res
= pet_expr_new_call(ctx
, name
.c_str(), n_arg
);
1056 for (unsigned i
= 0; i
< n_arg
; ++i
) {
1057 Expr
*arg
= expr
->getArg(i
);
1058 res
= pet_expr_set_arg(res
, i
,
1059 PetScan::extract_argument(fd
, i
, arg
, !is_kill
));
1062 fd
= get_summary_function(expr
);
1064 return pet_expr_free(res
);
1066 res
= set_summary(res
, fd
);
1071 /* Construct a pet_expr representing a (C style) cast.
1073 __isl_give pet_expr
*PetScan::extract_expr(CStyleCastExpr
*expr
)
1078 arg
= extract_expr(expr
->getSubExpr());
1082 type
= expr
->getTypeAsWritten();
1083 return pet_expr_new_cast(type
.getAsString().c_str(), arg
);
1086 /* Construct a pet_expr representing an integer.
1088 __isl_give pet_expr
*PetScan::extract_expr(IntegerLiteral
*expr
)
1090 return pet_expr_new_int(extract_int(expr
));
1093 /* Construct a pet_expr representing the integer enum constant "ecd".
1095 __isl_give pet_expr
*PetScan::extract_expr(EnumConstantDecl
*ecd
)
1098 const llvm::APSInt
&init
= ecd
->getInitVal();
1099 v
= ::extract_int(ctx
, init
.isSigned(), init
);
1100 return pet_expr_new_int(v
);
1103 /* Try and construct a pet_expr representing "expr".
1105 __isl_give pet_expr
*PetScan::extract_expr(Expr
*expr
)
1107 switch (expr
->getStmtClass()) {
1108 case Stmt::UnaryOperatorClass
:
1109 return extract_expr(cast
<UnaryOperator
>(expr
));
1110 case Stmt::CompoundAssignOperatorClass
:
1111 case Stmt::BinaryOperatorClass
:
1112 return extract_expr(cast
<BinaryOperator
>(expr
));
1113 case Stmt::ImplicitCastExprClass
:
1114 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1115 case Stmt::ArraySubscriptExprClass
:
1116 case Stmt::DeclRefExprClass
:
1117 case Stmt::MemberExprClass
:
1118 return extract_access_expr(expr
);
1119 case Stmt::IntegerLiteralClass
:
1120 return extract_expr(cast
<IntegerLiteral
>(expr
));
1121 case Stmt::FloatingLiteralClass
:
1122 return extract_expr(cast
<FloatingLiteral
>(expr
));
1123 case Stmt::ParenExprClass
:
1124 return extract_expr(cast
<ParenExpr
>(expr
));
1125 case Stmt::ConditionalOperatorClass
:
1126 return extract_expr(cast
<ConditionalOperator
>(expr
));
1127 case Stmt::CallExprClass
:
1128 return extract_expr(cast
<CallExpr
>(expr
));
1129 case Stmt::CStyleCastExprClass
:
1130 return extract_expr(cast
<CStyleCastExpr
>(expr
));
1137 /* Check if the given initialization statement is an assignment.
1138 * If so, return that assignment. Otherwise return NULL.
1140 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1142 BinaryOperator
*ass
;
1144 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1147 ass
= cast
<BinaryOperator
>(init
);
1148 if (ass
->getOpcode() != BO_Assign
)
1154 /* Check if the given initialization statement is a declaration
1155 * of a single variable.
1156 * If so, return that declaration. Otherwise return NULL.
1158 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1162 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1165 decl
= cast
<DeclStmt
>(init
);
1167 if (!decl
->isSingleDecl())
1170 return decl
->getSingleDecl();
1173 /* Given the assignment operator in the initialization of a for loop,
1174 * extract the induction variable, i.e., the (integer)variable being
1177 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1184 lhs
= init
->getLHS();
1185 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1190 ref
= cast
<DeclRefExpr
>(lhs
);
1191 decl
= ref
->getDecl();
1192 type
= decl
->getType().getTypePtr();
1194 if (!type
->isIntegerType()) {
1202 /* Given the initialization statement of a for loop and the single
1203 * declaration in this initialization statement,
1204 * extract the induction variable, i.e., the (integer) variable being
1207 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1211 vd
= cast
<VarDecl
>(decl
);
1213 const QualType type
= vd
->getType();
1214 if (!type
->isIntegerType()) {
1219 if (!vd
->getInit()) {
1227 /* Check that op is of the form iv++ or iv--.
1228 * Return a pet_expr representing "1" or "-1" accordingly.
1230 __isl_give pet_expr
*PetScan::extract_unary_increment(
1231 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1237 if (!op
->isIncrementDecrementOp()) {
1242 sub
= op
->getSubExpr();
1243 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1248 ref
= cast
<DeclRefExpr
>(sub
);
1249 if (ref
->getDecl() != iv
) {
1254 if (op
->isIncrementOp())
1255 v
= isl_val_one(ctx
);
1257 v
= isl_val_negone(ctx
);
1259 return pet_expr_new_int(v
);
1262 /* Check if op is of the form
1266 * and return the increment "expr - iv" as a pet_expr.
1268 __isl_give pet_expr
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1269 clang::ValueDecl
*iv
)
1274 pet_expr
*expr
, *expr_iv
;
1276 if (op
->getOpcode() != BO_Assign
) {
1282 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1287 ref
= cast
<DeclRefExpr
>(lhs
);
1288 if (ref
->getDecl() != iv
) {
1293 expr
= extract_expr(op
->getRHS());
1294 expr_iv
= extract_expr(lhs
);
1296 type_size
= pet_clang_get_type_size(iv
->getType(), ast_context
);
1297 return pet_expr_new_binary(type_size
, pet_op_sub
, expr
, expr_iv
);
1300 /* Check that op is of the form iv += cst or iv -= cst
1301 * and return a pet_expr corresponding to cst or -cst accordingly.
1303 __isl_give pet_expr
*PetScan::extract_compound_increment(
1304 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1310 BinaryOperatorKind opcode
;
1312 opcode
= op
->getOpcode();
1313 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1317 if (opcode
== BO_SubAssign
)
1321 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1326 ref
= cast
<DeclRefExpr
>(lhs
);
1327 if (ref
->getDecl() != iv
) {
1332 expr
= extract_expr(op
->getRHS());
1335 type_size
= pet_clang_get_type_size(op
->getType(), ast_context
);
1336 expr
= pet_expr_new_unary(type_size
, pet_op_minus
, expr
);
1342 /* Check that the increment of the given for loop increments
1343 * (or decrements) the induction variable "iv" and return
1344 * the increment as a pet_expr if successful.
1346 __isl_give pet_expr
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1349 Stmt
*inc
= stmt
->getInc();
1352 report_missing_increment(stmt
);
1356 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1357 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1358 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1359 return extract_compound_increment(
1360 cast
<CompoundAssignOperator
>(inc
), iv
);
1361 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1362 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1368 /* Construct a pet_tree for a while loop.
1370 * If we were only able to extract part of the body, then simply
1373 __isl_give pet_tree
*PetScan::extract(WhileStmt
*stmt
)
1378 tree
= extract(stmt
->getBody());
1381 pe_cond
= extract_expr(stmt
->getCond());
1382 tree
= pet_tree_new_while(pe_cond
, tree
);
1387 /* Construct a pet_tree for a for statement.
1388 * The for loop is required to be of one of the following forms
1390 * for (i = init; condition; ++i)
1391 * for (i = init; condition; --i)
1392 * for (i = init; condition; i += constant)
1393 * for (i = init; condition; i -= constant)
1395 * We extract a pet_tree for the body and then include it in a pet_tree
1396 * of type pet_tree_for.
1398 * As a special case, we also allow a for loop of the form
1402 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1404 * If we were only able to extract part of the body, then simply
1407 __isl_give pet_tree
*PetScan::extract_for(ForStmt
*stmt
)
1409 BinaryOperator
*ass
;
1417 pet_expr
*pe_init
, *pe_inc
, *pe_iv
, *pe_cond
;
1419 independent
= is_current_stmt_marked_independent();
1421 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc()) {
1422 tree
= extract(stmt
->getBody());
1425 tree
= pet_tree_new_infinite_loop(tree
);
1429 init
= stmt
->getInit();
1434 if ((ass
= initialization_assignment(init
)) != NULL
) {
1435 iv
= extract_induction_variable(ass
);
1438 lhs
= ass
->getLHS();
1439 rhs
= ass
->getRHS();
1440 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
1441 VarDecl
*var
= extract_induction_variable(init
, decl
);
1445 rhs
= var
->getInit();
1446 lhs
= create_DeclRefExpr(var
);
1448 unsupported(stmt
->getInit());
1452 declared
= !initialization_assignment(stmt
->getInit());
1453 tree
= extract(stmt
->getBody());
1456 pe_iv
= extract_access_expr(iv
);
1457 pe_iv
= mark_write(pe_iv
);
1458 pe_init
= extract_expr(rhs
);
1459 if (!stmt
->getCond())
1460 pe_cond
= pet_expr_new_int(isl_val_one(ctx
));
1462 pe_cond
= extract_expr(stmt
->getCond());
1463 pe_inc
= extract_increment(stmt
, iv
);
1464 tree
= pet_tree_new_for(independent
, declared
, pe_iv
, pe_init
, pe_cond
,
1469 /* Store the names of the variables declared in decl_context
1470 * in the set declared_names. Make sure to only do this once by
1471 * setting declared_names_collected.
1473 void PetScan::collect_declared_names()
1475 DeclContext
*DC
= decl_context
;
1476 DeclContext::decl_iterator it
;
1478 if (declared_names_collected
)
1481 for (it
= DC
->decls_begin(); it
!= DC
->decls_end(); ++it
) {
1485 if (!isa
<NamedDecl
>(D
))
1487 named
= cast
<NamedDecl
>(D
);
1488 declared_names
.insert(named
->getName().str());
1491 declared_names_collected
= true;
1494 /* Add the names in "names" that are not also in this->declared_names
1495 * to this->used_names.
1496 * It is up to the caller to make sure that declared_names has been
1497 * populated, if needed.
1499 void PetScan::add_new_used_names(const std::set
<std::string
> &names
)
1501 std::set
<std::string
>::const_iterator it
;
1503 for (it
= names
.begin(); it
!= names
.end(); ++it
) {
1504 if (declared_names
.find(*it
) != declared_names
.end())
1506 used_names
.insert(*it
);
1510 /* Is the name "name" used in any declaration other than "decl"?
1512 * If the name was found to be in use before, the consider it to be in use.
1513 * Otherwise, check the DeclContext of the function containing the scop
1514 * as well as all ancestors of this DeclContext for declarations
1515 * other than "decl" that declare something called "name".
1517 bool PetScan::name_in_use(const string
&name
, Decl
*decl
)
1520 DeclContext::decl_iterator it
;
1522 if (used_names
.find(name
) != used_names
.end())
1525 for (DC
= decl_context
; DC
; DC
= DC
->getParent()) {
1526 for (it
= DC
->decls_begin(); it
!= DC
->decls_end(); ++it
) {
1532 if (!isa
<NamedDecl
>(D
))
1534 named
= cast
<NamedDecl
>(D
);
1535 if (named
->getName().str() == name
)
1543 /* Generate a new name based on "name" that is not in use.
1544 * Do so by adding a suffix _i, with i an integer.
1546 string
PetScan::generate_new_name(const string
&name
)
1551 std::ostringstream oss
;
1552 oss
<< name
<< "_" << n_rename
++;
1553 new_name
= oss
.str();
1554 } while (name_in_use(new_name
, NULL
));
1559 /* Try and construct a pet_tree corresponding to a compound statement.
1561 * "skip_declarations" is set if we should skip initial declarations
1562 * in the children of the compound statements.
1564 * Collect a new set of declarations for the current compound statement.
1565 * If any of the names in these declarations is also used by another
1566 * declaration reachable from the current function, then rename it
1567 * to a name that is not already in use.
1568 * In particular, keep track of the old and new names in a pet_substituter
1569 * and apply the substitutions to the pet_tree corresponding to the
1570 * compound statement.
1572 __isl_give pet_tree
*PetScan::extract(CompoundStmt
*stmt
,
1573 bool skip_declarations
)
1576 std::vector
<VarDecl
*> saved_declarations
;
1577 std::vector
<VarDecl
*>::iterator it
;
1578 pet_substituter substituter
;
1580 saved_declarations
= declarations
;
1581 declarations
.clear();
1582 tree
= extract(stmt
->children(), true, skip_declarations
, stmt
);
1583 for (it
= declarations
.begin(); it
!= declarations
.end(); ++it
) {
1586 VarDecl
*decl
= *it
;
1587 string name
= decl
->getName().str();
1588 bool in_use
= name_in_use(name
, decl
);
1590 used_names
.insert(name
);
1594 name
= generate_new_name(name
);
1595 id
= pet_id_from_name_and_decl(ctx
, name
.c_str(), decl
);
1596 expr
= pet_id_create_index_expr(id
);
1597 expr
= extract_access_expr(decl
->getType(), expr
);
1598 id
= pet_id_from_decl(ctx
, decl
);
1599 substituter
.add_sub(id
, expr
);
1600 used_names
.insert(name
);
1602 tree
= substituter
.substitute(tree
);
1603 declarations
= saved_declarations
;
1608 /* Return the file offset of the expansion location of "Loc".
1610 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
1612 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
1615 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1617 /* Return a SourceLocation for the location after the first semicolon
1618 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1619 * call it and also skip trailing spaces and newline.
1621 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
1622 const LangOptions
&LO
)
1624 return Lexer::findLocationAfterToken(loc
, tok::semi
, SM
, LO
, true);
1629 /* Return a SourceLocation for the location after the first semicolon
1630 * after "loc". If Lexer::findLocationAfterToken is not available,
1631 * we look in the underlying character data for the first semicolon.
1633 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
1634 const LangOptions
&LO
)
1637 const char *s
= SM
.getCharacterData(loc
);
1639 semi
= strchr(s
, ';');
1641 return SourceLocation();
1642 return loc
.getFileLocWithOffset(semi
+ 1 - s
);
1647 /* If the token at "loc" is the first token on the line, then return
1648 * a location referring to the start of the line and set *indent
1649 * to the indentation of "loc"
1650 * Otherwise, return "loc" and set *indent to "".
1652 * This function is used to extend a scop to the start of the line
1653 * if the first token of the scop is also the first token on the line.
1655 * We look for the first token on the line. If its location is equal to "loc",
1656 * then the latter is the location of the first token on the line.
1658 static SourceLocation
move_to_start_of_line_if_first_token(SourceLocation loc
,
1659 SourceManager
&SM
, const LangOptions
&LO
, char **indent
)
1661 std::pair
<FileID
, unsigned> file_offset_pair
;
1662 llvm::StringRef file
;
1665 SourceLocation token_loc
, line_loc
;
1669 loc
= SM
.getExpansionLoc(loc
);
1670 col
= SM
.getExpansionColumnNumber(loc
);
1671 line_loc
= loc
.getLocWithOffset(1 - col
);
1672 file_offset_pair
= SM
.getDecomposedLoc(line_loc
);
1673 file
= SM
.getBufferData(file_offset_pair
.first
, NULL
);
1674 pos
= file
.data() + file_offset_pair
.second
;
1676 Lexer
lexer(SM
.getLocForStartOfFile(file_offset_pair
.first
), LO
,
1677 file
.begin(), pos
, file
.end());
1678 lexer
.LexFromRawLexer(tok
);
1679 token_loc
= tok
.getLocation();
1681 s
= SM
.getCharacterData(line_loc
);
1682 *indent
= strndup(s
, token_loc
== loc
? col
- 1 : 0);
1684 if (token_loc
== loc
)
1690 /* Construct a pet_loc corresponding to the region covered by "range".
1691 * If "skip_semi" is set, then we assume "range" is followed by
1692 * a semicolon and also include this semicolon.
1694 __isl_give pet_loc
*PetScan::construct_pet_loc(SourceRange range
,
1697 SourceLocation loc
= range
.getBegin();
1698 SourceManager
&SM
= PP
.getSourceManager();
1699 const LangOptions
&LO
= PP
.getLangOpts();
1700 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
1701 unsigned start
, end
;
1704 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
, &indent
);
1705 start
= getExpansionOffset(SM
, loc
);
1706 loc
= range
.getEnd();
1708 loc
= location_after_semi(loc
, SM
, LO
);
1710 loc
= PP
.getLocForEndOfToken(loc
);
1711 end
= getExpansionOffset(SM
, loc
);
1713 return pet_loc_alloc(ctx
, start
, end
, line
, indent
);
1716 /* Convert a top-level pet_expr to an expression pet_tree.
1718 __isl_give pet_tree
*PetScan::extract(__isl_take pet_expr
*expr
,
1719 SourceRange range
, bool skip_semi
)
1724 tree
= pet_tree_new_expr(expr
);
1725 loc
= construct_pet_loc(range
, skip_semi
);
1726 tree
= pet_tree_set_loc(tree
, loc
);
1731 /* Construct a pet_tree for an if statement.
1733 __isl_give pet_tree
*PetScan::extract(IfStmt
*stmt
)
1736 pet_tree
*tree
, *tree_else
;
1738 pe_cond
= extract_expr(stmt
->getCond());
1739 tree
= extract(stmt
->getThen());
1740 if (stmt
->getElse()) {
1741 tree_else
= extract(stmt
->getElse());
1742 if (options
->autodetect
) {
1743 if (tree
&& !tree_else
) {
1745 pet_expr_free(pe_cond
);
1748 if (!tree
&& tree_else
) {
1750 pet_expr_free(pe_cond
);
1754 tree
= pet_tree_new_if_else(pe_cond
, tree
, tree_else
);
1756 tree
= pet_tree_new_if(pe_cond
, tree
);
1760 /* Try and construct a pet_tree for a label statement.
1762 __isl_give pet_tree
*PetScan::extract(LabelStmt
*stmt
)
1767 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
1769 tree
= extract(stmt
->getSubStmt());
1770 tree
= pet_tree_set_label(tree
, label
);
1774 /* Update the location of "tree" to include the source range of "stmt".
1776 * Actually, we create a new location based on the source range of "stmt" and
1777 * then extend this new location to include the region of the original location.
1778 * This ensures that the line number of the final location refers to "stmt".
1780 __isl_give pet_tree
*PetScan::update_loc(__isl_take pet_tree
*tree
, Stmt
*stmt
)
1782 pet_loc
*loc
, *tree_loc
;
1784 tree_loc
= pet_tree_get_loc(tree
);
1785 loc
= construct_pet_loc(stmt
->getSourceRange(), false);
1786 loc
= pet_loc_update_start_end_from_loc(loc
, tree_loc
);
1787 pet_loc_free(tree_loc
);
1789 tree
= pet_tree_set_loc(tree
, loc
);
1793 /* Is "expr" of a type that can be converted to an access expression?
1795 static bool is_access_expr_type(Expr
*expr
)
1797 switch (expr
->getStmtClass()) {
1798 case Stmt::ArraySubscriptExprClass
:
1799 case Stmt::DeclRefExprClass
:
1800 case Stmt::MemberExprClass
:
1807 /* Tell the pet_inliner "inliner" about the formal arguments
1808 * in "fd" and the corresponding actual arguments in "call".
1809 * Return 0 if this was successful and -1 otherwise.
1811 * Any pointer argument is treated as an array.
1812 * The other arguments are treated as scalars.
1814 * In case of scalars, there is no restriction on the actual argument.
1815 * This actual argument is assigned to a variable with a name
1816 * that is derived from the name of the corresponding formal argument,
1817 * but made not to conflict with any variable names that are
1820 * In case of arrays, the actual argument needs to be an expression
1821 * of a type that can be converted to an access expression or the address
1822 * of such an expression, ignoring implicit and redundant casts.
1824 int PetScan::set_inliner_arguments(pet_inliner
&inliner
, CallExpr
*call
,
1829 n
= fd
->getNumParams();
1830 for (unsigned i
= 0; i
< n
; ++i
) {
1831 ParmVarDecl
*parm
= fd
->getParamDecl(i
);
1832 QualType type
= parm
->getType();
1837 arg
= call
->getArg(i
);
1838 if (pet_clang_array_depth(type
) == 0) {
1839 string name
= parm
->getName().str();
1840 if (name_in_use(name
, NULL
))
1841 name
= generate_new_name(name
);
1842 inliner
.add_scalar_arg(parm
, name
, extract_expr(arg
));
1845 arg
= pet_clang_strip_casts(arg
);
1846 sub
= extract_addr_of_arg(arg
);
1849 arg
= pet_clang_strip_casts(sub
);
1851 if (!is_access_expr_type(arg
)) {
1852 report_unsupported_inline_function_argument(arg
);
1855 expr
= extract_access_expr(arg
);
1858 inliner
.add_array_arg(parm
, expr
, is_addr
);
1864 /* Try and construct a pet_tree from the body of "fd" using the actual
1865 * arguments in "call" in place of the formal arguments.
1866 * "fd" is assumed to point to the declaration with a function body.
1867 * In particular, construct a block that consists of assignments
1868 * of (parts of) the actual arguments to temporary variables
1869 * followed by the inlined function body with the formal arguments
1870 * replaced by (expressions containing) these temporary variables.
1872 * The actual inlining is taken care of by the pet_inliner function.
1873 * This function merely calls set_inliner_arguments to tell
1874 * the pet_inliner about the actual arguments, extracts a pet_tree
1875 * from the body of the called function and then passes this pet_tree
1876 * to the pet_inliner.
1878 * During the extraction of the function body, all variables names
1879 * that are declared in the calling function as well all variable
1880 * names that are known to be in use are considered to be in use
1881 * in the called function to ensure that there is no naming conflict.
1882 * Similarly, the additional names that are in use in the called function
1883 * are considered to be in use in the calling function as well.
1885 * The location of the pet_tree is reset to the call site to ensure
1886 * that the extent of the scop does not include the body of the called
1889 __isl_give pet_tree
*PetScan::extract_inlined_call(CallExpr
*call
,
1892 int save_autodetect
;
1895 pet_inliner
inliner(ctx
, n_arg
, ast_context
);
1897 if (set_inliner_arguments(inliner
, call
, fd
) < 0)
1900 save_autodetect
= options
->autodetect
;
1901 options
->autodetect
= 0;
1902 PetScan
body_scan(PP
, ast_context
, fd
, loc
, options
,
1903 isl_union_map_copy(value_bounds
), independent
);
1904 collect_declared_names();
1905 body_scan
.add_new_used_names(declared_names
);
1906 body_scan
.add_new_used_names(used_names
);
1907 tree
= body_scan
.extract(fd
->getBody(), false);
1908 add_new_used_names(body_scan
.used_names
);
1909 options
->autodetect
= save_autodetect
;
1911 tree_loc
= construct_pet_loc(call
->getSourceRange(), true);
1912 tree
= pet_tree_set_loc(tree
, tree_loc
);
1914 return inliner
.inline_tree(tree
);
1917 /* Try and construct a pet_tree corresponding
1918 * to the expression statement "stmt".
1920 * If the outer expression is a function call and if the corresponding
1921 * function body is marked "inline", then return a pet_tree
1922 * corresponding to the inlined function.
1924 __isl_give pet_tree
*PetScan::extract_expr_stmt(Stmt
*stmt
)
1928 if (stmt
->getStmtClass() == Stmt::CallExprClass
) {
1929 CallExpr
*call
= cast
<CallExpr
>(stmt
);
1930 FunctionDecl
*fd
= call
->getDirectCallee();
1931 fd
= pet_clang_find_function_decl_with_body(fd
);
1932 if (fd
&& fd
->isInlineSpecified())
1933 return extract_inlined_call(call
, fd
);
1936 expr
= extract_expr(cast
<Expr
>(stmt
));
1937 return extract(expr
, stmt
->getSourceRange(), true);
1940 /* Try and construct a pet_tree corresponding to "stmt".
1942 * If "stmt" is a compound statement, then "skip_declarations"
1943 * indicates whether we should skip initial declarations in the
1944 * compound statement.
1946 * If the constructed pet_tree is not a (possibly) partial representation
1947 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1948 * In particular, if skip_declarations is set, then we may have skipped
1949 * declarations inside "stmt" and so the pet_scop may not represent
1950 * the entire "stmt".
1951 * Note that this function may be called with "stmt" referring to the entire
1952 * body of the function, including the outer braces. In such cases,
1953 * skip_declarations will be set and the braces will not be taken into
1954 * account in tree->loc.
1956 __isl_give pet_tree
*PetScan::extract(Stmt
*stmt
, bool skip_declarations
)
1960 set_current_stmt(stmt
);
1962 if (isa
<Expr
>(stmt
))
1963 return extract_expr_stmt(cast
<Expr
>(stmt
));
1965 switch (stmt
->getStmtClass()) {
1966 case Stmt::WhileStmtClass
:
1967 tree
= extract(cast
<WhileStmt
>(stmt
));
1969 case Stmt::ForStmtClass
:
1970 tree
= extract_for(cast
<ForStmt
>(stmt
));
1972 case Stmt::IfStmtClass
:
1973 tree
= extract(cast
<IfStmt
>(stmt
));
1975 case Stmt::CompoundStmtClass
:
1976 tree
= extract(cast
<CompoundStmt
>(stmt
), skip_declarations
);
1978 case Stmt::LabelStmtClass
:
1979 tree
= extract(cast
<LabelStmt
>(stmt
));
1981 case Stmt::ContinueStmtClass
:
1982 tree
= pet_tree_new_continue(ctx
);
1984 case Stmt::BreakStmtClass
:
1985 tree
= pet_tree_new_break(ctx
);
1987 case Stmt::DeclStmtClass
:
1988 tree
= extract(cast
<DeclStmt
>(stmt
));
1991 report_unsupported_statement_type(stmt
);
1995 if (partial
|| skip_declarations
)
1998 return update_loc(tree
, stmt
);
2001 /* Given a sequence of statements "stmt_range" of which the first "n_decl"
2002 * are declarations and of which the remaining statements are represented
2003 * by "tree", try and extend "tree" to include the last sequence of
2004 * the initial declarations that can be completely extracted.
2006 * We start collecting the initial declarations and start over
2007 * whenever we come across a declaration that we cannot extract.
2008 * If we have been able to extract any declarations, then we
2009 * copy over the contents of "tree" at the end of the declarations.
2010 * Otherwise, we simply return the original "tree".
2012 __isl_give pet_tree
*PetScan::insert_initial_declarations(
2013 __isl_take pet_tree
*tree
, int n_decl
, StmtRange stmt_range
)
2021 n_stmt
= pet_tree_block_n_child(tree
);
2022 is_block
= pet_tree_block_get_block(tree
);
2023 res
= pet_tree_new_block(ctx
, is_block
, n_decl
+ n_stmt
);
2025 for (i
= stmt_range
.first
; n_decl
; ++i
, --n_decl
) {
2029 tree_i
= extract(child
);
2030 if (tree_i
&& !partial
) {
2031 res
= pet_tree_block_add_child(res
, tree_i
);
2034 pet_tree_free(tree_i
);
2036 if (pet_tree_block_n_child(res
) == 0)
2039 res
= pet_tree_new_block(ctx
, is_block
, n_decl
+ n_stmt
);
2042 if (pet_tree_block_n_child(res
) == 0) {
2047 for (j
= 0; j
< n_stmt
; ++j
) {
2050 tree_i
= pet_tree_block_get_child(tree
, j
);
2051 res
= pet_tree_block_add_child(res
, tree_i
);
2053 pet_tree_free(tree
);
2058 /* Try and construct a pet_tree corresponding to (part of)
2059 * a sequence of statements.
2061 * "block" is set if the sequence represents the children of
2062 * a compound statement.
2063 * "skip_declarations" is set if we should skip initial declarations
2064 * in the sequence of statements.
2065 * "parent" is the statement that has stmt_range as (some of) its children.
2067 * If autodetect is set, then we allow the extraction of only a subrange
2068 * of the sequence of statements. However, if there is at least one
2069 * kill and there is some subsequent statement for which we could not
2070 * construct a tree, then turn off the "block" property of the tree
2071 * such that no extra kill will be introduced at the end of the (partial)
2072 * block. If, on the other hand, the final range contains
2073 * no statements, then we discard the entire range.
2074 * If only a subrange of the sequence was extracted, but each statement
2075 * in the sequence was extracted completely, and if there are some
2076 * variable declarations in the sequence before or inside
2077 * the extracted subrange, then check if any of these variables are
2078 * not used after the extracted subrange. If so, add kills to these
2081 * If the entire range was extracted, apart from some initial declarations,
2082 * then we try and extend the range with the latest of those initial
2085 __isl_give pet_tree
*PetScan::extract(StmtRange stmt_range
, bool block
,
2086 bool skip_declarations
, Stmt
*parent
)
2090 bool has_kills
= false;
2091 bool partial_range
= false;
2092 bool outer_partial
= false;
2094 SourceManager
&SM
= PP
.getSourceManager();
2095 pet_killed_locals
kl(SM
);
2096 unsigned range_start
, range_end
;
2098 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
)
2101 tree
= pet_tree_new_block(ctx
, block
, j
);
2104 i
= stmt_range
.first
;
2105 if (skip_declarations
)
2106 for (; i
!= stmt_range
.second
; ++i
) {
2107 if ((*i
)->getStmtClass() != Stmt::DeclStmtClass
)
2109 if (options
->autodetect
)
2110 kl
.add_locals(cast
<DeclStmt
>(*i
));
2114 for (; i
!= stmt_range
.second
; ++i
) {
2118 tree_i
= extract(child
);
2119 if (pet_tree_block_n_child(tree
) != 0 && partial
) {
2120 pet_tree_free(tree_i
);
2123 if (child
->getStmtClass() == Stmt::DeclStmtClass
) {
2124 if (options
->autodetect
)
2125 kl
.add_locals(cast
<DeclStmt
>(child
));
2126 if (tree_i
&& block
)
2129 if (options
->autodetect
) {
2131 range_end
= getExpansionOffset(SM
,
2132 child
->getLocEnd());
2133 if (pet_tree_block_n_child(tree
) == 0)
2134 range_start
= getExpansionOffset(SM
,
2135 child
->getLocStart());
2136 tree
= pet_tree_block_add_child(tree
, tree_i
);
2138 partial_range
= true;
2140 if (pet_tree_block_n_child(tree
) != 0 && !tree_i
)
2141 outer_partial
= partial
= true;
2143 tree
= pet_tree_block_add_child(tree
, tree_i
);
2146 if (partial
|| !tree
)
2155 tree
= pet_tree_block_set_block(tree
, 0);
2156 if (outer_partial
) {
2157 kl
.remove_accessed_after(parent
,
2158 range_start
, range_end
);
2159 tree
= add_kills(tree
, kl
.locals
);
2161 } else if (partial_range
) {
2162 if (pet_tree_block_n_child(tree
) == 0) {
2163 pet_tree_free(tree
);
2167 } else if (skip
> 0)
2168 tree
= insert_initial_declarations(tree
, skip
, stmt_range
);
2174 static __isl_give pet_expr
*get_array_size(__isl_keep pet_expr
*access
,
2176 static struct pet_array
*extract_array(__isl_keep pet_expr
*access
,
2177 __isl_keep pet_context
*pc
, void *user
);
2180 /* Construct a pet_expr that holds the sizes of the array accessed
2182 * This function is used as a callback to pet_context_add_parameters,
2183 * which is also passed a pointer to the PetScan object.
2185 static __isl_give pet_expr
*get_array_size(__isl_keep pet_expr
*access
,
2188 PetScan
*ps
= (PetScan
*) user
;
2192 id
= pet_expr_access_get_id(access
);
2193 qt
= pet_id_get_array_type(id
);
2195 return ps
->get_array_size(qt
);
2198 /* Construct and return a pet_array corresponding to the variable
2199 * accessed by "access".
2200 * This function is used as a callback to pet_scop_from_pet_tree,
2201 * which is also passed a pointer to the PetScan object.
2203 static struct pet_array
*extract_array(__isl_keep pet_expr
*access
,
2204 __isl_keep pet_context
*pc
, void *user
)
2206 PetScan
*ps
= (PetScan
*) user
;
2211 ctx
= pet_expr_get_ctx(access
);
2212 id
= pet_expr_access_get_id(access
);
2213 array
= ps
->extract_array(id
, NULL
, pc
);
2219 /* Extract a function summary from the body of "fd".
2221 * We extract a scop from the function body in a context with as
2222 * parameters the integer arguments of the function.
2223 * We turn off autodetection (in case it was set) to ensure that
2224 * the entire function body is considered.
2225 * We then collect the accessed array elements and attach them
2226 * to the corresponding array arguments, taking into account
2227 * that the function body may access members of array elements.
2229 * The reason for representing the integer arguments as parameters in
2230 * the context is that if we were to instead start with a context
2231 * with the function arguments as initial dimensions, then we would not
2232 * be able to refer to them from the array extents, without turning
2233 * array extents into maps.
2235 * The result is stored in the summary_cache cache so that we can reuse
2236 * it if this method gets called on the same function again later on.
2238 __isl_give pet_function_summary
*PetScan::get_summary(FunctionDecl
*fd
)
2244 pet_function_summary
*summary
;
2247 int save_autodetect
;
2248 struct pet_scop
*scop
;
2250 isl_union_set
*may_read
, *may_write
, *must_write
;
2251 isl_union_map
*to_inner
;
2253 if (summary_cache
.find(fd
) != summary_cache
.end())
2254 return pet_function_summary_copy(summary_cache
[fd
]);
2256 space
= isl_space_set_alloc(ctx
, 0, 0);
2258 n
= fd
->getNumParams();
2259 summary
= pet_function_summary_alloc(ctx
, n
);
2260 for (unsigned i
= 0; i
< n
; ++i
) {
2261 ParmVarDecl
*parm
= fd
->getParamDecl(i
);
2262 QualType type
= parm
->getType();
2265 if (!type
->isIntegerType())
2267 id
= pet_id_from_decl(ctx
, parm
);
2268 space
= isl_space_insert_dims(space
, isl_dim_param
, 0, 1);
2269 space
= isl_space_set_dim_id(space
, isl_dim_param
, 0,
2271 summary
= pet_function_summary_set_int(summary
, i
, id
);
2274 save_autodetect
= options
->autodetect
;
2275 options
->autodetect
= 0;
2276 PetScan
body_scan(PP
, ast_context
, fd
, loc
, options
,
2277 isl_union_map_copy(value_bounds
), independent
);
2279 tree
= body_scan
.extract(fd
->getBody(), false);
2281 domain
= isl_set_universe(space
);
2282 pc
= pet_context_alloc(domain
);
2283 pc
= pet_context_add_parameters(pc
, tree
,
2284 &::get_array_size
, &body_scan
);
2285 int_size
= size_in_bytes(ast_context
, ast_context
.IntTy
);
2286 scop
= pet_scop_from_pet_tree(tree
, int_size
,
2287 &::extract_array
, &body_scan
, pc
);
2288 scop
= scan_arrays(scop
, pc
);
2289 may_read
= isl_union_map_range(pet_scop_get_may_reads(scop
));
2290 may_write
= isl_union_map_range(pet_scop_get_may_writes(scop
));
2291 must_write
= isl_union_map_range(pet_scop_get_must_writes(scop
));
2292 to_inner
= pet_scop_compute_outer_to_inner(scop
);
2293 pet_scop_free(scop
);
2295 for (unsigned i
= 0; i
< n
; ++i
) {
2296 ParmVarDecl
*parm
= fd
->getParamDecl(i
);
2297 QualType type
= parm
->getType();
2298 struct pet_array
*array
;
2300 isl_union_set
*data_set
;
2301 isl_union_set
*may_read_i
, *may_write_i
, *must_write_i
;
2303 if (pet_clang_array_depth(type
) == 0)
2306 array
= body_scan
.extract_array(parm
, NULL
, pc
);
2307 space
= array
? isl_set_get_space(array
->extent
) : NULL
;
2308 pet_array_free(array
);
2309 data_set
= isl_union_set_from_set(isl_set_universe(space
));
2310 data_set
= isl_union_set_apply(data_set
,
2311 isl_union_map_copy(to_inner
));
2312 may_read_i
= isl_union_set_intersect(
2313 isl_union_set_copy(may_read
),
2314 isl_union_set_copy(data_set
));
2315 may_write_i
= isl_union_set_intersect(
2316 isl_union_set_copy(may_write
),
2317 isl_union_set_copy(data_set
));
2318 must_write_i
= isl_union_set_intersect(
2319 isl_union_set_copy(must_write
), data_set
);
2320 summary
= pet_function_summary_set_array(summary
, i
,
2321 may_read_i
, may_write_i
, must_write_i
);
2324 isl_union_set_free(may_read
);
2325 isl_union_set_free(may_write
);
2326 isl_union_set_free(must_write
);
2327 isl_union_map_free(to_inner
);
2329 options
->autodetect
= save_autodetect
;
2330 pet_context_free(pc
);
2332 summary_cache
[fd
] = pet_function_summary_copy(summary
);
2337 /* If "fd" has a function body, then extract a function summary from
2338 * this body and attach it to the call expression "expr".
2340 * Even if a function body is available, "fd" itself may point
2341 * to a declaration without function body. We therefore first
2342 * replace it by the declaration that comes with a body (if any).
2344 __isl_give pet_expr
*PetScan::set_summary(__isl_take pet_expr
*expr
,
2347 pet_function_summary
*summary
;
2351 fd
= pet_clang_find_function_decl_with_body(fd
);
2355 summary
= get_summary(fd
);
2357 expr
= pet_expr_call_set_summary(expr
, summary
);
2362 /* Extract a pet_scop from "tree".
2364 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
2365 * then add pet_arrays for all accessed arrays.
2366 * We populate the pet_context with assignments for all parameters used
2367 * inside "tree" or any of the size expressions for the arrays accessed
2368 * by "tree" so that they can be used in affine expressions.
2370 struct pet_scop
*PetScan::extract_scop(__isl_take pet_tree
*tree
)
2377 int_size
= size_in_bytes(ast_context
, ast_context
.IntTy
);
2379 domain
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2380 pc
= pet_context_alloc(domain
);
2381 pc
= pet_context_add_parameters(pc
, tree
, &::get_array_size
, this);
2382 scop
= pet_scop_from_pet_tree(tree
, int_size
,
2383 &::extract_array
, this, pc
);
2384 scop
= scan_arrays(scop
, pc
);
2385 pet_context_free(pc
);
2390 /* Add a call to __pencil_kill to the end of "tree" that kills
2391 * all the variables in "locals" and return the result.
2393 * No location is added to the kill because the most natural
2394 * location would lie outside the scop. Attaching such a location
2395 * to this tree would extend the scope of the final result
2396 * to include the location.
2398 __isl_give pet_tree
*PetScan::add_kills(__isl_take pet_tree
*tree
,
2399 set
<ValueDecl
*> locals
)
2403 pet_tree
*kill
, *block
;
2404 set
<ValueDecl
*>::iterator it
;
2406 if (locals
.size() == 0)
2408 expr
= pet_expr_new_call(ctx
, "__pencil_kill", locals
.size());
2410 for (it
= locals
.begin(); it
!= locals
.end(); ++it
) {
2412 arg
= extract_access_expr(*it
);
2413 expr
= pet_expr_set_arg(expr
, i
++, arg
);
2415 kill
= pet_tree_new_expr(expr
);
2416 block
= pet_tree_new_block(ctx
, 0, 2);
2417 block
= pet_tree_block_add_child(block
, tree
);
2418 block
= pet_tree_block_add_child(block
, kill
);
2423 /* Check if the scop marked by the user is exactly this Stmt
2424 * or part of this Stmt.
2425 * If so, return a pet_scop corresponding to the marked region.
2426 * Otherwise, return NULL.
2428 * If the scop is not further nested inside a child of "stmt",
2429 * then check if there are any variable declarations before the scop
2430 * inside "stmt". If so, and if these variables are not used
2431 * after the scop, then add kills to the variables.
2433 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
2435 SourceManager
&SM
= PP
.getSourceManager();
2436 unsigned start_off
, end_off
;
2439 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
2440 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
2442 if (start_off
> loc
.end
)
2444 if (end_off
< loc
.start
)
2447 if (start_off
>= loc
.start
&& end_off
<= loc
.end
)
2448 return extract_scop(extract(stmt
));
2450 pet_killed_locals
kl(SM
);
2452 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
2453 Stmt
*child
= *start
;
2456 start_off
= getExpansionOffset(SM
, child
->getLocStart());
2457 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
2458 if (start_off
< loc
.start
&& end_off
>= loc
.end
)
2460 if (start_off
>= loc
.start
)
2462 if (isa
<DeclStmt
>(child
))
2463 kl
.add_locals(cast
<DeclStmt
>(child
));
2467 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
2469 start_off
= SM
.getFileOffset(child
->getLocStart());
2470 if (start_off
>= loc
.end
)
2474 kl
.remove_accessed_after(stmt
, loc
.start
, loc
.end
);
2476 tree
= extract(StmtRange(start
, end
), false, false, stmt
);
2477 tree
= add_kills(tree
, kl
.locals
);
2478 return extract_scop(tree
);
2481 /* Set the size of index "pos" of "array" to "size".
2482 * In particular, add a constraint of the form
2486 * to array->extent and a constraint of the form
2490 * to array->context.
2492 * The domain of "size" is assumed to be zero-dimensional.
2494 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
2495 __isl_take isl_pw_aff
*size
)
2508 valid
= isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
)));
2509 array
->context
= isl_set_intersect(array
->context
, valid
);
2511 dim
= isl_set_get_space(array
->extent
);
2512 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2513 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
2514 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
2515 index
= isl_pw_aff_alloc(univ
, aff
);
2517 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
2518 isl_set_dim(array
->extent
, isl_dim_set
));
2519 id
= isl_set_get_tuple_id(array
->extent
);
2520 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
2521 bound
= isl_pw_aff_lt_set(index
, size
);
2523 array
->extent
= isl_set_intersect(array
->extent
, bound
);
2525 if (!array
->context
|| !array
->extent
)
2526 return pet_array_free(array
);
2530 isl_pw_aff_free(size
);
2534 #ifdef HAVE_DECAYEDTYPE
2536 /* If "qt" is a decayed type, then set *decayed to true and
2537 * return the original type.
2539 static QualType
undecay(QualType qt
, bool *decayed
)
2541 const Type
*type
= qt
.getTypePtr();
2543 *decayed
= isa
<DecayedType
>(type
);
2545 qt
= cast
<DecayedType
>(type
)->getOriginalType();
2551 /* If "qt" is a decayed type, then set *decayed to true and
2552 * return the original type.
2553 * Since this version of clang does not define a DecayedType,
2554 * we cannot obtain the original type even if it had been decayed and
2555 * we set *decayed to false.
2557 static QualType
undecay(QualType qt
, bool *decayed
)
2565 /* Figure out the size of the array at position "pos" and all
2566 * subsequent positions from "qt" and update the corresponding
2567 * argument of "expr" accordingly.
2569 * The initial type (when pos is zero) may be a pointer type decayed
2570 * from an array type, if this initial type is the type of a function
2571 * argument. This only happens if the original array type has
2572 * a constant size in the outer dimension as otherwise we get
2573 * a VariableArrayType. Try and obtain this original type (if available) and
2574 * take the outer array size into account if it was marked static.
2576 __isl_give pet_expr
*PetScan::set_upper_bounds(__isl_take pet_expr
*expr
,
2577 QualType qt
, int pos
)
2579 const ArrayType
*atype
;
2581 bool decayed
= false;
2587 qt
= undecay(qt
, &decayed
);
2589 if (qt
->isPointerType()) {
2590 qt
= qt
->getPointeeType();
2591 return set_upper_bounds(expr
, qt
, pos
+ 1);
2593 if (!qt
->isArrayType())
2596 qt
= qt
->getCanonicalTypeInternal();
2597 atype
= cast
<ArrayType
>(qt
.getTypePtr());
2599 if (decayed
&& atype
->getSizeModifier() != ArrayType::Static
) {
2600 qt
= atype
->getElementType();
2601 return set_upper_bounds(expr
, qt
, pos
+ 1);
2604 if (qt
->isConstantArrayType()) {
2605 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
2606 size
= extract_expr(ca
->getSize());
2607 expr
= pet_expr_set_arg(expr
, pos
, size
);
2608 } else if (qt
->isVariableArrayType()) {
2609 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
2610 size
= extract_expr(vla
->getSizeExpr());
2611 expr
= pet_expr_set_arg(expr
, pos
, size
);
2614 qt
= atype
->getElementType();
2616 return set_upper_bounds(expr
, qt
, pos
+ 1);
2619 /* Construct a pet_expr that holds the sizes of an array of the given type.
2620 * The returned expression is a call expression with as arguments
2621 * the sizes in each dimension. If we are unable to derive the size
2622 * in a given dimension, then the corresponding argument is set to infinity.
2623 * In fact, we initialize all arguments to infinity and then update
2624 * them if we are able to figure out the size.
2626 * The result is stored in the type_size cache so that we can reuse
2627 * it if this method gets called on the same type again later on.
2629 __isl_give pet_expr
*PetScan::get_array_size(QualType qt
)
2632 pet_expr
*expr
, *inf
;
2633 const Type
*type
= qt
.getTypePtr();
2635 if (type_size
.find(type
) != type_size
.end())
2636 return pet_expr_copy(type_size
[type
]);
2638 depth
= pet_clang_array_depth(qt
);
2639 inf
= pet_expr_new_int(isl_val_infty(ctx
));
2640 expr
= pet_expr_new_call(ctx
, "bounds", depth
);
2641 for (int i
= 0; i
< depth
; ++i
)
2642 expr
= pet_expr_set_arg(expr
, i
, pet_expr_copy(inf
));
2645 expr
= set_upper_bounds(expr
, qt
, 0);
2646 type_size
[type
] = pet_expr_copy(expr
);
2651 /* Does "expr" represent the "integer" infinity?
2653 static int is_infty(__isl_keep pet_expr
*expr
)
2658 if (pet_expr_get_type(expr
) != pet_expr_int
)
2660 v
= pet_expr_int_get_val(expr
);
2661 res
= isl_val_is_infty(v
);
2667 /* Figure out the dimensions of an array "array" based on its type
2668 * "qt" and update "array" accordingly.
2670 * We first construct a pet_expr that holds the sizes of the array
2671 * in each dimension. The resulting expression may containing
2672 * infinity values for dimension where we are unable to derive
2673 * a size expression.
2675 * The arguments of the size expression that have a value different from
2676 * infinity are then converted to an affine expression
2677 * within the context "pc" and incorporated into the size of "array".
2678 * If we are unable to convert a size expression to an affine expression or
2679 * if the size is not a (symbolic) constant,
2680 * then we leave the corresponding size of "array" untouched.
2682 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
2683 QualType qt
, __isl_keep pet_context
*pc
)
2691 expr
= get_array_size(qt
);
2693 n
= pet_expr_get_n_arg(expr
);
2694 for (int i
= 0; i
< n
; ++i
) {
2698 arg
= pet_expr_get_arg(expr
, i
);
2699 if (!is_infty(arg
)) {
2702 size
= pet_expr_extract_affine(arg
, pc
);
2703 dim
= isl_pw_aff_dim(size
, isl_dim_in
);
2705 array
= pet_array_free(array
);
2706 else if (isl_pw_aff_involves_nan(size
) ||
2707 isl_pw_aff_involves_dims(size
, isl_dim_in
, 0, dim
))
2708 isl_pw_aff_free(size
);
2710 size
= isl_pw_aff_drop_dims(size
,
2711 isl_dim_in
, 0, dim
);
2712 array
= update_size(array
, i
, size
);
2717 pet_expr_free(expr
);
2722 /* Does "decl" have a definition that we can keep track of in a pet_type?
2724 static bool has_printable_definition(RecordDecl
*decl
)
2726 if (!decl
->getDeclName())
2728 return decl
->getLexicalDeclContext() == decl
->getDeclContext();
2731 /* Construct and return a pet_array corresponding to the variable
2732 * represented by "id".
2733 * In particular, initialize array->extent to
2735 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2737 * and then call set_upper_bounds to set the upper bounds on the indices
2738 * based on the type of the variable. The upper bounds are converted
2739 * to affine expressions within the context "pc".
2741 * If the base type is that of a record with a top-level definition or
2742 * of a typedef and if "types" is not null, then the RecordDecl or
2743 * TypedefType corresponding to the type
2744 * is added to "types".
2746 * If the base type is that of a record with no top-level definition,
2747 * then we replace it by "<subfield>".
2749 struct pet_array
*PetScan::extract_array(__isl_keep isl_id
*id
,
2750 PetTypes
*types
, __isl_keep pet_context
*pc
)
2752 struct pet_array
*array
;
2753 QualType qt
= pet_id_get_array_type(id
);
2754 int depth
= pet_clang_array_depth(qt
);
2755 QualType base
= pet_clang_base_type(qt
);
2759 array
= isl_calloc_type(ctx
, struct pet_array
);
2763 space
= isl_space_set_alloc(ctx
, 0, depth
);
2764 space
= isl_space_set_tuple_id(space
, isl_dim_set
, isl_id_copy(id
));
2766 array
->extent
= isl_set_nat_universe(space
);
2768 space
= isl_space_params_alloc(ctx
, 0);
2769 array
->context
= isl_set_universe(space
);
2771 array
= set_upper_bounds(array
, qt
, pc
);
2775 name
= base
.getAsString();
2778 if (isa
<TypedefType
>(base
)) {
2779 types
->insert(cast
<TypedefType
>(base
)->getDecl());
2780 } else if (base
->isRecordType()) {
2781 RecordDecl
*decl
= pet_clang_record_decl(base
);
2782 TypedefNameDecl
*typedecl
;
2783 typedecl
= decl
->getTypedefNameForAnonDecl();
2785 types
->insert(typedecl
);
2786 else if (has_printable_definition(decl
))
2787 types
->insert(decl
);
2789 name
= "<subfield>";
2793 array
->element_type
= strdup(name
.c_str());
2794 array
->element_is_record
= base
->isRecordType();
2795 array
->element_size
= size_in_bytes(ast_context
, base
);
2800 /* Construct and return a pet_array corresponding to the variable "decl".
2802 struct pet_array
*PetScan::extract_array(ValueDecl
*decl
,
2803 PetTypes
*types
, __isl_keep pet_context
*pc
)
2808 id
= pet_id_from_decl(ctx
, decl
);
2809 array
= extract_array(id
, types
, pc
);
2815 /* Construct and return a pet_array corresponding to the sequence
2816 * of declarations represented by "decls".
2817 * The upper bounds of the array are converted to affine expressions
2818 * within the context "pc".
2819 * If the sequence contains a single declaration, then it corresponds
2820 * to a simple array access. Otherwise, it corresponds to a member access,
2821 * with the declaration for the substructure following that of the containing
2822 * structure in the sequence of declarations.
2823 * We start with the outermost substructure and then combine it with
2824 * information from the inner structures.
2826 * Additionally, keep track of all required types in "types".
2828 struct pet_array
*PetScan::extract_array(__isl_keep isl_id_list
*decls
,
2829 PetTypes
*types
, __isl_keep pet_context
*pc
)
2833 struct pet_array
*array
;
2835 id
= isl_id_list_get_id(decls
, 0);
2836 array
= extract_array(id
, types
, pc
);
2839 n
= isl_id_list_n_id(decls
);
2840 for (i
= 1; i
< n
; ++i
) {
2841 struct pet_array
*parent
;
2842 const char *base_name
, *field_name
;
2846 id
= isl_id_list_get_id(decls
, i
);
2847 array
= extract_array(id
, types
, pc
);
2850 return pet_array_free(parent
);
2852 base_name
= isl_set_get_tuple_name(parent
->extent
);
2853 field_name
= isl_set_get_tuple_name(array
->extent
);
2854 product_name
= pet_array_member_access_name(ctx
,
2855 base_name
, field_name
);
2857 array
->extent
= isl_set_product(isl_set_copy(parent
->extent
),
2860 array
->extent
= isl_set_set_tuple_name(array
->extent
,
2862 array
->context
= isl_set_intersect(array
->context
,
2863 isl_set_copy(parent
->context
));
2865 pet_array_free(parent
);
2868 if (!array
->extent
|| !array
->context
|| !product_name
)
2869 return pet_array_free(array
);
2875 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
2876 RecordDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2877 std::set
<TypeDecl
*> &types_done
);
2878 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
2879 TypedefNameDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2880 std::set
<TypeDecl
*> &types_done
);
2882 /* For each of the fields of "decl" that is itself a record type
2883 * or a typedef, add a corresponding pet_type to "scop".
2885 static struct pet_scop
*add_field_types(isl_ctx
*ctx
, struct pet_scop
*scop
,
2886 RecordDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2887 std::set
<TypeDecl
*> &types_done
)
2889 RecordDecl::field_iterator it
;
2891 for (it
= decl
->field_begin(); it
!= decl
->field_end(); ++it
) {
2892 QualType type
= it
->getType();
2894 if (isa
<TypedefType
>(type
)) {
2895 TypedefNameDecl
*typedefdecl
;
2897 typedefdecl
= cast
<TypedefType
>(type
)->getDecl();
2898 scop
= add_type(ctx
, scop
, typedefdecl
,
2899 PP
, types
, types_done
);
2900 } else if (type
->isRecordType()) {
2903 record
= pet_clang_record_decl(type
);
2904 scop
= add_type(ctx
, scop
, record
,
2905 PP
, types
, types_done
);
2912 /* Add a pet_type corresponding to "decl" to "scop", provided
2913 * it is a member of types.records and it has not been added before
2914 * (i.e., it is not a member of "types_done").
2916 * Since we want the user to be able to print the types
2917 * in the order in which they appear in the scop, we need to
2918 * make sure that types of fields in a structure appear before
2919 * that structure. We therefore call ourselves recursively
2920 * through add_field_types on the types of all record subfields.
2922 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
2923 RecordDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2924 std::set
<TypeDecl
*> &types_done
)
2927 llvm::raw_string_ostream
S(s
);
2929 if (types
.records
.find(decl
) == types
.records
.end())
2931 if (types_done
.find(decl
) != types_done
.end())
2934 add_field_types(ctx
, scop
, decl
, PP
, types
, types_done
);
2936 if (strlen(decl
->getName().str().c_str()) == 0)
2939 decl
->print(S
, PrintingPolicy(PP
.getLangOpts()));
2942 scop
->types
[scop
->n_type
] = pet_type_alloc(ctx
,
2943 decl
->getName().str().c_str(), s
.c_str());
2944 if (!scop
->types
[scop
->n_type
])
2945 return pet_scop_free(scop
);
2947 types_done
.insert(decl
);
2954 /* Add a pet_type corresponding to "decl" to "scop", provided
2955 * it is a member of types.typedefs and it has not been added before
2956 * (i.e., it is not a member of "types_done").
2958 * If the underlying type is a structure, then we print the typedef
2959 * ourselves since clang does not print the definition of the structure
2960 * in the typedef. We also make sure in this case that the types of
2961 * the fields in the structure are added first.
2963 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
2964 TypedefNameDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2965 std::set
<TypeDecl
*> &types_done
)
2968 llvm::raw_string_ostream
S(s
);
2969 QualType qt
= decl
->getUnderlyingType();
2971 if (types
.typedefs
.find(decl
) == types
.typedefs
.end())
2973 if (types_done
.find(decl
) != types_done
.end())
2976 if (qt
->isRecordType()) {
2977 RecordDecl
*rec
= pet_clang_record_decl(qt
);
2979 add_field_types(ctx
, scop
, rec
, PP
, types
, types_done
);
2981 rec
->print(S
, PrintingPolicy(PP
.getLangOpts()));
2983 S
<< decl
->getName();
2985 decl
->print(S
, PrintingPolicy(PP
.getLangOpts()));
2989 scop
->types
[scop
->n_type
] = pet_type_alloc(ctx
,
2990 decl
->getName().str().c_str(), s
.c_str());
2991 if (!scop
->types
[scop
->n_type
])
2992 return pet_scop_free(scop
);
2994 types_done
.insert(decl
);
3001 /* Construct a list of pet_arrays, one for each array (or scalar)
3002 * accessed inside "scop", add this list to "scop" and return the result.
3003 * The upper bounds of the arrays are converted to affine expressions
3004 * within the context "pc".
3006 * The context of "scop" is updated with the intersection of
3007 * the contexts of all arrays, i.e., constraints on the parameters
3008 * that ensure that the arrays have a valid (non-negative) size.
3010 * If any of the extracted arrays refers to a member access or
3011 * has a typedef'd type as base type,
3012 * then also add the required types to "scop".
3014 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
,
3015 __isl_keep pet_context
*pc
)
3018 array_desc_set arrays
;
3019 array_desc_set::iterator it
;
3021 std::set
<TypeDecl
*> types_done
;
3022 std::set
<clang::RecordDecl
*, less_name
>::iterator records_it
;
3023 std::set
<clang::TypedefNameDecl
*, less_name
>::iterator typedefs_it
;
3025 struct pet_array
**scop_arrays
;
3030 pet_scop_collect_arrays(scop
, arrays
);
3031 if (arrays
.size() == 0)
3034 n_array
= scop
->n_array
;
3036 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
3037 n_array
+ arrays
.size());
3040 scop
->arrays
= scop_arrays
;
3042 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
3043 struct pet_array
*array
;
3044 array
= extract_array(*it
, &types
, pc
);
3045 scop
->arrays
[n_array
+ i
] = array
;
3046 if (!scop
->arrays
[n_array
+ i
])
3049 scop
->context
= isl_set_intersect(scop
->context
,
3050 isl_set_copy(array
->context
));
3055 n
= types
.records
.size() + types
.typedefs
.size();
3059 scop
->types
= isl_alloc_array(ctx
, struct pet_type
*, n
);
3063 for (records_it
= types
.records
.begin();
3064 records_it
!= types
.records
.end(); ++records_it
)
3065 scop
= add_type(ctx
, scop
, *records_it
, PP
, types
, types_done
);
3067 for (typedefs_it
= types
.typedefs
.begin();
3068 typedefs_it
!= types
.typedefs
.end(); ++typedefs_it
)
3069 scop
= add_type(ctx
, scop
, *typedefs_it
, PP
, types
, types_done
);
3073 pet_scop_free(scop
);
3077 /* Bound all parameters in scop->context to the possible values
3078 * of the corresponding C variable.
3080 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
3087 n
= isl_set_dim(scop
->context
, isl_dim_param
);
3088 for (int i
= 0; i
< n
; ++i
) {
3092 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
3093 if (pet_nested_in_id(id
)) {
3095 isl_die(isl_set_get_ctx(scop
->context
),
3097 "unresolved nested parameter", goto error
);
3099 decl
= pet_id_get_decl(id
);
3102 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
3110 pet_scop_free(scop
);
3114 /* Construct a pet_scop from the given function.
3116 * If the scop was delimited by scop and endscop pragmas, then we override
3117 * the file offsets by those derived from the pragmas.
3119 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
3124 stmt
= fd
->getBody();
3126 if (options
->autodetect
) {
3127 set_current_stmt(stmt
);
3128 scop
= extract_scop(extract(stmt
, true));
3130 current_line
= loc
.start_line
;
3132 scop
= pet_scop_update_start_end(scop
, loc
.start
, loc
.end
);
3134 scop
= add_parameter_bounds(scop
);
3135 scop
= pet_scop_gist(scop
, value_bounds
);
3140 /* Update this->last_line and this->current_line based on the fact
3141 * that we are about to consider "stmt".
3143 void PetScan::set_current_stmt(Stmt
*stmt
)
3145 SourceLocation loc
= stmt
->getLocStart();
3146 SourceManager
&SM
= PP
.getSourceManager();
3148 last_line
= current_line
;
3149 current_line
= SM
.getExpansionLineNumber(loc
);
3152 /* Is the current statement marked by an independent pragma?
3153 * That is, is there an independent pragma on a line between
3154 * the line of the current statement and the line of the previous statement.
3155 * The search is not implemented very efficiently. We currently
3156 * assume that there are only a few independent pragmas, if any.
3158 bool PetScan::is_current_stmt_marked_independent()
3160 for (unsigned i
= 0; i
< independent
.size(); ++i
) {
3161 unsigned line
= independent
[i
].line
;
3163 if (last_line
< line
&& line
< current_line
)