2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2015 Ecole Normale Superieure. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
41 #include <llvm/Support/raw_ostream.h>
42 #include <clang/AST/ASTContext.h>
43 #include <clang/AST/ASTDiagnostic.h>
44 #include <clang/AST/Attr.h>
45 #include <clang/AST/Expr.h>
46 #include <clang/AST/RecursiveASTVisitor.h>
49 #include <isl/space.h>
52 #include <isl/union_set.h>
63 #include "scop_plus.h"
65 #include "tree2scop.h"
68 using namespace clang
;
70 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
80 return pet_op_post_inc
;
82 return pet_op_post_dec
;
84 return pet_op_pre_inc
;
86 return pet_op_pre_dec
;
92 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
96 return pet_op_add_assign
;
98 return pet_op_sub_assign
;
100 return pet_op_mul_assign
;
102 return pet_op_div_assign
;
104 return pet_op_assign
;
146 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
147 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
149 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
150 SourceLocation(), var
, false, var
->getInnerLocStart(),
151 var
->getType(), VK_LValue
);
153 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
154 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
156 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
157 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
161 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
163 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
164 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
168 #ifdef GETTYPEINFORETURNSTYPEINFO
170 static int size_in_bytes(ASTContext
&context
, QualType type
)
172 return context
.getTypeInfo(type
).Width
/ 8;
177 static int size_in_bytes(ASTContext
&context
, QualType type
)
179 return context
.getTypeInfo(type
).first
/ 8;
184 /* Check if the element type corresponding to the given array type
185 * has a const qualifier.
187 static bool const_base(QualType qt
)
189 const Type
*type
= qt
.getTypePtr();
191 if (type
->isPointerType())
192 return const_base(type
->getPointeeType());
193 if (type
->isArrayType()) {
194 const ArrayType
*atype
;
195 type
= type
->getCanonicalTypeInternal().getTypePtr();
196 atype
= cast
<ArrayType
>(type
);
197 return const_base(atype
->getElementType());
200 return qt
.isConstQualified();
203 /* Create an isl_id that refers to the named declarator "decl".
205 static __isl_give isl_id
*create_decl_id(isl_ctx
*ctx
, NamedDecl
*decl
)
207 return isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
212 std::map
<const Type
*, pet_expr
*>::iterator it
;
213 std::map
<FunctionDecl
*, pet_function_summary
*>::iterator it_s
;
215 for (it
= type_size
.begin(); it
!= type_size
.end(); ++it
)
216 pet_expr_free(it
->second
);
217 for (it_s
= summary_cache
.begin(); it_s
!= summary_cache
.end(); ++it_s
)
218 pet_function_summary_free(it_s
->second
);
220 isl_union_map_free(value_bounds
);
223 /* Report a diagnostic, unless autodetect is set.
225 void PetScan::report(Stmt
*stmt
, unsigned id
)
227 if (options
->autodetect
)
230 SourceLocation loc
= stmt
->getLocStart();
231 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
232 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
235 /* Called if we found something we (currently) cannot handle.
236 * We'll provide more informative warnings later.
238 * We only actually complain if autodetect is false.
240 void PetScan::unsupported(Stmt
*stmt
)
242 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
243 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
248 /* Report an unsupported statement type, unless autodetect is set.
250 void PetScan::report_unsupported_statement_type(Stmt
*stmt
)
252 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
253 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
254 "this type of statement is not supported");
258 /* Report a missing prototype, unless autodetect is set.
260 void PetScan::report_prototype_required(Stmt
*stmt
)
262 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
263 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
264 "prototype required");
268 /* Report a missing increment, unless autodetect is set.
270 void PetScan::report_missing_increment(Stmt
*stmt
)
272 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
273 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
274 "missing increment");
278 /* Report a missing summary function, unless autodetect is set.
280 void PetScan::report_missing_summary_function(Stmt
*stmt
)
282 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
283 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
284 "missing summary function");
288 /* Report a missing summary function body, unless autodetect is set.
290 void PetScan::report_missing_summary_function_body(Stmt
*stmt
)
292 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
293 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
294 "missing summary function body");
298 /* Extract an integer from "val", which is assumed to be non-negative.
300 static __isl_give isl_val
*extract_unsigned(isl_ctx
*ctx
,
301 const llvm::APInt
&val
)
304 const uint64_t *data
;
306 data
= val
.getRawData();
307 n
= val
.getNumWords();
308 return isl_val_int_from_chunks(ctx
, n
, sizeof(uint64_t), data
);
311 /* Extract an integer from "val". If "is_signed" is set, then "val"
312 * is signed. Otherwise it it unsigned.
314 static __isl_give isl_val
*extract_int(isl_ctx
*ctx
, bool is_signed
,
317 int is_negative
= is_signed
&& val
.isNegative();
323 v
= extract_unsigned(ctx
, val
);
330 /* Extract an integer from "expr".
332 __isl_give isl_val
*PetScan::extract_int(isl_ctx
*ctx
, IntegerLiteral
*expr
)
334 const Type
*type
= expr
->getType().getTypePtr();
335 bool is_signed
= type
->hasSignedIntegerRepresentation();
337 return ::extract_int(ctx
, is_signed
, expr
->getValue());
340 /* Extract an integer from "expr".
341 * Return NULL if "expr" does not (obviously) represent an integer.
343 __isl_give isl_val
*PetScan::extract_int(clang::ParenExpr
*expr
)
345 return extract_int(expr
->getSubExpr());
348 /* Extract an integer from "expr".
349 * Return NULL if "expr" does not (obviously) represent an integer.
351 __isl_give isl_val
*PetScan::extract_int(clang::Expr
*expr
)
353 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
354 return extract_int(ctx
, cast
<IntegerLiteral
>(expr
));
355 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
356 return extract_int(cast
<ParenExpr
>(expr
));
362 /* Extract a pet_expr from the APInt "val", which is assumed
363 * to be non-negative.
365 __isl_give pet_expr
*PetScan::extract_expr(const llvm::APInt
&val
)
367 return pet_expr_new_int(extract_unsigned(ctx
, val
));
370 /* Return the number of bits needed to represent the type "qt",
371 * if it is an integer type. Otherwise return 0.
372 * If qt is signed then return the opposite of the number of bits.
374 static int get_type_size(QualType qt
, ASTContext
&ast_context
)
378 if (!qt
->isIntegerType())
381 size
= ast_context
.getIntWidth(qt
);
382 if (!qt
->isUnsignedIntegerType())
388 /* Return the number of bits needed to represent the type of "decl",
389 * if it is an integer type. Otherwise return 0.
390 * If qt is signed then return the opposite of the number of bits.
392 static int get_type_size(ValueDecl
*decl
)
394 return get_type_size(decl
->getType(), decl
->getASTContext());
397 /* Bound parameter "pos" of "set" to the possible values of "decl".
399 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
400 unsigned pos
, ValueDecl
*decl
)
406 ctx
= isl_set_get_ctx(set
);
407 type_size
= get_type_size(decl
);
409 isl_die(ctx
, isl_error_invalid
, "not an integer type",
410 return isl_set_free(set
));
412 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
413 bound
= isl_val_int_from_ui(ctx
, type_size
);
414 bound
= isl_val_2exp(bound
);
415 bound
= isl_val_sub_ui(bound
, 1);
416 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
, bound
);
418 bound
= isl_val_int_from_ui(ctx
, -type_size
- 1);
419 bound
= isl_val_2exp(bound
);
420 bound
= isl_val_sub_ui(bound
, 1);
421 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
,
422 isl_val_copy(bound
));
423 bound
= isl_val_neg(bound
);
424 bound
= isl_val_sub_ui(bound
, 1);
425 set
= isl_set_lower_bound_val(set
, isl_dim_param
, pos
, bound
);
431 __isl_give pet_expr
*PetScan::extract_index_expr(ImplicitCastExpr
*expr
)
433 return extract_index_expr(expr
->getSubExpr());
436 /* Return the depth of an array of the given type.
438 static int array_depth(const Type
*type
)
440 if (type
->isPointerType())
441 return 1 + array_depth(type
->getPointeeType().getTypePtr());
442 if (type
->isArrayType()) {
443 const ArrayType
*atype
;
444 type
= type
->getCanonicalTypeInternal().getTypePtr();
445 atype
= cast
<ArrayType
>(type
);
446 return 1 + array_depth(atype
->getElementType().getTypePtr());
451 /* Return the depth of the array accessed by the index expression "index".
452 * If "index" is an affine expression, i.e., if it does not access
453 * any array, then return 1.
454 * If "index" represent a member access, i.e., if its range is a wrapped
455 * relation, then return the sum of the depth of the array of structures
456 * and that of the member inside the structure.
458 static int extract_depth(__isl_keep isl_multi_pw_aff
*index
)
466 if (isl_multi_pw_aff_range_is_wrapping(index
)) {
467 int domain_depth
, range_depth
;
468 isl_multi_pw_aff
*domain
, *range
;
470 domain
= isl_multi_pw_aff_copy(index
);
471 domain
= isl_multi_pw_aff_range_factor_domain(domain
);
472 domain_depth
= extract_depth(domain
);
473 isl_multi_pw_aff_free(domain
);
474 range
= isl_multi_pw_aff_copy(index
);
475 range
= isl_multi_pw_aff_range_factor_range(range
);
476 range_depth
= extract_depth(range
);
477 isl_multi_pw_aff_free(range
);
479 return domain_depth
+ range_depth
;
482 if (!isl_multi_pw_aff_has_tuple_id(index
, isl_dim_out
))
485 id
= isl_multi_pw_aff_get_tuple_id(index
, isl_dim_out
);
488 decl
= (ValueDecl
*) isl_id_get_user(id
);
491 return array_depth(decl
->getType().getTypePtr());
494 /* Return the depth of the array accessed by the access expression "expr".
496 static int extract_depth(__isl_keep pet_expr
*expr
)
498 isl_multi_pw_aff
*index
;
501 index
= pet_expr_access_get_index(expr
);
502 depth
= extract_depth(index
);
503 isl_multi_pw_aff_free(index
);
508 /* Construct a pet_expr representing an index expression for an access
509 * to the variable referenced by "expr".
511 * If "expr" references an enum constant, then return an integer expression
512 * instead, representing the value of the enum constant.
514 __isl_give pet_expr
*PetScan::extract_index_expr(DeclRefExpr
*expr
)
516 return extract_index_expr(expr
->getDecl());
519 /* Construct a pet_expr representing an index expression for an access
520 * to the variable "decl".
522 * If "decl" is an enum constant, then we return an integer expression
523 * instead, representing the value of the enum constant.
525 __isl_give pet_expr
*PetScan::extract_index_expr(ValueDecl
*decl
)
530 if (isa
<EnumConstantDecl
>(decl
))
531 return extract_expr(cast
<EnumConstantDecl
>(decl
));
533 id
= create_decl_id(ctx
, decl
);
534 space
= isl_space_alloc(ctx
, 0, 0, 0);
535 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
537 return pet_expr_from_index(isl_multi_pw_aff_zero(space
));
540 /* Construct a pet_expr representing the index expression "expr"
541 * Return NULL on error.
543 * If "expr" is a reference to an enum constant, then return
544 * an integer expression instead, representing the value of the enum constant.
546 __isl_give pet_expr
*PetScan::extract_index_expr(Expr
*expr
)
548 switch (expr
->getStmtClass()) {
549 case Stmt::ImplicitCastExprClass
:
550 return extract_index_expr(cast
<ImplicitCastExpr
>(expr
));
551 case Stmt::DeclRefExprClass
:
552 return extract_index_expr(cast
<DeclRefExpr
>(expr
));
553 case Stmt::ArraySubscriptExprClass
:
554 return extract_index_expr(cast
<ArraySubscriptExpr
>(expr
));
555 case Stmt::IntegerLiteralClass
:
556 return extract_expr(cast
<IntegerLiteral
>(expr
));
557 case Stmt::MemberExprClass
:
558 return extract_index_expr(cast
<MemberExpr
>(expr
));
565 /* Extract an index expression from the given array subscript expression.
567 * We first extract an index expression from the base.
568 * This will result in an index expression with a range that corresponds
569 * to the earlier indices.
570 * We then extract the current index and let
571 * pet_expr_access_subscript combine the two.
573 __isl_give pet_expr
*PetScan::extract_index_expr(ArraySubscriptExpr
*expr
)
575 Expr
*base
= expr
->getBase();
576 Expr
*idx
= expr
->getIdx();
580 base_expr
= extract_index_expr(base
);
581 index
= extract_expr(idx
);
583 base_expr
= pet_expr_access_subscript(base_expr
, index
);
588 /* Extract an index expression from a member expression.
590 * If the base access (to the structure containing the member)
595 * and the member is called "f", then the member access is of
600 * If the member access is to an anonymous struct, then simply return
604 * If the member access in the source code is of the form
608 * then it is treated as
612 __isl_give pet_expr
*PetScan::extract_index_expr(MemberExpr
*expr
)
614 Expr
*base
= expr
->getBase();
615 FieldDecl
*field
= cast
<FieldDecl
>(expr
->getMemberDecl());
616 pet_expr
*base_index
;
619 base_index
= extract_index_expr(base
);
621 if (expr
->isArrow()) {
622 pet_expr
*index
= pet_expr_new_int(isl_val_zero(ctx
));
623 base_index
= pet_expr_access_subscript(base_index
, index
);
626 if (field
->isAnonymousStructOrUnion())
629 id
= create_decl_id(ctx
, field
);
631 return pet_expr_access_member(base_index
, id
);
634 /* Mark the given access pet_expr as a write.
636 static __isl_give pet_expr
*mark_write(__isl_take pet_expr
*access
)
638 access
= pet_expr_access_set_write(access
, 1);
639 access
= pet_expr_access_set_read(access
, 0);
644 /* Mark the given (read) access pet_expr as also possibly being written.
645 * That is, initialize the may write access relation from the may read relation
646 * and initialize the must write access relation to the empty relation.
648 static __isl_give pet_expr
*mark_may_write(__isl_take pet_expr
*expr
)
650 isl_union_map
*access
;
651 isl_union_map
*empty
;
653 access
= pet_expr_access_get_dependent_access(expr
,
654 pet_expr_access_may_read
);
655 empty
= isl_union_map_empty(isl_union_map_get_space(access
));
656 expr
= pet_expr_access_set_access(expr
, pet_expr_access_may_write
,
658 expr
= pet_expr_access_set_access(expr
, pet_expr_access_must_write
,
664 /* Construct a pet_expr representing a unary operator expression.
666 __isl_give pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
672 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
673 if (op
== pet_op_last
) {
678 arg
= extract_expr(expr
->getSubExpr());
680 if (expr
->isIncrementDecrementOp() &&
681 pet_expr_get_type(arg
) == pet_expr_access
) {
682 arg
= mark_write(arg
);
683 arg
= pet_expr_access_set_read(arg
, 1);
686 type_size
= get_type_size(expr
->getType(), ast_context
);
687 return pet_expr_new_unary(type_size
, op
, arg
);
690 /* Construct a pet_expr representing a binary operator expression.
692 * If the top level operator is an assignment and the LHS is an access,
693 * then we mark that access as a write. If the operator is a compound
694 * assignment, the access is marked as both a read and a write.
696 __isl_give pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
702 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
703 if (op
== pet_op_last
) {
708 lhs
= extract_expr(expr
->getLHS());
709 rhs
= extract_expr(expr
->getRHS());
711 if (expr
->isAssignmentOp() &&
712 pet_expr_get_type(lhs
) == pet_expr_access
) {
713 lhs
= mark_write(lhs
);
714 if (expr
->isCompoundAssignmentOp())
715 lhs
= pet_expr_access_set_read(lhs
, 1);
718 type_size
= get_type_size(expr
->getType(), ast_context
);
719 return pet_expr_new_binary(type_size
, op
, lhs
, rhs
);
722 /* Construct a pet_tree for a variable declaration.
724 __isl_give pet_tree
*PetScan::extract(Decl
*decl
)
730 vd
= cast
<VarDecl
>(decl
);
732 lhs
= extract_access_expr(vd
);
733 lhs
= mark_write(lhs
);
735 tree
= pet_tree_new_decl(lhs
);
737 rhs
= extract_expr(vd
->getInit());
738 tree
= pet_tree_new_decl_init(lhs
, rhs
);
744 /* Construct a pet_tree for a variable declaration statement.
745 * If the declaration statement declares multiple variables,
746 * then return a group of pet_trees, one for each declared variable.
748 __isl_give pet_tree
*PetScan::extract(DeclStmt
*stmt
)
753 if (!stmt
->isSingleDecl()) {
754 const DeclGroup
&group
= stmt
->getDeclGroup().getDeclGroup();
756 tree
= pet_tree_new_block(ctx
, 0, n
);
758 for (int i
= 0; i
< n
; ++i
) {
762 tree_i
= extract(group
[i
]);
763 loc
= construct_pet_loc(group
[i
]->getSourceRange(),
765 tree_i
= pet_tree_set_loc(tree_i
, loc
);
766 tree
= pet_tree_block_add_child(tree
, tree_i
);
772 return extract(stmt
->getSingleDecl());
775 /* Construct a pet_expr representing a conditional operation.
777 __isl_give pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
779 pet_expr
*cond
, *lhs
, *rhs
;
782 cond
= extract_expr(expr
->getCond());
783 lhs
= extract_expr(expr
->getTrueExpr());
784 rhs
= extract_expr(expr
->getFalseExpr());
786 return pet_expr_new_ternary(cond
, lhs
, rhs
);
789 __isl_give pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
791 return extract_expr(expr
->getSubExpr());
794 /* Construct a pet_expr representing a floating point value.
796 * If the floating point literal does not appear in a macro,
797 * then we use the original representation in the source code
798 * as the string representation. Otherwise, we use the pretty
799 * printer to produce a string representation.
801 __isl_give pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
805 const LangOptions
&LO
= PP
.getLangOpts();
806 SourceLocation loc
= expr
->getLocation();
808 if (!loc
.isMacroID()) {
809 SourceManager
&SM
= PP
.getSourceManager();
810 unsigned len
= Lexer::MeasureTokenLength(loc
, SM
, LO
);
811 s
= string(SM
.getCharacterData(loc
), len
);
813 llvm::raw_string_ostream
S(s
);
814 expr
->printPretty(S
, 0, PrintingPolicy(LO
));
817 d
= expr
->getValueAsApproximateDouble();
818 return pet_expr_new_double(ctx
, d
, s
.c_str());
821 /* Convert the index expression "index" into an access pet_expr of type "qt".
823 __isl_give pet_expr
*PetScan::extract_access_expr(QualType qt
,
824 __isl_take pet_expr
*index
)
829 depth
= extract_depth(index
);
830 type_size
= get_type_size(qt
, ast_context
);
832 index
= pet_expr_set_type_size(index
, type_size
);
833 index
= pet_expr_access_set_depth(index
, depth
);
838 /* Extract an index expression from "expr" and then convert it into
839 * an access pet_expr.
841 * If "expr" is a reference to an enum constant, then return
842 * an integer expression instead, representing the value of the enum constant.
844 __isl_give pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
848 index
= extract_index_expr(expr
);
850 if (pet_expr_get_type(index
) == pet_expr_int
)
853 return extract_access_expr(expr
->getType(), index
);
856 /* Extract an index expression from "decl" and then convert it into
857 * an access pet_expr.
859 __isl_give pet_expr
*PetScan::extract_access_expr(ValueDecl
*decl
)
861 return extract_access_expr(decl
->getType(), extract_index_expr(decl
));
864 __isl_give pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
866 return extract_expr(expr
->getSubExpr());
869 /* Extract an assume statement from the argument "expr"
870 * of a __pencil_assume statement.
872 __isl_give pet_expr
*PetScan::extract_assume(Expr
*expr
)
874 return pet_expr_new_unary(0, pet_op_assume
, extract_expr(expr
));
877 /* Construct a pet_expr corresponding to the function call argument "expr".
878 * The argument appears in position "pos" of a call to function "fd".
880 * If we are passing along a pointer to an array element
881 * or an entire row or even higher dimensional slice of an array,
882 * then the function being called may write into the array.
884 * We assume here that if the function is declared to take a pointer
885 * to a const type, then the function may only perform a read
886 * and that otherwise, it may either perform a read or a write (or both).
887 * We only perform this check if "detect_writes" is set.
889 __isl_give pet_expr
*PetScan::extract_argument(FunctionDecl
*fd
, int pos
,
890 Expr
*expr
, bool detect_writes
)
893 int is_addr
= 0, is_partial
= 0;
895 while (expr
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
896 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(expr
);
897 expr
= ice
->getSubExpr();
899 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
) {
900 UnaryOperator
*op
= cast
<UnaryOperator
>(expr
);
901 if (op
->getOpcode() == UO_AddrOf
) {
903 expr
= op
->getSubExpr();
906 res
= extract_expr(expr
);
909 if (array_depth(expr
->getType().getTypePtr()) > 0)
911 if (detect_writes
&& (is_addr
|| is_partial
) &&
912 pet_expr_get_type(res
) == pet_expr_access
) {
914 if (!fd
->hasPrototype()) {
915 report_prototype_required(expr
);
916 return pet_expr_free(res
);
918 parm
= fd
->getParamDecl(pos
);
919 if (!const_base(parm
->getType()))
920 res
= mark_may_write(res
);
924 res
= pet_expr_new_unary(0, pet_op_address_of
, res
);
928 /* Find the first FunctionDecl with the given name.
929 * "call" is the corresponding call expression and is only used
930 * for reporting errors.
932 * Return NULL on error.
934 FunctionDecl
*PetScan::find_decl_from_name(CallExpr
*call
, string name
)
936 TranslationUnitDecl
*tu
= ast_context
.getTranslationUnitDecl();
937 DeclContext::decl_iterator begin
= tu
->decls_begin();
938 DeclContext::decl_iterator end
= tu
->decls_end();
939 for (DeclContext::decl_iterator i
= begin
; i
!= end
; ++i
) {
940 FunctionDecl
*fd
= dyn_cast
<FunctionDecl
>(*i
);
943 if (fd
->getName().str().compare(name
) != 0)
947 report_missing_summary_function_body(call
);
950 report_missing_summary_function(call
);
954 /* Return the FunctionDecl for the summary function associated to the
955 * function called by "call".
957 * In particular, if the pencil option is set, then
958 * search for an annotate attribute formatted as
959 * "pencil_access(name)", where "name" is the name of the summary function.
961 * If no summary function was specified, then return the FunctionDecl
962 * that is actually being called.
964 * Return NULL on error.
966 FunctionDecl
*PetScan::get_summary_function(CallExpr
*call
)
968 FunctionDecl
*decl
= call
->getDirectCallee();
972 if (!options
->pencil
)
975 specific_attr_iterator
<AnnotateAttr
> begin
, end
, i
;
976 begin
= decl
->specific_attr_begin
<AnnotateAttr
>();
977 end
= decl
->specific_attr_end
<AnnotateAttr
>();
978 for (i
= begin
; i
!= end
; ++i
) {
979 string attr
= (*i
)->getAnnotation().str();
981 const char prefix
[] = "pencil_access(";
982 size_t start
= attr
.find(prefix
);
983 if (start
== string::npos
)
985 start
+= strlen(prefix
);
986 string name
= attr
.substr(start
, attr
.find(')') - start
);
988 return find_decl_from_name(call
, name
);
994 /* Construct a pet_expr representing a function call.
996 * In the special case of a "call" to __pencil_assume,
997 * construct an assume expression instead.
999 * In the case of a "call" to __pencil_kill, the arguments
1000 * are neither read nor written (only killed), so there
1001 * is no need to check for writes to these arguments.
1003 * __pencil_assume and __pencil_kill are only recognized
1004 * when the pencil option is set.
1006 __isl_give pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1008 pet_expr
*res
= NULL
;
1014 fd
= expr
->getDirectCallee();
1020 name
= fd
->getDeclName().getAsString();
1021 n_arg
= expr
->getNumArgs();
1023 if (options
->pencil
&& n_arg
== 1 && name
== "__pencil_assume")
1024 return extract_assume(expr
->getArg(0));
1025 is_kill
= options
->pencil
&& name
== "__pencil_kill";
1027 res
= pet_expr_new_call(ctx
, name
.c_str(), n_arg
);
1031 for (int i
= 0; i
< n_arg
; ++i
) {
1032 Expr
*arg
= expr
->getArg(i
);
1033 res
= pet_expr_set_arg(res
, i
,
1034 PetScan::extract_argument(fd
, i
, arg
, !is_kill
));
1037 fd
= get_summary_function(expr
);
1039 return pet_expr_free(res
);
1041 res
= set_summary(res
, fd
);
1046 /* Construct a pet_expr representing a (C style) cast.
1048 __isl_give pet_expr
*PetScan::extract_expr(CStyleCastExpr
*expr
)
1053 arg
= extract_expr(expr
->getSubExpr());
1057 type
= expr
->getTypeAsWritten();
1058 return pet_expr_new_cast(type
.getAsString().c_str(), arg
);
1061 /* Construct a pet_expr representing an integer.
1063 __isl_give pet_expr
*PetScan::extract_expr(IntegerLiteral
*expr
)
1065 return pet_expr_new_int(extract_int(expr
));
1068 /* Construct a pet_expr representing the integer enum constant "ecd".
1070 __isl_give pet_expr
*PetScan::extract_expr(EnumConstantDecl
*ecd
)
1073 const llvm::APSInt
&init
= ecd
->getInitVal();
1074 v
= ::extract_int(ctx
, init
.isSigned(), init
);
1075 return pet_expr_new_int(v
);
1078 /* Try and construct a pet_expr representing "expr".
1080 __isl_give pet_expr
*PetScan::extract_expr(Expr
*expr
)
1082 switch (expr
->getStmtClass()) {
1083 case Stmt::UnaryOperatorClass
:
1084 return extract_expr(cast
<UnaryOperator
>(expr
));
1085 case Stmt::CompoundAssignOperatorClass
:
1086 case Stmt::BinaryOperatorClass
:
1087 return extract_expr(cast
<BinaryOperator
>(expr
));
1088 case Stmt::ImplicitCastExprClass
:
1089 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1090 case Stmt::ArraySubscriptExprClass
:
1091 case Stmt::DeclRefExprClass
:
1092 case Stmt::MemberExprClass
:
1093 return extract_access_expr(expr
);
1094 case Stmt::IntegerLiteralClass
:
1095 return extract_expr(cast
<IntegerLiteral
>(expr
));
1096 case Stmt::FloatingLiteralClass
:
1097 return extract_expr(cast
<FloatingLiteral
>(expr
));
1098 case Stmt::ParenExprClass
:
1099 return extract_expr(cast
<ParenExpr
>(expr
));
1100 case Stmt::ConditionalOperatorClass
:
1101 return extract_expr(cast
<ConditionalOperator
>(expr
));
1102 case Stmt::CallExprClass
:
1103 return extract_expr(cast
<CallExpr
>(expr
));
1104 case Stmt::CStyleCastExprClass
:
1105 return extract_expr(cast
<CStyleCastExpr
>(expr
));
1112 /* Check if the given initialization statement is an assignment.
1113 * If so, return that assignment. Otherwise return NULL.
1115 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1117 BinaryOperator
*ass
;
1119 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1122 ass
= cast
<BinaryOperator
>(init
);
1123 if (ass
->getOpcode() != BO_Assign
)
1129 /* Check if the given initialization statement is a declaration
1130 * of a single variable.
1131 * If so, return that declaration. Otherwise return NULL.
1133 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1137 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1140 decl
= cast
<DeclStmt
>(init
);
1142 if (!decl
->isSingleDecl())
1145 return decl
->getSingleDecl();
1148 /* Given the assignment operator in the initialization of a for loop,
1149 * extract the induction variable, i.e., the (integer)variable being
1152 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1159 lhs
= init
->getLHS();
1160 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1165 ref
= cast
<DeclRefExpr
>(lhs
);
1166 decl
= ref
->getDecl();
1167 type
= decl
->getType().getTypePtr();
1169 if (!type
->isIntegerType()) {
1177 /* Given the initialization statement of a for loop and the single
1178 * declaration in this initialization statement,
1179 * extract the induction variable, i.e., the (integer) variable being
1182 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1186 vd
= cast
<VarDecl
>(decl
);
1188 const QualType type
= vd
->getType();
1189 if (!type
->isIntegerType()) {
1194 if (!vd
->getInit()) {
1202 /* Check that op is of the form iv++ or iv--.
1203 * Return a pet_expr representing "1" or "-1" accordingly.
1205 __isl_give pet_expr
*PetScan::extract_unary_increment(
1206 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1212 if (!op
->isIncrementDecrementOp()) {
1217 sub
= op
->getSubExpr();
1218 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1223 ref
= cast
<DeclRefExpr
>(sub
);
1224 if (ref
->getDecl() != iv
) {
1229 if (op
->isIncrementOp())
1230 v
= isl_val_one(ctx
);
1232 v
= isl_val_negone(ctx
);
1234 return pet_expr_new_int(v
);
1237 /* Check if op is of the form
1241 * and return the increment "expr - iv" as a pet_expr.
1243 __isl_give pet_expr
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1244 clang::ValueDecl
*iv
)
1249 pet_expr
*expr
, *expr_iv
;
1251 if (op
->getOpcode() != BO_Assign
) {
1257 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1262 ref
= cast
<DeclRefExpr
>(lhs
);
1263 if (ref
->getDecl() != iv
) {
1268 expr
= extract_expr(op
->getRHS());
1269 expr_iv
= extract_expr(lhs
);
1271 type_size
= get_type_size(iv
->getType(), ast_context
);
1272 return pet_expr_new_binary(type_size
, pet_op_sub
, expr
, expr_iv
);
1275 /* Check that op is of the form iv += cst or iv -= cst
1276 * and return a pet_expr corresponding to cst or -cst accordingly.
1278 __isl_give pet_expr
*PetScan::extract_compound_increment(
1279 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1285 BinaryOperatorKind opcode
;
1287 opcode
= op
->getOpcode();
1288 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1292 if (opcode
== BO_SubAssign
)
1296 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1301 ref
= cast
<DeclRefExpr
>(lhs
);
1302 if (ref
->getDecl() != iv
) {
1307 expr
= extract_expr(op
->getRHS());
1310 type_size
= get_type_size(op
->getType(), ast_context
);
1311 expr
= pet_expr_new_unary(type_size
, pet_op_minus
, expr
);
1317 /* Check that the increment of the given for loop increments
1318 * (or decrements) the induction variable "iv" and return
1319 * the increment as a pet_expr if successful.
1321 __isl_give pet_expr
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1324 Stmt
*inc
= stmt
->getInc();
1327 report_missing_increment(stmt
);
1331 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1332 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1333 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1334 return extract_compound_increment(
1335 cast
<CompoundAssignOperator
>(inc
), iv
);
1336 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1337 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1343 /* Construct a pet_tree for a while loop.
1345 * If we were only able to extract part of the body, then simply
1348 __isl_give pet_tree
*PetScan::extract(WhileStmt
*stmt
)
1353 tree
= extract(stmt
->getBody());
1356 pe_cond
= extract_expr(stmt
->getCond());
1357 tree
= pet_tree_new_while(pe_cond
, tree
);
1362 /* Construct a pet_tree for a for statement.
1363 * The for loop is required to be of one of the following forms
1365 * for (i = init; condition; ++i)
1366 * for (i = init; condition; --i)
1367 * for (i = init; condition; i += constant)
1368 * for (i = init; condition; i -= constant)
1370 * We extract a pet_tree for the body and then include it in a pet_tree
1371 * of type pet_tree_for.
1373 * As a special case, we also allow a for loop of the form
1377 * in which case we return a pet_tree of type pet_tree_infinite_loop.
1379 * If we were only able to extract part of the body, then simply
1382 __isl_give pet_tree
*PetScan::extract_for(ForStmt
*stmt
)
1384 BinaryOperator
*ass
;
1390 struct pet_scop
*scop
;
1393 pet_expr
*pe_init
, *pe_inc
, *pe_iv
, *pe_cond
;
1395 independent
= is_current_stmt_marked_independent();
1397 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc()) {
1398 tree
= extract(stmt
->getBody());
1401 tree
= pet_tree_new_infinite_loop(tree
);
1405 init
= stmt
->getInit();
1410 if ((ass
= initialization_assignment(init
)) != NULL
) {
1411 iv
= extract_induction_variable(ass
);
1414 lhs
= ass
->getLHS();
1415 rhs
= ass
->getRHS();
1416 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
1417 VarDecl
*var
= extract_induction_variable(init
, decl
);
1421 rhs
= var
->getInit();
1422 lhs
= create_DeclRefExpr(var
);
1424 unsupported(stmt
->getInit());
1428 declared
= !initialization_assignment(stmt
->getInit());
1429 tree
= extract(stmt
->getBody());
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
));
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
,
1445 /* Try and construct a pet_tree corresponding to a compound statement.
1447 * "skip_declarations" is set if we should skip initial declarations
1448 * in the children of the compound statements.
1450 __isl_give pet_tree
*PetScan::extract(CompoundStmt
*stmt
,
1451 bool skip_declarations
)
1453 return extract(stmt
->children(), true, skip_declarations
);
1456 /* Return the file offset of the expansion location of "Loc".
1458 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
1460 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
1463 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
1465 /* Return a SourceLocation for the location after the first semicolon
1466 * after "loc". If Lexer::findLocationAfterToken is available, we simply
1467 * call it and also skip trailing spaces and newline.
1469 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
1470 const LangOptions
&LO
)
1472 return Lexer::findLocationAfterToken(loc
, tok::semi
, SM
, LO
, true);
1477 /* Return a SourceLocation for the location after the first semicolon
1478 * after "loc". If Lexer::findLocationAfterToken is not available,
1479 * we look in the underlying character data for the first semicolon.
1481 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
1482 const LangOptions
&LO
)
1485 const char *s
= SM
.getCharacterData(loc
);
1487 semi
= strchr(s
, ';');
1489 return SourceLocation();
1490 return loc
.getFileLocWithOffset(semi
+ 1 - s
);
1495 /* If the token at "loc" is the first token on the line, then return
1496 * a location referring to the start of the line and set *indent
1497 * to the indentation of "loc"
1498 * Otherwise, return "loc" and set *indent to "".
1500 * This function is used to extend a scop to the start of the line
1501 * if the first token of the scop is also the first token on the line.
1503 * We look for the first token on the line. If its location is equal to "loc",
1504 * then the latter is the location of the first token on the line.
1506 static SourceLocation
move_to_start_of_line_if_first_token(SourceLocation loc
,
1507 SourceManager
&SM
, const LangOptions
&LO
, char **indent
)
1509 std::pair
<FileID
, unsigned> file_offset_pair
;
1510 llvm::StringRef file
;
1513 SourceLocation token_loc
, line_loc
;
1517 loc
= SM
.getExpansionLoc(loc
);
1518 col
= SM
.getExpansionColumnNumber(loc
);
1519 line_loc
= loc
.getLocWithOffset(1 - col
);
1520 file_offset_pair
= SM
.getDecomposedLoc(line_loc
);
1521 file
= SM
.getBufferData(file_offset_pair
.first
, NULL
);
1522 pos
= file
.data() + file_offset_pair
.second
;
1524 Lexer
lexer(SM
.getLocForStartOfFile(file_offset_pair
.first
), LO
,
1525 file
.begin(), pos
, file
.end());
1526 lexer
.LexFromRawLexer(tok
);
1527 token_loc
= tok
.getLocation();
1529 s
= SM
.getCharacterData(line_loc
);
1530 *indent
= strndup(s
, token_loc
== loc
? col
- 1 : 0);
1532 if (token_loc
== loc
)
1538 /* Construct a pet_loc corresponding to the region covered by "range".
1539 * If "skip_semi" is set, then we assume "range" is followed by
1540 * a semicolon and also include this semicolon.
1542 __isl_give pet_loc
*PetScan::construct_pet_loc(SourceRange range
,
1545 SourceLocation loc
= range
.getBegin();
1546 SourceManager
&SM
= PP
.getSourceManager();
1547 const LangOptions
&LO
= PP
.getLangOpts();
1548 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
1549 unsigned start
, end
;
1552 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
, &indent
);
1553 start
= getExpansionOffset(SM
, loc
);
1554 loc
= range
.getEnd();
1556 loc
= location_after_semi(loc
, SM
, LO
);
1558 loc
= PP
.getLocForEndOfToken(loc
);
1559 end
= getExpansionOffset(SM
, loc
);
1561 return pet_loc_alloc(ctx
, start
, end
, line
, indent
);
1564 /* Convert a top-level pet_expr to an expression pet_tree.
1566 __isl_give pet_tree
*PetScan::extract(__isl_take pet_expr
*expr
,
1567 SourceRange range
, bool skip_semi
)
1572 tree
= pet_tree_new_expr(expr
);
1573 loc
= construct_pet_loc(range
, skip_semi
);
1574 tree
= pet_tree_set_loc(tree
, loc
);
1579 /* Construct a pet_tree for an if statement.
1581 __isl_give pet_tree
*PetScan::extract(IfStmt
*stmt
)
1584 pet_tree
*tree
, *tree_else
;
1585 struct pet_scop
*scop
;
1588 pe_cond
= extract_expr(stmt
->getCond());
1589 tree
= extract(stmt
->getThen());
1590 if (stmt
->getElse()) {
1591 tree_else
= extract(stmt
->getElse());
1592 if (options
->autodetect
) {
1593 if (tree
&& !tree_else
) {
1595 pet_expr_free(pe_cond
);
1598 if (!tree
&& tree_else
) {
1600 pet_expr_free(pe_cond
);
1604 tree
= pet_tree_new_if_else(pe_cond
, tree
, tree_else
);
1606 tree
= pet_tree_new_if(pe_cond
, tree
);
1610 /* Try and construct a pet_tree for a label statement.
1612 __isl_give pet_tree
*PetScan::extract(LabelStmt
*stmt
)
1617 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
1619 tree
= extract(stmt
->getSubStmt());
1620 tree
= pet_tree_set_label(tree
, label
);
1624 /* Update the location of "tree" to include the source range of "stmt".
1626 * Actually, we create a new location based on the source range of "stmt" and
1627 * then extend this new location to include the region of the original location.
1628 * This ensures that the line number of the final location refers to "stmt".
1630 __isl_give pet_tree
*PetScan::update_loc(__isl_take pet_tree
*tree
, Stmt
*stmt
)
1632 pet_loc
*loc
, *tree_loc
;
1634 tree_loc
= pet_tree_get_loc(tree
);
1635 loc
= construct_pet_loc(stmt
->getSourceRange(), false);
1636 loc
= pet_loc_update_start_end_from_loc(loc
, tree_loc
);
1637 pet_loc_free(tree_loc
);
1639 tree
= pet_tree_set_loc(tree
, loc
);
1643 /* Try and construct a pet_tree corresponding to "stmt".
1645 * If "stmt" is a compound statement, then "skip_declarations"
1646 * indicates whether we should skip initial declarations in the
1647 * compound statement.
1649 * If the constructed pet_tree is not a (possibly) partial representation
1650 * of "stmt", we update start and end of the pet_scop to those of "stmt".
1651 * In particular, if skip_declarations is set, then we may have skipped
1652 * declarations inside "stmt" and so the pet_scop may not represent
1653 * the entire "stmt".
1654 * Note that this function may be called with "stmt" referring to the entire
1655 * body of the function, including the outer braces. In such cases,
1656 * skip_declarations will be set and the braces will not be taken into
1657 * account in tree->loc.
1659 __isl_give pet_tree
*PetScan::extract(Stmt
*stmt
, bool skip_declarations
)
1663 set_current_stmt(stmt
);
1665 if (isa
<Expr
>(stmt
))
1666 return extract(extract_expr(cast
<Expr
>(stmt
)),
1667 stmt
->getSourceRange(), true);
1669 switch (stmt
->getStmtClass()) {
1670 case Stmt::WhileStmtClass
:
1671 tree
= extract(cast
<WhileStmt
>(stmt
));
1673 case Stmt::ForStmtClass
:
1674 tree
= extract_for(cast
<ForStmt
>(stmt
));
1676 case Stmt::IfStmtClass
:
1677 tree
= extract(cast
<IfStmt
>(stmt
));
1679 case Stmt::CompoundStmtClass
:
1680 tree
= extract(cast
<CompoundStmt
>(stmt
), skip_declarations
);
1682 case Stmt::LabelStmtClass
:
1683 tree
= extract(cast
<LabelStmt
>(stmt
));
1685 case Stmt::ContinueStmtClass
:
1686 tree
= pet_tree_new_continue(ctx
);
1688 case Stmt::BreakStmtClass
:
1689 tree
= pet_tree_new_break(ctx
);
1691 case Stmt::DeclStmtClass
:
1692 tree
= extract(cast
<DeclStmt
>(stmt
));
1695 report_unsupported_statement_type(stmt
);
1699 if (partial
|| skip_declarations
)
1702 return update_loc(tree
, stmt
);
1705 /* Given a sequence of statements "stmt_range" of which the first "n_decl"
1706 * are declarations and of which the remaining statements are represented
1707 * by "tree", try and extend "tree" to include the last sequence of
1708 * the initial declarations that can be completely extracted.
1710 * We start collecting the initial declarations and start over
1711 * whenever we come across a declaration that we cannot extract.
1712 * If we have been able to extract any declarations, then we
1713 * copy over the contents of "tree" at the end of the declarations.
1714 * Otherwise, we simply return the original "tree".
1716 __isl_give pet_tree
*PetScan::insert_initial_declarations(
1717 __isl_take pet_tree
*tree
, int n_decl
, StmtRange stmt_range
)
1725 n_stmt
= pet_tree_block_n_child(tree
);
1726 is_block
= pet_tree_block_get_block(tree
);
1727 res
= pet_tree_new_block(ctx
, is_block
, n_decl
+ n_stmt
);
1729 for (i
= stmt_range
.first
; n_decl
; ++i
, --n_decl
) {
1733 tree_i
= extract(child
);
1734 if (tree_i
&& !partial
) {
1735 res
= pet_tree_block_add_child(res
, tree_i
);
1738 pet_tree_free(tree_i
);
1740 if (pet_tree_block_n_child(res
) == 0)
1743 res
= pet_tree_new_block(ctx
, is_block
, n_decl
+ n_stmt
);
1746 if (pet_tree_block_n_child(res
) == 0) {
1751 for (j
= 0; j
< n_stmt
; ++j
) {
1754 tree_i
= pet_tree_block_get_child(tree
, j
);
1755 res
= pet_tree_block_add_child(res
, tree_i
);
1757 pet_tree_free(tree
);
1762 /* Try and construct a pet_tree corresponding to (part of)
1763 * a sequence of statements.
1765 * "block" is set if the sequence represents the children of
1766 * a compound statement.
1767 * "skip_declarations" is set if we should skip initial declarations
1768 * in the sequence of statements.
1770 * If autodetect is set, then we allow the extraction of only a subrange
1771 * of the sequence of statements. However, if there is at least one
1772 * kill and there is some subsequent statement for which we could not
1773 * construct a tree, then turn off the "block" property of the tree
1774 * such that no extra kill will be introduced at the end of the (partial)
1775 * block. If, on the other hand, the final range contains
1776 * no statements, then we discard the entire range.
1778 * If the entire range was extracted, apart from some initial declarations,
1779 * then we try and extend the range with the latest of those initial
1782 __isl_give pet_tree
*PetScan::extract(StmtRange stmt_range
, bool block
,
1783 bool skip_declarations
)
1787 bool has_kills
= false;
1788 bool partial_range
= false;
1791 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
)
1794 tree
= pet_tree_new_block(ctx
, block
, j
);
1797 i
= stmt_range
.first
;
1798 if (skip_declarations
)
1799 for (; i
!= stmt_range
.second
; ++i
) {
1800 if ((*i
)->getStmtClass() != Stmt::DeclStmtClass
)
1805 for (; i
!= stmt_range
.second
; ++i
) {
1809 tree_i
= extract(child
);
1810 if (pet_tree_block_n_child(tree
) != 0 && partial
) {
1811 pet_tree_free(tree_i
);
1814 if (tree_i
&& child
->getStmtClass() == Stmt::DeclStmtClass
&&
1817 if (options
->autodetect
) {
1819 tree
= pet_tree_block_add_child(tree
, tree_i
);
1821 partial_range
= true;
1822 if (pet_tree_block_n_child(tree
) != 0 && !tree_i
)
1825 tree
= pet_tree_block_add_child(tree
, tree_i
);
1828 if (partial
|| !tree
)
1837 tree
= pet_tree_block_set_block(tree
, 0);
1838 } else if (partial_range
) {
1839 if (pet_tree_block_n_child(tree
) == 0) {
1840 pet_tree_free(tree
);
1844 } else if (skip
> 0)
1845 tree
= insert_initial_declarations(tree
, skip
, stmt_range
);
1850 /* Is "T" the type of a variable length array with static size?
1852 static bool is_vla_with_static_size(QualType T
)
1854 const VariableArrayType
*vlatype
;
1856 if (!T
->isVariableArrayType())
1858 vlatype
= cast
<VariableArrayType
>(T
);
1859 return vlatype
->getSizeModifier() == VariableArrayType::Static
;
1862 /* Return the type of "decl" as an array.
1864 * In particular, if "decl" is a parameter declaration that
1865 * is a variable length array with a static size, then
1866 * return the original type (i.e., the variable length array).
1867 * Otherwise, return the type of decl.
1869 static QualType
get_array_type(ValueDecl
*decl
)
1874 parm
= dyn_cast
<ParmVarDecl
>(decl
);
1876 return decl
->getType();
1878 T
= parm
->getOriginalType();
1879 if (!is_vla_with_static_size(T
))
1880 return decl
->getType();
1885 static __isl_give pet_expr
*get_array_size(__isl_keep pet_expr
*access
,
1887 static struct pet_array
*extract_array(__isl_keep pet_expr
*access
,
1888 __isl_keep pet_context
*pc
, void *user
);
1891 /* Construct a pet_expr that holds the sizes of the array accessed
1893 * This function is used as a callback to pet_context_add_parameters,
1894 * which is also passed a pointer to the PetScan object.
1896 static __isl_give pet_expr
*get_array_size(__isl_keep pet_expr
*access
,
1899 PetScan
*ps
= (PetScan
*) user
;
1904 id
= pet_expr_access_get_id(access
);
1905 decl
= (ValueDecl
*) isl_id_get_user(id
);
1907 type
= get_array_type(decl
).getTypePtr();
1908 return ps
->get_array_size(type
);
1911 /* Construct and return a pet_array corresponding to the variable
1912 * accessed by "access".
1913 * This function is used as a callback to pet_scop_from_pet_tree,
1914 * which is also passed a pointer to the PetScan object.
1916 static struct pet_array
*extract_array(__isl_keep pet_expr
*access
,
1917 __isl_keep pet_context
*pc
, void *user
)
1919 PetScan
*ps
= (PetScan
*) user
;
1924 ctx
= pet_expr_get_ctx(access
);
1925 id
= pet_expr_access_get_id(access
);
1926 iv
= (ValueDecl
*) isl_id_get_user(id
);
1928 return ps
->extract_array(ctx
, iv
, NULL
, pc
);
1931 /* Extract a function summary from the body of "fd".
1933 * We extract a scop from the function body in a context with as
1934 * parameters the integer arguments of the function.
1935 * We turn off autodetection (in case it was set) to ensure that
1936 * the entire function body is considered.
1937 * We then collect the accessed array elements and attach them
1938 * to the corresponding array arguments, taking into account
1939 * that the function body may access members of array elements.
1941 * The reason for representing the integer arguments as parameters in
1942 * the context is that if we were to instead start with a context
1943 * with the function arguments as initial dimensions, then we would not
1944 * be able to refer to them from the array extents, without turning
1945 * array extents into maps.
1947 * The result is stored in the summary_cache cache so that we can reuse
1948 * it if this method gets called on the same function again later on.
1950 __isl_give pet_function_summary
*PetScan::get_summary(FunctionDecl
*fd
)
1956 pet_function_summary
*summary
;
1959 int save_autodetect
;
1960 struct pet_scop
*scop
;
1962 isl_union_set
*may_read
, *may_write
, *must_write
;
1963 isl_union_map
*to_inner
;
1965 if (summary_cache
.find(fd
) != summary_cache
.end())
1966 return pet_function_summary_copy(summary_cache
[fd
]);
1968 space
= isl_space_set_alloc(ctx
, 0, 0);
1970 n
= fd
->getNumParams();
1971 summary
= pet_function_summary_alloc(ctx
, n
);
1972 for (int i
= 0; i
< n
; ++i
) {
1973 ParmVarDecl
*parm
= fd
->getParamDecl(i
);
1974 QualType type
= parm
->getType();
1977 if (!type
->isIntegerType())
1979 id
= create_decl_id(ctx
, parm
);
1980 space
= isl_space_insert_dims(space
, isl_dim_param
, 0, 1);
1981 space
= isl_space_set_dim_id(space
, isl_dim_param
, 0,
1983 summary
= pet_function_summary_set_int(summary
, i
, id
);
1986 save_autodetect
= options
->autodetect
;
1987 options
->autodetect
= 0;
1988 PetScan
body_scan(PP
, ast_context
, loc
, options
,
1989 isl_union_map_copy(value_bounds
), independent
);
1991 tree
= body_scan
.extract(fd
->getBody(), false);
1993 domain
= isl_set_universe(space
);
1994 pc
= pet_context_alloc(domain
);
1995 pc
= pet_context_add_parameters(pc
, tree
,
1996 &::get_array_size
, &body_scan
);
1997 int_size
= size_in_bytes(ast_context
, ast_context
.IntTy
);
1998 scop
= pet_scop_from_pet_tree(tree
, int_size
,
1999 &::extract_array
, &body_scan
, pc
);
2000 scop
= scan_arrays(scop
, pc
);
2001 may_read
= isl_union_map_range(pet_scop_collect_may_reads(scop
));
2002 may_write
= isl_union_map_range(pet_scop_collect_may_writes(scop
));
2003 must_write
= isl_union_map_range(pet_scop_collect_must_writes(scop
));
2004 to_inner
= pet_scop_compute_outer_to_inner(scop
);
2005 pet_scop_free(scop
);
2007 for (int i
= 0; i
< n
; ++i
) {
2008 ParmVarDecl
*parm
= fd
->getParamDecl(i
);
2009 QualType type
= parm
->getType();
2010 struct pet_array
*array
;
2012 isl_union_set
*data_set
;
2013 isl_union_set
*may_read_i
, *may_write_i
, *must_write_i
;
2015 if (array_depth(type
.getTypePtr()) == 0)
2018 array
= body_scan
.extract_array(ctx
, parm
, NULL
, pc
);
2019 space
= array
? isl_set_get_space(array
->extent
) : NULL
;
2020 pet_array_free(array
);
2021 data_set
= isl_union_set_from_set(isl_set_universe(space
));
2022 data_set
= isl_union_set_apply(data_set
,
2023 isl_union_map_copy(to_inner
));
2024 may_read_i
= isl_union_set_intersect(
2025 isl_union_set_copy(may_read
),
2026 isl_union_set_copy(data_set
));
2027 may_write_i
= isl_union_set_intersect(
2028 isl_union_set_copy(may_write
),
2029 isl_union_set_copy(data_set
));
2030 must_write_i
= isl_union_set_intersect(
2031 isl_union_set_copy(must_write
), data_set
);
2032 summary
= pet_function_summary_set_array(summary
, i
,
2033 may_read_i
, may_write_i
, must_write_i
);
2036 isl_union_set_free(may_read
);
2037 isl_union_set_free(may_write
);
2038 isl_union_set_free(must_write
);
2039 isl_union_map_free(to_inner
);
2041 options
->autodetect
= save_autodetect
;
2042 pet_context_free(pc
);
2044 summary_cache
[fd
] = pet_function_summary_copy(summary
);
2049 /* If "fd" has a function body, then extract a function summary from
2050 * this body and attach it to the call expression "expr".
2052 * Even if a function body is available, "fd" itself may point
2053 * to a declaration without function body. We therefore first
2054 * replace it by the declaration that comes with a body (if any).
2056 * It is not clear why hasBody takes a reference to a const FunctionDecl *.
2057 * It seems that it is possible to directly use the iterators to obtain
2058 * a non-const pointer.
2059 * Since we are not going to use the pointer to modify anything anyway,
2060 * it seems safe to drop the constness. The alternative would be to
2061 * modify a lot of other functions to include const qualifiers.
2063 __isl_give pet_expr
*PetScan::set_summary(__isl_take pet_expr
*expr
,
2066 pet_function_summary
*summary
;
2067 const FunctionDecl
*def
;
2071 if (!fd
->hasBody(def
))
2074 fd
= const_cast<FunctionDecl
*>(def
);
2076 summary
= get_summary(fd
);
2078 expr
= pet_expr_call_set_summary(expr
, summary
);
2083 /* Extract a pet_scop from "tree".
2085 * We simply call pet_scop_from_pet_tree with the appropriate arguments and
2086 * then add pet_arrays for all accessed arrays.
2087 * We populate the pet_context with assignments for all parameters used
2088 * inside "tree" or any of the size expressions for the arrays accessed
2089 * by "tree" so that they can be used in affine expressions.
2091 struct pet_scop
*PetScan::extract_scop(__isl_take pet_tree
*tree
)
2098 int_size
= size_in_bytes(ast_context
, ast_context
.IntTy
);
2100 domain
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2101 pc
= pet_context_alloc(domain
);
2102 pc
= pet_context_add_parameters(pc
, tree
, &::get_array_size
, this);
2103 scop
= pet_scop_from_pet_tree(tree
, int_size
,
2104 &::extract_array
, this, pc
);
2105 scop
= scan_arrays(scop
, pc
);
2106 pet_context_free(pc
);
2111 /* Check if the scop marked by the user is exactly this Stmt
2112 * or part of this Stmt.
2113 * If so, return a pet_scop corresponding to the marked region.
2114 * Otherwise, return NULL.
2116 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
2118 SourceManager
&SM
= PP
.getSourceManager();
2119 unsigned start_off
, end_off
;
2121 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
2122 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
2124 if (start_off
> loc
.end
)
2126 if (end_off
< loc
.start
)
2129 if (start_off
>= loc
.start
&& end_off
<= loc
.end
)
2130 return extract_scop(extract(stmt
));
2133 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
2134 Stmt
*child
= *start
;
2137 start_off
= getExpansionOffset(SM
, child
->getLocStart());
2138 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
2139 if (start_off
< loc
.start
&& end_off
>= loc
.end
)
2141 if (start_off
>= loc
.start
)
2146 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
2148 start_off
= SM
.getFileOffset(child
->getLocStart());
2149 if (start_off
>= loc
.end
)
2153 return extract_scop(extract(StmtRange(start
, end
), false, false));
2156 /* Set the size of index "pos" of "array" to "size".
2157 * In particular, add a constraint of the form
2161 * to array->extent and a constraint of the form
2165 * to array->context.
2167 * The domain of "size" is assumed to be zero-dimensional.
2169 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
2170 __isl_take isl_pw_aff
*size
)
2183 valid
= isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
)));
2184 array
->context
= isl_set_intersect(array
->context
, valid
);
2186 dim
= isl_set_get_space(array
->extent
);
2187 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2188 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
2189 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
2190 index
= isl_pw_aff_alloc(univ
, aff
);
2192 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
2193 isl_set_dim(array
->extent
, isl_dim_set
));
2194 id
= isl_set_get_tuple_id(array
->extent
);
2195 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
2196 bound
= isl_pw_aff_lt_set(index
, size
);
2198 array
->extent
= isl_set_intersect(array
->extent
, bound
);
2200 if (!array
->context
|| !array
->extent
)
2201 return pet_array_free(array
);
2205 isl_pw_aff_free(size
);
2209 #ifdef HAVE_DECAYEDTYPE
2211 /* If "type" is a decayed type, then set *decayed to true and
2212 * return the original type.
2214 static const Type
*undecay(const Type
*type
, bool *decayed
)
2216 *decayed
= isa
<DecayedType
>(type
);
2218 type
= cast
<DecayedType
>(type
)->getOriginalType().getTypePtr();
2224 /* If "type" is a decayed type, then set *decayed to true and
2225 * return the original type.
2226 * Since this version of clang does not define a DecayedType,
2227 * we cannot obtain the original type even if it had been decayed and
2228 * we set *decayed to false.
2230 static const Type
*undecay(const Type
*type
, bool *decayed
)
2238 /* Figure out the size of the array at position "pos" and all
2239 * subsequent positions from "type" and update the corresponding
2240 * argument of "expr" accordingly.
2242 * The initial type (when pos is zero) may be a pointer type decayed
2243 * from an array type, if this initial type is the type of a function
2244 * argument. This only happens if the original array type has
2245 * a constant size in the outer dimension as otherwise we get
2246 * a VariableArrayType. Try and obtain this original type (if available) and
2247 * take the outer array size into account if it was marked static.
2249 __isl_give pet_expr
*PetScan::set_upper_bounds(__isl_take pet_expr
*expr
,
2250 const Type
*type
, int pos
)
2252 const ArrayType
*atype
;
2254 bool decayed
= false;
2260 type
= undecay(type
, &decayed
);
2262 if (type
->isPointerType()) {
2263 type
= type
->getPointeeType().getTypePtr();
2264 return set_upper_bounds(expr
, type
, pos
+ 1);
2266 if (!type
->isArrayType())
2269 type
= type
->getCanonicalTypeInternal().getTypePtr();
2270 atype
= cast
<ArrayType
>(type
);
2272 if (decayed
&& atype
->getSizeModifier() != ArrayType::Static
) {
2273 type
= atype
->getElementType().getTypePtr();
2274 return set_upper_bounds(expr
, type
, pos
+ 1);
2277 if (type
->isConstantArrayType()) {
2278 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
2279 size
= extract_expr(ca
->getSize());
2280 expr
= pet_expr_set_arg(expr
, pos
, size
);
2281 } else if (type
->isVariableArrayType()) {
2282 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
2283 size
= extract_expr(vla
->getSizeExpr());
2284 expr
= pet_expr_set_arg(expr
, pos
, size
);
2287 type
= atype
->getElementType().getTypePtr();
2289 return set_upper_bounds(expr
, type
, pos
+ 1);
2292 /* Construct a pet_expr that holds the sizes of an array of the given type.
2293 * The returned expression is a call expression with as arguments
2294 * the sizes in each dimension. If we are unable to derive the size
2295 * in a given dimension, then the corresponding argument is set to infinity.
2296 * In fact, we initialize all arguments to infinity and then update
2297 * them if we are able to figure out the size.
2299 * The result is stored in the type_size cache so that we can reuse
2300 * it if this method gets called on the same type again later on.
2302 __isl_give pet_expr
*PetScan::get_array_size(const Type
*type
)
2305 pet_expr
*expr
, *inf
;
2307 if (type_size
.find(type
) != type_size
.end())
2308 return pet_expr_copy(type_size
[type
]);
2310 depth
= array_depth(type
);
2311 inf
= pet_expr_new_int(isl_val_infty(ctx
));
2312 expr
= pet_expr_new_call(ctx
, "bounds", depth
);
2313 for (int i
= 0; i
< depth
; ++i
)
2314 expr
= pet_expr_set_arg(expr
, i
, pet_expr_copy(inf
));
2317 expr
= set_upper_bounds(expr
, type
, 0);
2318 type_size
[type
] = pet_expr_copy(expr
);
2323 /* Does "expr" represent the "integer" infinity?
2325 static int is_infty(__isl_keep pet_expr
*expr
)
2330 if (pet_expr_get_type(expr
) != pet_expr_int
)
2332 v
= pet_expr_int_get_val(expr
);
2333 res
= isl_val_is_infty(v
);
2339 /* Figure out the dimensions of an array "array" based on its type
2340 * "type" and update "array" accordingly.
2342 * We first construct a pet_expr that holds the sizes of the array
2343 * in each dimension. The resulting expression may containing
2344 * infinity values for dimension where we are unable to derive
2345 * a size expression.
2347 * The arguments of the size expression that have a value different from
2348 * infinity are then converted to an affine expression
2349 * within the context "pc" and incorporated into the size of "array".
2350 * If we are unable to convert a size expression to an affine expression or
2351 * if the size is not a (symbolic) constant,
2352 * then we leave the corresponding size of "array" untouched.
2354 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
2355 const Type
*type
, __isl_keep pet_context
*pc
)
2363 expr
= get_array_size(type
);
2365 n
= pet_expr_get_n_arg(expr
);
2366 for (int i
= 0; i
< n
; ++i
) {
2370 arg
= pet_expr_get_arg(expr
, i
);
2371 if (!is_infty(arg
)) {
2374 size
= pet_expr_extract_affine(arg
, pc
);
2375 dim
= isl_pw_aff_dim(size
, isl_dim_in
);
2377 array
= pet_array_free(array
);
2378 else if (isl_pw_aff_involves_nan(size
) ||
2379 isl_pw_aff_involves_dims(size
, isl_dim_in
, 0, dim
))
2380 isl_pw_aff_free(size
);
2382 size
= isl_pw_aff_drop_dims(size
,
2383 isl_dim_in
, 0, dim
);
2384 array
= update_size(array
, i
, size
);
2389 pet_expr_free(expr
);
2394 /* Does "decl" have a definition that we can keep track of in a pet_type?
2396 static bool has_printable_definition(RecordDecl
*decl
)
2398 if (!decl
->getDeclName())
2400 return decl
->getLexicalDeclContext() == decl
->getDeclContext();
2403 /* Construct and return a pet_array corresponding to the variable "decl".
2404 * In particular, initialize array->extent to
2406 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2408 * and then call set_upper_bounds to set the upper bounds on the indices
2409 * based on the type of the variable. The upper bounds are converted
2410 * to affine expressions within the context "pc".
2412 * If the base type is that of a record with a top-level definition or
2413 * of a typedef and if "types" is not null, then the RecordDecl or
2414 * TypedefType corresponding to the type
2415 * is added to "types".
2417 * If the base type is that of a record with no top-level definition,
2418 * then we replace it by "<subfield>".
2420 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
,
2421 PetTypes
*types
, __isl_keep pet_context
*pc
)
2423 struct pet_array
*array
;
2424 QualType qt
= get_array_type(decl
);
2425 const Type
*type
= qt
.getTypePtr();
2426 int depth
= array_depth(type
);
2427 QualType base
= pet_clang_base_type(qt
);
2432 array
= isl_calloc_type(ctx
, struct pet_array
);
2436 id
= create_decl_id(ctx
, decl
);
2437 dim
= isl_space_set_alloc(ctx
, 0, depth
);
2438 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
2440 array
->extent
= isl_set_nat_universe(dim
);
2442 dim
= isl_space_params_alloc(ctx
, 0);
2443 array
->context
= isl_set_universe(dim
);
2445 array
= set_upper_bounds(array
, type
, pc
);
2449 name
= base
.getAsString();
2452 if (isa
<TypedefType
>(base
)) {
2453 types
->insert(cast
<TypedefType
>(base
)->getDecl());
2454 } else if (base
->isRecordType()) {
2455 RecordDecl
*decl
= pet_clang_record_decl(base
);
2456 TypedefNameDecl
*typedecl
;
2457 typedecl
= decl
->getTypedefNameForAnonDecl();
2459 types
->insert(typedecl
);
2460 else if (has_printable_definition(decl
))
2461 types
->insert(decl
);
2463 name
= "<subfield>";
2467 array
->element_type
= strdup(name
.c_str());
2468 array
->element_is_record
= base
->isRecordType();
2469 array
->element_size
= size_in_bytes(decl
->getASTContext(), base
);
2474 /* Construct and return a pet_array corresponding to the sequence
2475 * of declarations "decls".
2476 * The upper bounds of the array are converted to affine expressions
2477 * within the context "pc".
2478 * If the sequence contains a single declaration, then it corresponds
2479 * to a simple array access. Otherwise, it corresponds to a member access,
2480 * with the declaration for the substructure following that of the containing
2481 * structure in the sequence of declarations.
2482 * We start with the outermost substructure and then combine it with
2483 * information from the inner structures.
2485 * Additionally, keep track of all required types in "types".
2487 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
,
2488 vector
<ValueDecl
*> decls
, PetTypes
*types
, __isl_keep pet_context
*pc
)
2490 struct pet_array
*array
;
2491 vector
<ValueDecl
*>::iterator it
;
2495 array
= extract_array(ctx
, *it
, types
, pc
);
2497 for (++it
; it
!= decls
.end(); ++it
) {
2498 struct pet_array
*parent
;
2499 const char *base_name
, *field_name
;
2503 array
= extract_array(ctx
, *it
, types
, pc
);
2505 return pet_array_free(parent
);
2507 base_name
= isl_set_get_tuple_name(parent
->extent
);
2508 field_name
= isl_set_get_tuple_name(array
->extent
);
2509 product_name
= pet_array_member_access_name(ctx
,
2510 base_name
, field_name
);
2512 array
->extent
= isl_set_product(isl_set_copy(parent
->extent
),
2515 array
->extent
= isl_set_set_tuple_name(array
->extent
,
2517 array
->context
= isl_set_intersect(array
->context
,
2518 isl_set_copy(parent
->context
));
2520 pet_array_free(parent
);
2523 if (!array
->extent
|| !array
->context
|| !product_name
)
2524 return pet_array_free(array
);
2530 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
2531 RecordDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2532 std::set
<TypeDecl
*> &types_done
);
2533 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
2534 TypedefNameDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2535 std::set
<TypeDecl
*> &types_done
);
2537 /* For each of the fields of "decl" that is itself a record type
2538 * or a typedef, add a corresponding pet_type to "scop".
2540 static struct pet_scop
*add_field_types(isl_ctx
*ctx
, struct pet_scop
*scop
,
2541 RecordDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2542 std::set
<TypeDecl
*> &types_done
)
2544 RecordDecl::field_iterator it
;
2546 for (it
= decl
->field_begin(); it
!= decl
->field_end(); ++it
) {
2547 QualType type
= it
->getType();
2549 if (isa
<TypedefType
>(type
)) {
2550 TypedefNameDecl
*typedefdecl
;
2552 typedefdecl
= cast
<TypedefType
>(type
)->getDecl();
2553 scop
= add_type(ctx
, scop
, typedefdecl
,
2554 PP
, types
, types_done
);
2555 } else if (type
->isRecordType()) {
2558 record
= pet_clang_record_decl(type
);
2559 scop
= add_type(ctx
, scop
, record
,
2560 PP
, types
, types_done
);
2567 /* Add a pet_type corresponding to "decl" to "scop", provided
2568 * it is a member of types.records and it has not been added before
2569 * (i.e., it is not a member of "types_done").
2571 * Since we want the user to be able to print the types
2572 * in the order in which they appear in the scop, we need to
2573 * make sure that types of fields in a structure appear before
2574 * that structure. We therefore call ourselves recursively
2575 * through add_field_types on the types of all record subfields.
2577 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
2578 RecordDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2579 std::set
<TypeDecl
*> &types_done
)
2582 llvm::raw_string_ostream
S(s
);
2584 if (types
.records
.find(decl
) == types
.records
.end())
2586 if (types_done
.find(decl
) != types_done
.end())
2589 add_field_types(ctx
, scop
, decl
, PP
, types
, types_done
);
2591 if (strlen(decl
->getName().str().c_str()) == 0)
2594 decl
->print(S
, PrintingPolicy(PP
.getLangOpts()));
2597 scop
->types
[scop
->n_type
] = pet_type_alloc(ctx
,
2598 decl
->getName().str().c_str(), s
.c_str());
2599 if (!scop
->types
[scop
->n_type
])
2600 return pet_scop_free(scop
);
2602 types_done
.insert(decl
);
2609 /* Add a pet_type corresponding to "decl" to "scop", provided
2610 * it is a member of types.typedefs and it has not been added before
2611 * (i.e., it is not a member of "types_done").
2613 * If the underlying type is a structure, then we print the typedef
2614 * ourselves since clang does not print the definition of the structure
2615 * in the typedef. We also make sure in this case that the types of
2616 * the fields in the structure are added first.
2618 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
2619 TypedefNameDecl
*decl
, Preprocessor
&PP
, PetTypes
&types
,
2620 std::set
<TypeDecl
*> &types_done
)
2623 llvm::raw_string_ostream
S(s
);
2624 QualType qt
= decl
->getUnderlyingType();
2626 if (types
.typedefs
.find(decl
) == types
.typedefs
.end())
2628 if (types_done
.find(decl
) != types_done
.end())
2631 if (qt
->isRecordType()) {
2632 RecordDecl
*rec
= pet_clang_record_decl(qt
);
2634 add_field_types(ctx
, scop
, rec
, PP
, types
, types_done
);
2636 rec
->print(S
, PrintingPolicy(PP
.getLangOpts()));
2638 S
<< decl
->getName();
2640 decl
->print(S
, PrintingPolicy(PP
.getLangOpts()));
2644 scop
->types
[scop
->n_type
] = pet_type_alloc(ctx
,
2645 decl
->getName().str().c_str(), s
.c_str());
2646 if (!scop
->types
[scop
->n_type
])
2647 return pet_scop_free(scop
);
2649 types_done
.insert(decl
);
2656 /* Construct a list of pet_arrays, one for each array (or scalar)
2657 * accessed inside "scop", add this list to "scop" and return the result.
2658 * The upper bounds of the arrays are converted to affine expressions
2659 * within the context "pc".
2661 * The context of "scop" is updated with the intersection of
2662 * the contexts of all arrays, i.e., constraints on the parameters
2663 * that ensure that the arrays have a valid (non-negative) size.
2665 * If any of the extracted arrays refers to a member access or
2666 * has a typedef'd type as base type,
2667 * then also add the required types to "scop".
2669 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
,
2670 __isl_keep pet_context
*pc
)
2673 array_desc_set arrays
;
2674 array_desc_set::iterator it
;
2676 std::set
<TypeDecl
*> types_done
;
2677 std::set
<clang::RecordDecl
*, less_name
>::iterator records_it
;
2678 std::set
<clang::TypedefNameDecl
*, less_name
>::iterator typedefs_it
;
2680 struct pet_array
**scop_arrays
;
2685 pet_scop_collect_arrays(scop
, arrays
);
2686 if (arrays
.size() == 0)
2689 n_array
= scop
->n_array
;
2691 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
2692 n_array
+ arrays
.size());
2695 scop
->arrays
= scop_arrays
;
2697 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
2698 struct pet_array
*array
;
2699 array
= extract_array(ctx
, *it
, &types
, pc
);
2700 scop
->arrays
[n_array
+ i
] = array
;
2701 if (!scop
->arrays
[n_array
+ i
])
2704 scop
->context
= isl_set_intersect(scop
->context
,
2705 isl_set_copy(array
->context
));
2710 n
= types
.records
.size() + types
.typedefs
.size();
2714 scop
->types
= isl_alloc_array(ctx
, struct pet_type
*, n
);
2718 for (records_it
= types
.records
.begin();
2719 records_it
!= types
.records
.end(); ++records_it
)
2720 scop
= add_type(ctx
, scop
, *records_it
, PP
, types
, types_done
);
2722 for (typedefs_it
= types
.typedefs
.begin();
2723 typedefs_it
!= types
.typedefs
.end(); ++typedefs_it
)
2724 scop
= add_type(ctx
, scop
, *typedefs_it
, PP
, types
, types_done
);
2728 pet_scop_free(scop
);
2732 /* Bound all parameters in scop->context to the possible values
2733 * of the corresponding C variable.
2735 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
2742 n
= isl_set_dim(scop
->context
, isl_dim_param
);
2743 for (int i
= 0; i
< n
; ++i
) {
2747 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
2748 if (pet_nested_in_id(id
)) {
2750 isl_die(isl_set_get_ctx(scop
->context
),
2752 "unresolved nested parameter", goto error
);
2754 decl
= (ValueDecl
*) isl_id_get_user(id
);
2757 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
2765 pet_scop_free(scop
);
2769 /* Construct a pet_scop from the given function.
2771 * If the scop was delimited by scop and endscop pragmas, then we override
2772 * the file offsets by those derived from the pragmas.
2774 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
2779 stmt
= fd
->getBody();
2781 if (options
->autodetect
) {
2782 set_current_stmt(stmt
);
2783 scop
= extract_scop(extract(stmt
, true));
2785 current_line
= loc
.start_line
;
2787 scop
= pet_scop_update_start_end(scop
, loc
.start
, loc
.end
);
2789 scop
= add_parameter_bounds(scop
);
2790 scop
= pet_scop_gist(scop
, value_bounds
);
2795 /* Update this->last_line and this->current_line based on the fact
2796 * that we are about to consider "stmt".
2798 void PetScan::set_current_stmt(Stmt
*stmt
)
2800 SourceLocation loc
= stmt
->getLocStart();
2801 SourceManager
&SM
= PP
.getSourceManager();
2803 last_line
= current_line
;
2804 current_line
= SM
.getExpansionLineNumber(loc
);
2807 /* Is the current statement marked by an independent pragma?
2808 * That is, is there an independent pragma on a line between
2809 * the line of the current statement and the line of the previous statement.
2810 * The search is not implemented very efficiently. We currently
2811 * assume that there are only a few independent pragmas, if any.
2813 bool PetScan::is_current_stmt_marked_independent()
2815 for (int i
= 0; i
< independent
.size(); ++i
) {
2816 unsigned line
= independent
[i
].line
;
2818 if (last_line
< line
&& line
< current_line
)