2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2014 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
39 #include <llvm/Support/raw_ostream.h>
40 #include <clang/AST/ASTContext.h>
41 #include <clang/AST/ASTDiagnostic.h>
42 #include <clang/AST/Expr.h>
43 #include <clang/AST/RecursiveASTVisitor.h>
46 #include <isl/space.h>
60 #include "scop_plus.h"
66 using namespace clang
;
68 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
78 return pet_op_post_inc
;
80 return pet_op_post_dec
;
82 return pet_op_pre_inc
;
84 return pet_op_pre_dec
;
90 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
94 return pet_op_add_assign
;
96 return pet_op_sub_assign
;
98 return pet_op_mul_assign
;
100 return pet_op_div_assign
;
102 return pet_op_assign
;
144 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
145 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
147 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
148 SourceLocation(), var
, false, var
->getInnerLocStart(),
149 var
->getType(), VK_LValue
);
151 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
152 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
154 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
155 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
159 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
161 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
162 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
166 /* Check if the element type corresponding to the given array type
167 * has a const qualifier.
169 static bool const_base(QualType qt
)
171 const Type
*type
= qt
.getTypePtr();
173 if (type
->isPointerType())
174 return const_base(type
->getPointeeType());
175 if (type
->isArrayType()) {
176 const ArrayType
*atype
;
177 type
= type
->getCanonicalTypeInternal().getTypePtr();
178 atype
= cast
<ArrayType
>(type
);
179 return const_base(atype
->getElementType());
182 return qt
.isConstQualified();
185 /* Create an isl_id that refers to the named declarator "decl".
187 static __isl_give isl_id
*create_decl_id(isl_ctx
*ctx
, NamedDecl
*decl
)
189 return isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
192 /* Mark "decl" as having an unknown value in "assigned_value".
194 * If no (known or unknown) value was assigned to "decl" before,
195 * then it may have been treated as a parameter before and may
196 * therefore appear in a value assigned to another variable.
197 * If so, this assignment needs to be turned into an unknown value too.
199 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
202 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
204 it
= assigned_value
.find(decl
);
206 assigned_value
[decl
] = NULL
;
208 if (it
!= assigned_value
.end())
211 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
212 isl_pw_aff
*pa
= it
->second
;
213 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
215 for (int i
= 0; i
< nparam
; ++i
) {
218 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
220 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
221 if (isl_id_get_user(id
) == decl
)
228 /* Look for any assignments to scalar variables in part of the parse
229 * tree and set assigned_value to NULL for each of them.
230 * Also reset assigned_value if the address of a scalar variable
231 * is being taken. As an exception, if the address is passed to a function
232 * that is declared to receive a const pointer, then assigned_value is
235 * This ensures that we won't use any previously stored value
236 * in the current subtree and its parents.
238 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
239 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
240 set
<UnaryOperator
*> skip
;
242 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
243 assigned_value(assigned_value
) {}
245 /* Check for "address of" operators whose value is passed
246 * to a const pointer argument and add them to "skip", so that
247 * we can skip them in VisitUnaryOperator.
249 bool VisitCallExpr(CallExpr
*expr
) {
251 fd
= expr
->getDirectCallee();
254 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
255 Expr
*arg
= expr
->getArg(i
);
257 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
258 ImplicitCastExpr
*ice
;
259 ice
= cast
<ImplicitCastExpr
>(arg
);
260 arg
= ice
->getSubExpr();
262 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
264 op
= cast
<UnaryOperator
>(arg
);
265 if (op
->getOpcode() != UO_AddrOf
)
267 if (const_base(fd
->getParamDecl(i
)->getType()))
273 bool VisitUnaryOperator(UnaryOperator
*expr
) {
278 switch (expr
->getOpcode()) {
288 if (skip
.find(expr
) != skip
.end())
291 arg
= expr
->getSubExpr();
292 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
294 ref
= cast
<DeclRefExpr
>(arg
);
295 decl
= ref
->getDecl();
296 clear_assignment(assigned_value
, decl
);
300 bool VisitBinaryOperator(BinaryOperator
*expr
) {
305 if (!expr
->isAssignmentOp())
307 lhs
= expr
->getLHS();
308 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
310 ref
= cast
<DeclRefExpr
>(lhs
);
311 decl
= ref
->getDecl();
312 clear_assignment(assigned_value
, decl
);
317 /* Keep a copy of the currently assigned values.
319 * Any variable that is assigned a value inside the current scope
320 * is removed again when we leave the scope (either because it wasn't
321 * stored in the cache or because it has a different value in the cache).
323 struct assigned_value_cache
{
324 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
325 map
<ValueDecl
*, isl_pw_aff
*> cache
;
327 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
328 assigned_value(assigned_value
), cache(assigned_value
) {}
329 ~assigned_value_cache() {
330 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
331 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
334 (cache
.find(it
->first
) != cache
.end() &&
335 cache
[it
->first
] != it
->second
))
336 cache
[it
->first
] = NULL
;
338 assigned_value
= cache
;
342 /* Convert the mapping from identifiers to values in "assigned_value"
343 * to a pet_context to be used by pet_expr_extract_*.
344 * In particular, the clang identifiers are wrapped in an isl_id and
345 * a NULL value (representing an unknown value) is replaced by a NaN.
347 static __isl_give pet_context
*convert_assignments(isl_ctx
*ctx
,
348 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
)
351 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
353 pc
= pet_context_alloc(isl_space_set_alloc(ctx
, 0, 0));
355 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
356 ValueDecl
*decl
= it
->first
;
357 isl_pw_aff
*pa
= it
->second
;
360 id
= create_decl_id(ctx
, decl
);
362 pc
= pet_context_set_value(pc
, id
, isl_pw_aff_copy(pa
));
364 pc
= pet_context_mark_unknown(pc
, id
);
370 /* Insert an expression into the collection of expressions,
371 * provided it is not already in there.
372 * The isl_pw_affs are freed in the destructor.
374 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
376 std::set
<isl_pw_aff
*>::iterator it
;
378 if (expressions
.find(expr
) == expressions
.end())
379 expressions
.insert(expr
);
381 isl_pw_aff_free(expr
);
386 std::set
<isl_pw_aff
*>::iterator it
;
388 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
389 isl_pw_aff_free(*it
);
391 isl_union_map_free(value_bounds
);
394 /* Report a diagnostic, unless autodetect is set.
396 void PetScan::report(Stmt
*stmt
, unsigned id
)
398 if (options
->autodetect
)
401 SourceLocation loc
= stmt
->getLocStart();
402 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
403 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
406 /* Called if we found something we (currently) cannot handle.
407 * We'll provide more informative warnings later.
409 * We only actually complain if autodetect is false.
411 void PetScan::unsupported(Stmt
*stmt
)
413 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
414 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
419 /* Report a missing prototype, unless autodetect is set.
421 void PetScan::report_prototype_required(Stmt
*stmt
)
423 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
424 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
425 "prototype required");
429 /* Report a missing increment, unless autodetect is set.
431 void PetScan::report_missing_increment(Stmt
*stmt
)
433 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
434 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
435 "missing increment");
439 /* Extract an integer from "expr".
441 __isl_give isl_val
*PetScan::extract_int(isl_ctx
*ctx
, IntegerLiteral
*expr
)
443 const Type
*type
= expr
->getType().getTypePtr();
444 int is_signed
= type
->hasSignedIntegerRepresentation();
445 llvm::APInt val
= expr
->getValue();
446 int is_negative
= is_signed
&& val
.isNegative();
452 v
= extract_unsigned(ctx
, val
);
459 /* Extract an integer from "val", which is assumed to be non-negative.
461 __isl_give isl_val
*PetScan::extract_unsigned(isl_ctx
*ctx
,
462 const llvm::APInt
&val
)
465 const uint64_t *data
;
467 data
= val
.getRawData();
468 n
= val
.getNumWords();
469 return isl_val_int_from_chunks(ctx
, n
, sizeof(uint64_t), data
);
472 /* Extract an integer from "expr".
473 * Return NULL if "expr" does not (obviously) represent an integer.
475 __isl_give isl_val
*PetScan::extract_int(clang::ParenExpr
*expr
)
477 return extract_int(expr
->getSubExpr());
480 /* Extract an integer from "expr".
481 * Return NULL if "expr" does not (obviously) represent an integer.
483 __isl_give isl_val
*PetScan::extract_int(clang::Expr
*expr
)
485 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
486 return extract_int(ctx
, cast
<IntegerLiteral
>(expr
));
487 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
488 return extract_int(cast
<ParenExpr
>(expr
));
494 /* Extract a pet_expr from the APInt "val", which is assumed
495 * to be non-negative.
497 __isl_give pet_expr
*PetScan::extract_expr(const llvm::APInt
&val
)
499 return pet_expr_new_int(extract_unsigned(ctx
, val
));
502 /* Return the number of bits needed to represent the type "qt",
503 * if it is an integer type. Otherwise return 0.
504 * If qt is signed then return the opposite of the number of bits.
506 static int get_type_size(QualType qt
, ASTContext
&ast_context
)
510 if (!qt
->isIntegerType())
513 size
= ast_context
.getIntWidth(qt
);
514 if (!qt
->isUnsignedIntegerType())
520 /* Return the number of bits needed to represent the type of "decl",
521 * if it is an integer type. Otherwise return 0.
522 * If qt is signed then return the opposite of the number of bits.
524 static int get_type_size(ValueDecl
*decl
)
526 return get_type_size(decl
->getType(), decl
->getASTContext());
529 /* Bound parameter "pos" of "set" to the possible values of "decl".
531 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
532 unsigned pos
, ValueDecl
*decl
)
538 ctx
= isl_set_get_ctx(set
);
539 type_size
= get_type_size(decl
);
541 isl_die(ctx
, isl_error_invalid
, "not an integer type",
542 return isl_set_free(set
));
544 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
545 bound
= isl_val_int_from_ui(ctx
, type_size
);
546 bound
= isl_val_2exp(bound
);
547 bound
= isl_val_sub_ui(bound
, 1);
548 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
, bound
);
550 bound
= isl_val_int_from_ui(ctx
, -type_size
- 1);
551 bound
= isl_val_2exp(bound
);
552 bound
= isl_val_sub_ui(bound
, 1);
553 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
,
554 isl_val_copy(bound
));
555 bound
= isl_val_neg(bound
);
556 bound
= isl_val_sub_ui(bound
, 1);
557 set
= isl_set_lower_bound_val(set
, isl_dim_param
, pos
, bound
);
563 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
565 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
566 __isl_take isl_set
*dom
)
569 pa
= isl_set_indicator_function(set
);
570 pa
= isl_pw_aff_intersect_domain(pa
, isl_set_coalesce(dom
));
574 /* Extract an affine expression, if possible, from "expr".
575 * Otherwise return NULL.
577 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
583 pe
= extract_expr(expr
);
586 pc
= convert_assignments(ctx
, assigned_value
);
587 pe
= pet_expr_plug_in_args(pe
, pc
);
588 pa
= pet_expr_extract_affine(pe
, pc
);
589 if (isl_pw_aff_involves_nan(pa
)) {
591 pa
= isl_pw_aff_free(pa
);
593 pet_context_free(pc
);
599 __isl_give pet_expr
*PetScan::extract_index_expr(ImplicitCastExpr
*expr
)
601 return extract_index_expr(expr
->getSubExpr());
604 /* Return the depth of an array of the given type.
606 static int array_depth(const Type
*type
)
608 if (type
->isPointerType())
609 return 1 + array_depth(type
->getPointeeType().getTypePtr());
610 if (type
->isArrayType()) {
611 const ArrayType
*atype
;
612 type
= type
->getCanonicalTypeInternal().getTypePtr();
613 atype
= cast
<ArrayType
>(type
);
614 return 1 + array_depth(atype
->getElementType().getTypePtr());
619 /* Return the depth of the array accessed by the index expression "index".
620 * If "index" is an affine expression, i.e., if it does not access
621 * any array, then return 1.
622 * If "index" represent a member access, i.e., if its range is a wrapped
623 * relation, then return the sum of the depth of the array of structures
624 * and that of the member inside the structure.
626 static int extract_depth(__isl_keep isl_multi_pw_aff
*index
)
634 if (isl_multi_pw_aff_range_is_wrapping(index
)) {
635 int domain_depth
, range_depth
;
636 isl_multi_pw_aff
*domain
, *range
;
638 domain
= isl_multi_pw_aff_copy(index
);
639 domain
= isl_multi_pw_aff_range_factor_domain(domain
);
640 domain_depth
= extract_depth(domain
);
641 isl_multi_pw_aff_free(domain
);
642 range
= isl_multi_pw_aff_copy(index
);
643 range
= isl_multi_pw_aff_range_factor_range(range
);
644 range_depth
= extract_depth(range
);
645 isl_multi_pw_aff_free(range
);
647 return domain_depth
+ range_depth
;
650 if (!isl_multi_pw_aff_has_tuple_id(index
, isl_dim_out
))
653 id
= isl_multi_pw_aff_get_tuple_id(index
, isl_dim_out
);
656 decl
= (ValueDecl
*) isl_id_get_user(id
);
659 return array_depth(decl
->getType().getTypePtr());
662 /* Return the depth of the array accessed by the access expression "expr".
664 static int extract_depth(__isl_keep pet_expr
*expr
)
666 isl_multi_pw_aff
*index
;
669 index
= pet_expr_access_get_index(expr
);
670 depth
= extract_depth(index
);
671 isl_multi_pw_aff_free(index
);
676 /* Construct a pet_expr representing an index expression for an access
677 * to the variable referenced by "expr".
679 __isl_give pet_expr
*PetScan::extract_index_expr(DeclRefExpr
*expr
)
681 return extract_index_expr(expr
->getDecl());
684 /* Construct a pet_expr representing an index expression for an access
685 * to the variable "decl".
687 __isl_give pet_expr
*PetScan::extract_index_expr(ValueDecl
*decl
)
689 isl_id
*id
= create_decl_id(ctx
, decl
);
690 isl_space
*space
= isl_space_alloc(ctx
, 0, 0, 0);
692 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
694 return pet_expr_from_index(isl_multi_pw_aff_zero(space
));
697 /* Construct a pet_expr representing the index expression "expr"
698 * Return NULL on error.
700 __isl_give pet_expr
*PetScan::extract_index_expr(Expr
*expr
)
702 switch (expr
->getStmtClass()) {
703 case Stmt::ImplicitCastExprClass
:
704 return extract_index_expr(cast
<ImplicitCastExpr
>(expr
));
705 case Stmt::DeclRefExprClass
:
706 return extract_index_expr(cast
<DeclRefExpr
>(expr
));
707 case Stmt::ArraySubscriptExprClass
:
708 return extract_index_expr(cast
<ArraySubscriptExpr
>(expr
));
709 case Stmt::IntegerLiteralClass
:
710 return extract_expr(cast
<IntegerLiteral
>(expr
));
711 case Stmt::MemberExprClass
:
712 return extract_index_expr(cast
<MemberExpr
>(expr
));
719 /* Extract an index expression from the given array subscript expression.
721 * We first extract an index expression from the base.
722 * This will result in an index expression with a range that corresponds
723 * to the earlier indices.
724 * We then extract the current index and let
725 * pet_expr_access_subscript combine the two.
727 __isl_give pet_expr
*PetScan::extract_index_expr(ArraySubscriptExpr
*expr
)
729 Expr
*base
= expr
->getBase();
730 Expr
*idx
= expr
->getIdx();
734 base_expr
= extract_index_expr(base
);
735 index
= extract_expr(idx
);
737 base_expr
= pet_expr_access_subscript(base_expr
, index
);
742 /* Extract an index expression from a member expression.
744 * If the base access (to the structure containing the member)
749 * and the member is called "f", then the member access is of
754 * If the member access is to an anonymous struct, then simply return
758 * If the member access in the source code is of the form
762 * then it is treated as
766 __isl_give pet_expr
*PetScan::extract_index_expr(MemberExpr
*expr
)
768 Expr
*base
= expr
->getBase();
769 FieldDecl
*field
= cast
<FieldDecl
>(expr
->getMemberDecl());
770 pet_expr
*base_index
;
773 base_index
= extract_index_expr(base
);
775 if (expr
->isArrow()) {
776 pet_expr
*index
= pet_expr_new_int(isl_val_zero(ctx
));
777 base_index
= pet_expr_access_subscript(base_index
, index
);
780 if (field
->isAnonymousStructOrUnion())
783 id
= create_decl_id(ctx
, field
);
785 return pet_expr_access_member(base_index
, id
);
788 /* Check if "expr" calls function "minmax" with two arguments and if so
789 * make lhs and rhs refer to these two arguments.
791 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
797 if (expr
->getStmtClass() != Stmt::CallExprClass
)
800 call
= cast
<CallExpr
>(expr
);
801 fd
= call
->getDirectCallee();
805 if (call
->getNumArgs() != 2)
808 name
= fd
->getDeclName().getAsString();
812 lhs
= call
->getArg(0);
813 rhs
= call
->getArg(1);
818 /* Check if "expr" is of the form min(lhs, rhs) and if so make
819 * lhs and rhs refer to the two arguments.
821 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
823 return is_minmax(expr
, "min", lhs
, rhs
);
826 /* Check if "expr" is of the form max(lhs, rhs) and if so make
827 * lhs and rhs refer to the two arguments.
829 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
831 return is_minmax(expr
, "max", lhs
, rhs
);
834 /* Extract an affine expressions representing the comparison "LHS op RHS"
835 * "comp" is the original statement that "LHS op RHS" is derived from
836 * and is used for diagnostics.
838 * If the comparison is of the form
842 * then the expression is constructed as the conjunction of
847 * A similar optimization is performed for max(a,b) <= c.
848 * We do this because that will lead to simpler representations
850 * If isl is ever enhanced to explicitly deal with min and max expressions,
851 * this optimization can be removed.
853 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
854 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
861 enum pet_op_type type
;
864 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
866 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
868 if (op
== BO_LT
|| op
== BO_LE
) {
870 if (is_min(RHS
, expr1
, expr2
)) {
871 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
872 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
873 return pet_and(lhs
, rhs
);
875 if (is_max(LHS
, expr1
, expr2
)) {
876 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
877 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
878 return pet_and(lhs
, rhs
);
882 lhs
= extract_affine(LHS
);
883 rhs
= extract_affine(RHS
);
885 type
= BinaryOperatorKind2pet_op_type(op
);
886 return pet_comparison(type
, lhs
, rhs
);
889 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
891 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
892 comp
->getRHS(), comp
);
895 /* Extract an affine expression from a boolean expression.
896 * In particular, return the expression "expr ? 1 : 0".
897 * Return NULL if we are unable to extract an affine expression.
899 * We first convert the clang::Expr to a pet_expr and
900 * then extract an affine expression from that pet_expr.
902 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
909 isl_set
*u
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
910 return indicator_function(u
, isl_set_copy(u
));
913 pe
= extract_expr(expr
);
914 pc
= convert_assignments(ctx
, assigned_value
);
915 pe
= pet_expr_plug_in_args(pe
, pc
);
916 pc
= pet_context_set_allow_nested(pc
, nesting_enabled
);
917 cond
= pet_expr_extract_affine_condition(pe
, pc
);
918 if (isl_pw_aff_involves_nan(cond
))
919 cond
= isl_pw_aff_free(cond
);
920 pet_context_free(pc
);
925 /* Mark the given access pet_expr as a write.
927 static __isl_give pet_expr
*mark_write(__isl_take pet_expr
*access
)
929 access
= pet_expr_access_set_write(access
, 1);
930 access
= pet_expr_access_set_read(access
, 0);
935 /* Construct a pet_expr representing a unary operator expression.
937 __isl_give pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
942 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
943 if (op
== pet_op_last
) {
948 arg
= extract_expr(expr
->getSubExpr());
950 if (expr
->isIncrementDecrementOp() &&
951 pet_expr_get_type(arg
) == pet_expr_access
) {
952 arg
= mark_write(arg
);
953 arg
= pet_expr_access_set_read(arg
, 1);
956 return pet_expr_new_unary(op
, arg
);
959 /* If the access expression "expr" writes to a (non-virtual) scalar,
960 * then mark the scalar as having an unknown value in "assigned_value".
962 static int clear_write(__isl_keep pet_expr
*expr
, void *user
)
966 PetScan
*ps
= (PetScan
*) user
;
968 if (!pet_expr_access_is_write(expr
))
970 if (!pet_expr_is_scalar_access(expr
))
973 id
= pet_expr_access_get_id(expr
);
974 decl
= (ValueDecl
*) isl_id_get_user(id
);
978 clear_assignment(ps
->assigned_value
, decl
);
983 /* Take into account the writes in "stmt".
984 * That is, first mark all scalar variables that are written by "stmt"
985 * as having an unknown value. Afterwards,
986 * if "stmt" is a top-level (i.e., unconditional) assignment
987 * to a scalar variable, then update "assigned_value" accordingly.
989 * In particular, if the lhs of the assignment is a scalar variable, then mark
990 * the variable as having been assigned. If, furthermore, the rhs
991 * is an affine expression, then keep track of this value in assigned_value
992 * so that we can plug it in when we later come across the same variable.
994 * We skip assignments to virtual arrays (those with NULL user pointer).
996 void PetScan::handle_writes(struct pet_stmt
*stmt
)
998 pet_expr
*body
= stmt
->body
;
1005 pet_expr_foreach_access_expr(body
, &clear_write
, this);
1007 if (!pet_stmt_is_assign(stmt
))
1009 if (!isl_set_plain_is_universe(stmt
->domain
))
1011 arg
= pet_expr_get_arg(body
, 0);
1012 if (!pet_expr_is_scalar_access(arg
)) {
1017 id
= pet_expr_access_get_id(arg
);
1018 decl
= (ValueDecl
*) isl_id_get_user(id
);
1025 arg
= pet_expr_get_arg(body
, 1);
1026 pc
= convert_assignments(ctx
, assigned_value
);
1027 pa
= pet_expr_extract_affine(arg
, pc
);
1028 pet_context_free(pc
);
1029 clear_assignment(assigned_value
, decl
);
1032 if (isl_pw_aff_involves_nan(pa
))
1033 pa
= isl_pw_aff_free(pa
);
1036 assigned_value
[decl
] = pa
;
1037 insert_expression(pa
);
1040 /* Update "assigned_value" based on the write accesses (and, in particular,
1041 * assignments) in "scop".
1043 void PetScan::handle_writes(struct pet_scop
*scop
)
1047 for (int i
= 0; i
< scop
->n_stmt
; ++i
)
1048 handle_writes(scop
->stmts
[i
]);
1051 /* Construct a pet_expr representing a binary operator expression.
1053 * If the top level operator is an assignment and the LHS is an access,
1054 * then we mark that access as a write. If the operator is a compound
1055 * assignment, the access is marked as both a read and a write.
1057 __isl_give pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1060 pet_expr
*lhs
, *rhs
;
1061 enum pet_op_type op
;
1063 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1064 if (op
== pet_op_last
) {
1069 lhs
= extract_expr(expr
->getLHS());
1070 rhs
= extract_expr(expr
->getRHS());
1072 if (expr
->isAssignmentOp() &&
1073 pet_expr_get_type(lhs
) == pet_expr_access
) {
1074 lhs
= mark_write(lhs
);
1075 if (expr
->isCompoundAssignmentOp())
1076 lhs
= pet_expr_access_set_read(lhs
, 1);
1079 type_size
= get_type_size(expr
->getType(), ast_context
);
1080 return pet_expr_new_binary(type_size
, op
, lhs
, rhs
);
1083 /* Construct a pet_scop with a single statement killing the entire
1086 struct pet_scop
*PetScan::kill(Stmt
*stmt
, struct pet_array
*array
)
1090 isl_multi_pw_aff
*index
;
1096 access
= isl_map_from_range(isl_set_copy(array
->extent
));
1097 id
= isl_set_get_tuple_id(array
->extent
);
1098 space
= isl_space_alloc(ctx
, 0, 0, 0);
1099 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
1100 index
= isl_multi_pw_aff_zero(space
);
1101 expr
= pet_expr_kill_from_access_and_index(access
, index
);
1102 return extract(expr
, stmt
->getSourceRange(), false);
1105 /* Construct a pet_scop for a (single) variable declaration.
1107 * The scop contains the variable being declared (as an array)
1108 * and a statement killing the array.
1110 * If the variable is initialized in the AST, then the scop
1111 * also contains an assignment to the variable.
1113 struct pet_scop
*PetScan::extract(DeclStmt
*stmt
)
1118 pet_expr
*lhs
, *rhs
, *pe
;
1119 struct pet_scop
*scop_decl
, *scop
;
1120 struct pet_array
*array
;
1122 if (!stmt
->isSingleDecl()) {
1127 decl
= stmt
->getSingleDecl();
1128 vd
= cast
<VarDecl
>(decl
);
1130 array
= extract_array(ctx
, vd
, NULL
);
1132 array
->declared
= 1;
1133 scop_decl
= kill(stmt
, array
);
1134 scop_decl
= pet_scop_add_array(scop_decl
, array
);
1139 lhs
= extract_access_expr(vd
);
1140 rhs
= extract_expr(vd
->getInit());
1142 lhs
= mark_write(lhs
);
1144 type_size
= get_type_size(vd
->getType(), ast_context
);
1145 pe
= pet_expr_new_binary(type_size
, pet_op_assign
, lhs
, rhs
);
1146 scop
= extract(pe
, stmt
->getSourceRange(), false);
1148 scop_decl
= pet_scop_prefix(scop_decl
, 0);
1149 scop
= pet_scop_prefix(scop
, 1);
1151 scop
= pet_scop_add_seq(ctx
, scop_decl
, scop
);
1156 /* Construct a pet_expr representing a conditional operation.
1158 __isl_give pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1160 pet_expr
*cond
, *lhs
, *rhs
;
1163 cond
= extract_expr(expr
->getCond());
1164 lhs
= extract_expr(expr
->getTrueExpr());
1165 rhs
= extract_expr(expr
->getFalseExpr());
1167 return pet_expr_new_ternary(cond
, lhs
, rhs
);
1170 __isl_give pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1172 return extract_expr(expr
->getSubExpr());
1175 /* Construct a pet_expr representing a floating point value.
1177 * If the floating point literal does not appear in a macro,
1178 * then we use the original representation in the source code
1179 * as the string representation. Otherwise, we use the pretty
1180 * printer to produce a string representation.
1182 __isl_give pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1186 const LangOptions
&LO
= PP
.getLangOpts();
1187 SourceLocation loc
= expr
->getLocation();
1189 if (!loc
.isMacroID()) {
1190 SourceManager
&SM
= PP
.getSourceManager();
1191 unsigned len
= Lexer::MeasureTokenLength(loc
, SM
, LO
);
1192 s
= string(SM
.getCharacterData(loc
), len
);
1194 llvm::raw_string_ostream
S(s
);
1195 expr
->printPretty(S
, 0, PrintingPolicy(LO
));
1198 d
= expr
->getValueAsApproximateDouble();
1199 return pet_expr_new_double(ctx
, d
, s
.c_str());
1202 /* Convert the index expression "index" into an access pet_expr of type "qt".
1204 __isl_give pet_expr
*PetScan::extract_access_expr(QualType qt
,
1205 __isl_take pet_expr
*index
)
1210 depth
= extract_depth(index
);
1211 type_size
= get_type_size(qt
, ast_context
);
1213 index
= pet_expr_set_type_size(index
, type_size
);
1214 index
= pet_expr_access_set_depth(index
, depth
);
1219 /* Extract an index expression from "expr" and then convert it into
1220 * an access pet_expr.
1222 __isl_give pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1224 return extract_access_expr(expr
->getType(), extract_index_expr(expr
));
1227 /* Extract an index expression from "decl" and then convert it into
1228 * an access pet_expr.
1230 __isl_give pet_expr
*PetScan::extract_access_expr(ValueDecl
*decl
)
1232 return extract_access_expr(decl
->getType(), extract_index_expr(decl
));
1235 __isl_give pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1237 return extract_expr(expr
->getSubExpr());
1240 /* Extract an assume statement from the argument "expr"
1241 * of a __pencil_assume statement.
1243 __isl_give pet_expr
*PetScan::extract_assume(Expr
*expr
)
1245 return pet_expr_new_unary(pet_op_assume
, extract_expr(expr
));
1248 /* Construct a pet_expr corresponding to the function call argument "expr".
1249 * The argument appears in position "pos" of a call to function "fd".
1251 * If we are passing along a pointer to an array element
1252 * or an entire row or even higher dimensional slice of an array,
1253 * then the function being called may write into the array.
1255 * We assume here that if the function is declared to take a pointer
1256 * to a const type, then the function will perform a read
1257 * and that otherwise, it will perform a write.
1259 __isl_give pet_expr
*PetScan::extract_argument(FunctionDecl
*fd
, int pos
,
1263 int is_addr
= 0, is_partial
= 0;
1266 if (expr
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1267 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(expr
);
1268 expr
= ice
->getSubExpr();
1270 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1271 UnaryOperator
*op
= cast
<UnaryOperator
>(expr
);
1272 if (op
->getOpcode() == UO_AddrOf
) {
1274 expr
= op
->getSubExpr();
1277 res
= extract_expr(expr
);
1280 sc
= expr
->getStmtClass();
1281 if ((sc
== Stmt::ArraySubscriptExprClass
||
1282 sc
== Stmt::MemberExprClass
) &&
1283 array_depth(expr
->getType().getTypePtr()) > 0)
1285 if ((is_addr
|| is_partial
) &&
1286 pet_expr_get_type(res
) == pet_expr_access
) {
1288 if (!fd
->hasPrototype()) {
1289 report_prototype_required(expr
);
1290 return pet_expr_free(res
);
1292 parm
= fd
->getParamDecl(pos
);
1293 if (!const_base(parm
->getType()))
1294 res
= mark_write(res
);
1298 res
= pet_expr_new_unary(pet_op_address_of
, res
);
1302 /* Construct a pet_expr representing a function call.
1304 * In the special case of a "call" to __pencil_assume,
1305 * construct an assume expression instead.
1307 __isl_give pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1309 pet_expr
*res
= NULL
;
1314 fd
= expr
->getDirectCallee();
1320 name
= fd
->getDeclName().getAsString();
1321 n_arg
= expr
->getNumArgs();
1323 if (n_arg
== 1 && name
== "__pencil_assume")
1324 return extract_assume(expr
->getArg(0));
1326 res
= pet_expr_new_call(ctx
, name
.c_str(), n_arg
);
1330 for (int i
= 0; i
< n_arg
; ++i
) {
1331 Expr
*arg
= expr
->getArg(i
);
1332 res
= pet_expr_set_arg(res
, i
,
1333 PetScan::extract_argument(fd
, i
, arg
));
1339 /* Construct a pet_expr representing a (C style) cast.
1341 __isl_give pet_expr
*PetScan::extract_expr(CStyleCastExpr
*expr
)
1346 arg
= extract_expr(expr
->getSubExpr());
1350 type
= expr
->getTypeAsWritten();
1351 return pet_expr_new_cast(type
.getAsString().c_str(), arg
);
1354 /* Construct a pet_expr representing an integer.
1356 __isl_give pet_expr
*PetScan::extract_expr(IntegerLiteral
*expr
)
1358 return pet_expr_new_int(extract_int(expr
));
1361 /* Try and construct a pet_expr representing "expr".
1363 __isl_give pet_expr
*PetScan::extract_expr(Expr
*expr
)
1365 switch (expr
->getStmtClass()) {
1366 case Stmt::UnaryOperatorClass
:
1367 return extract_expr(cast
<UnaryOperator
>(expr
));
1368 case Stmt::CompoundAssignOperatorClass
:
1369 case Stmt::BinaryOperatorClass
:
1370 return extract_expr(cast
<BinaryOperator
>(expr
));
1371 case Stmt::ImplicitCastExprClass
:
1372 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1373 case Stmt::ArraySubscriptExprClass
:
1374 case Stmt::DeclRefExprClass
:
1375 case Stmt::MemberExprClass
:
1376 return extract_access_expr(expr
);
1377 case Stmt::IntegerLiteralClass
:
1378 return extract_expr(cast
<IntegerLiteral
>(expr
));
1379 case Stmt::FloatingLiteralClass
:
1380 return extract_expr(cast
<FloatingLiteral
>(expr
));
1381 case Stmt::ParenExprClass
:
1382 return extract_expr(cast
<ParenExpr
>(expr
));
1383 case Stmt::ConditionalOperatorClass
:
1384 return extract_expr(cast
<ConditionalOperator
>(expr
));
1385 case Stmt::CallExprClass
:
1386 return extract_expr(cast
<CallExpr
>(expr
));
1387 case Stmt::CStyleCastExprClass
:
1388 return extract_expr(cast
<CStyleCastExpr
>(expr
));
1395 /* Check if the given initialization statement is an assignment.
1396 * If so, return that assignment. Otherwise return NULL.
1398 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1400 BinaryOperator
*ass
;
1402 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1405 ass
= cast
<BinaryOperator
>(init
);
1406 if (ass
->getOpcode() != BO_Assign
)
1412 /* Check if the given initialization statement is a declaration
1413 * of a single variable.
1414 * If so, return that declaration. Otherwise return NULL.
1416 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1420 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1423 decl
= cast
<DeclStmt
>(init
);
1425 if (!decl
->isSingleDecl())
1428 return decl
->getSingleDecl();
1431 /* Given the assignment operator in the initialization of a for loop,
1432 * extract the induction variable, i.e., the (integer)variable being
1435 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1442 lhs
= init
->getLHS();
1443 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1448 ref
= cast
<DeclRefExpr
>(lhs
);
1449 decl
= ref
->getDecl();
1450 type
= decl
->getType().getTypePtr();
1452 if (!type
->isIntegerType()) {
1460 /* Given the initialization statement of a for loop and the single
1461 * declaration in this initialization statement,
1462 * extract the induction variable, i.e., the (integer) variable being
1465 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1469 vd
= cast
<VarDecl
>(decl
);
1471 const QualType type
= vd
->getType();
1472 if (!type
->isIntegerType()) {
1477 if (!vd
->getInit()) {
1485 /* Check that op is of the form iv++ or iv--.
1486 * Return a pet_expr representing "1" or "-1" accordingly.
1488 __isl_give pet_expr
*PetScan::extract_unary_increment(
1489 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1495 if (!op
->isIncrementDecrementOp()) {
1500 sub
= op
->getSubExpr();
1501 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1506 ref
= cast
<DeclRefExpr
>(sub
);
1507 if (ref
->getDecl() != iv
) {
1512 if (op
->isIncrementOp())
1513 v
= isl_val_one(ctx
);
1515 v
= isl_val_negone(ctx
);
1517 return pet_expr_new_int(v
);
1520 /* Check if op is of the form
1524 * and return the increment "expr - iv" as a pet_expr.
1526 __isl_give pet_expr
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1527 clang::ValueDecl
*iv
)
1532 pet_expr
*expr
, *expr_iv
;
1534 if (op
->getOpcode() != BO_Assign
) {
1540 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1545 ref
= cast
<DeclRefExpr
>(lhs
);
1546 if (ref
->getDecl() != iv
) {
1551 expr
= extract_expr(op
->getRHS());
1552 expr_iv
= extract_expr(lhs
);
1554 type_size
= get_type_size(iv
->getType(), ast_context
);
1555 return pet_expr_new_binary(type_size
, pet_op_sub
, expr
, expr_iv
);
1558 /* Check that op is of the form iv += cst or iv -= cst
1559 * and return a pet_expr corresponding to cst or -cst accordingly.
1561 __isl_give pet_expr
*PetScan::extract_compound_increment(
1562 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1568 BinaryOperatorKind opcode
;
1570 opcode
= op
->getOpcode();
1571 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1575 if (opcode
== BO_SubAssign
)
1579 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1584 ref
= cast
<DeclRefExpr
>(lhs
);
1585 if (ref
->getDecl() != iv
) {
1590 expr
= extract_expr(op
->getRHS());
1592 expr
= pet_expr_new_unary(pet_op_minus
, expr
);
1597 /* Check that the increment of the given for loop increments
1598 * (or decrements) the induction variable "iv" and return
1599 * the increment as a pet_expr if successful.
1601 __isl_give pet_expr
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1604 Stmt
*inc
= stmt
->getInc();
1607 report_missing_increment(stmt
);
1611 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1612 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1613 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1614 return extract_compound_increment(
1615 cast
<CompoundAssignOperator
>(inc
), iv
);
1616 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1617 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1623 /* Embed the given iteration domain in an extra outer loop
1624 * with induction variable "var".
1625 * If this variable appeared as a parameter in the constraints,
1626 * it is replaced by the new outermost dimension.
1628 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1629 __isl_take isl_id
*var
)
1633 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1634 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1636 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1637 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1644 /* Return those elements in the space of "cond" that come after
1645 * (based on "sign") an element in "cond".
1647 static __isl_give isl_set
*after(__isl_take isl_set
*cond
, int sign
)
1649 isl_map
*previous_to_this
;
1652 previous_to_this
= isl_map_lex_lt(isl_set_get_space(cond
));
1654 previous_to_this
= isl_map_lex_gt(isl_set_get_space(cond
));
1656 cond
= isl_set_apply(cond
, previous_to_this
);
1661 /* Create the infinite iteration domain
1663 * { [id] : id >= 0 }
1665 * If "scop" has an affine skip of type pet_skip_later,
1666 * then remove those iterations i that have an earlier iteration
1667 * where the skip condition is satisfied, meaning that iteration i
1669 * Since we are dealing with a loop without loop iterator,
1670 * the skip condition cannot refer to the current loop iterator and
1671 * so effectively, the returned set is of the form
1673 * { [0]; [id] : id >= 1 and not skip }
1675 static __isl_give isl_set
*infinite_domain(__isl_take isl_id
*id
,
1676 struct pet_scop
*scop
)
1678 isl_ctx
*ctx
= isl_id_get_ctx(id
);
1682 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
1683 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, id
);
1685 if (!pet_scop_has_affine_skip(scop
, pet_skip_later
))
1688 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
1689 skip
= embed(skip
, isl_id_copy(id
));
1690 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
1691 domain
= isl_set_subtract(domain
, after(skip
, 1));
1696 /* Create an identity affine expression on the space containing "domain",
1697 * which is assumed to be one-dimensional.
1699 static __isl_give isl_aff
*identity_aff(__isl_keep isl_set
*domain
)
1701 isl_local_space
*ls
;
1703 ls
= isl_local_space_from_space(isl_set_get_space(domain
));
1704 return isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
1707 /* Create an affine expression that maps elements
1708 * of a single-dimensional array "id_test" to the previous element
1709 * (according to "inc"), provided this element belongs to "domain".
1710 * That is, create the affine expression
1712 * { id[x] -> id[x - inc] : x - inc in domain }
1714 static __isl_give isl_multi_pw_aff
*map_to_previous(__isl_take isl_id
*id_test
,
1715 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
1718 isl_local_space
*ls
;
1720 isl_multi_pw_aff
*prev
;
1722 space
= isl_set_get_space(domain
);
1723 ls
= isl_local_space_from_space(space
);
1724 aff
= isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
1725 aff
= isl_aff_add_constant_val(aff
, isl_val_neg(inc
));
1726 prev
= isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
1727 domain
= isl_set_preimage_multi_pw_aff(domain
,
1728 isl_multi_pw_aff_copy(prev
));
1729 prev
= isl_multi_pw_aff_intersect_domain(prev
, domain
);
1730 prev
= isl_multi_pw_aff_set_tuple_id(prev
, isl_dim_out
, id_test
);
1735 /* Add an implication to "scop" expressing that if an element of
1736 * virtual array "id_test" has value "satisfied" then all previous elements
1737 * of this array also have that value. The set of previous elements
1738 * is bounded by "domain". If "sign" is negative then the iterator
1739 * is decreasing and we express that all subsequent array elements
1740 * (but still defined previously) have the same value.
1742 static struct pet_scop
*add_implication(struct pet_scop
*scop
,
1743 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
, int sign
,
1749 domain
= isl_set_set_tuple_id(domain
, id_test
);
1750 space
= isl_set_get_space(domain
);
1752 map
= isl_map_lex_ge(space
);
1754 map
= isl_map_lex_le(space
);
1755 map
= isl_map_intersect_range(map
, domain
);
1756 scop
= pet_scop_add_implication(scop
, map
, satisfied
);
1761 /* Add a filter to "scop" that imposes that it is only executed
1762 * when the variable identified by "id_test" has a zero value
1763 * for all previous iterations of "domain".
1765 * In particular, add a filter that imposes that the array
1766 * has a zero value at the previous iteration of domain and
1767 * add an implication that implies that it then has that
1768 * value for all previous iterations.
1770 static struct pet_scop
*scop_add_break(struct pet_scop
*scop
,
1771 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
,
1772 __isl_take isl_val
*inc
)
1774 isl_multi_pw_aff
*prev
;
1775 int sign
= isl_val_sgn(inc
);
1777 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
1778 scop
= add_implication(scop
, id_test
, domain
, sign
, 0);
1779 scop
= pet_scop_filter(scop
, prev
, 0);
1784 /* Construct a pet_scop for an infinite loop around the given body.
1786 * We extract a pet_scop for the body and then embed it in a loop with
1795 * If the body contains any break, then it is taken into
1796 * account in infinite_domain (if the skip condition is affine)
1797 * or in scop_add_break (if the skip condition is not affine).
1799 * If we were only able to extract part of the body, then simply
1802 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
1804 isl_id
*id
, *id_test
;
1807 struct pet_scop
*scop
;
1810 scop
= extract(body
);
1816 id
= isl_id_alloc(ctx
, "t", NULL
);
1817 domain
= infinite_domain(isl_id_copy(id
), scop
);
1818 ident
= identity_aff(domain
);
1820 has_var_break
= pet_scop_has_var_skip(scop
, pet_skip_later
);
1822 id_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
1824 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
1825 isl_aff_copy(ident
), ident
, id
);
1827 scop
= scop_add_break(scop
, id_test
, domain
, isl_val_one(ctx
));
1829 isl_set_free(domain
);
1834 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1840 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
1842 clear_assignments
clear(assigned_value
);
1843 clear
.TraverseStmt(stmt
->getBody());
1845 return extract_infinite_loop(stmt
->getBody());
1848 /* Add an array with the given extent (range of "index") to the list
1849 * of arrays in "scop" and return the extended pet_scop.
1850 * The array is marked as attaining values 0 and 1 only and
1851 * as each element being assigned at most once.
1853 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
1854 __isl_keep isl_multi_pw_aff
*index
, clang::ASTContext
&ast_ctx
)
1856 int int_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
1858 return pet_scop_add_boolean_array(scop
, isl_multi_pw_aff_copy(index
),
1862 /* Construct a pet_scop for a while loop of the form
1867 * In particular, construct a scop for an infinite loop around body and
1868 * intersect the domain with the affine expression.
1869 * Note that this intersection may result in an empty loop.
1871 struct pet_scop
*PetScan::extract_affine_while(__isl_take isl_pw_aff
*pa
,
1874 struct pet_scop
*scop
;
1878 valid
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
1879 dom
= isl_pw_aff_non_zero_set(pa
);
1880 scop
= extract_infinite_loop(body
);
1881 scop
= pet_scop_restrict(scop
, isl_set_params(dom
));
1882 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid
));
1887 /* Construct a scop for a while, given the scops for the condition
1888 * and the body, the filter identifier and the iteration domain of
1891 * In particular, the scop for the condition is filtered to depend
1892 * on "id_test" evaluating to true for all previous iterations
1893 * of the loop, while the scop for the body is filtered to depend
1894 * on "id_test" evaluating to true for all iterations up to the
1895 * current iteration.
1896 * The actual filter only imposes that this virtual array has
1897 * value one on the previous or the current iteration.
1898 * The fact that this condition also applies to the previous
1899 * iterations is enforced by an implication.
1901 * These filtered scops are then combined into a single scop.
1903 * "sign" is positive if the iterator increases and negative
1906 static struct pet_scop
*scop_add_while(struct pet_scop
*scop_cond
,
1907 struct pet_scop
*scop_body
, __isl_take isl_id
*id_test
,
1908 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
1910 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
1912 isl_multi_pw_aff
*test_index
;
1913 isl_multi_pw_aff
*prev
;
1914 int sign
= isl_val_sgn(inc
);
1915 struct pet_scop
*scop
;
1917 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
1918 scop_cond
= pet_scop_filter(scop_cond
, prev
, 1);
1920 space
= isl_space_map_from_set(isl_set_get_space(domain
));
1921 test_index
= isl_multi_pw_aff_identity(space
);
1922 test_index
= isl_multi_pw_aff_set_tuple_id(test_index
, isl_dim_out
,
1923 isl_id_copy(id_test
));
1924 scop_body
= pet_scop_filter(scop_body
, test_index
, 1);
1926 scop
= pet_scop_add_seq(ctx
, scop_cond
, scop_body
);
1927 scop
= add_implication(scop
, id_test
, domain
, sign
, 1);
1932 /* Check if the while loop is of the form
1934 * while (affine expression)
1937 * If so, call extract_affine_while to construct a scop.
1939 * Otherwise, extract the body and pass control to extract_while
1940 * to extend the iteration domain with an infinite loop.
1941 * If we were only able to extract part of the body, then simply
1944 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
1947 int test_nr
, stmt_nr
;
1949 struct pet_scop
*scop_body
;
1951 cond
= stmt
->getCond();
1957 clear_assignments
clear(assigned_value
);
1958 clear
.TraverseStmt(stmt
->getBody());
1960 pa
= extract_condition(cond
);
1962 return extract_affine_while(pa
, stmt
->getBody());
1964 if (!allow_nested
) {
1971 scop_body
= extract(stmt
->getBody());
1975 return extract_while(cond
, test_nr
, stmt_nr
, scop_body
, NULL
);
1978 /* Construct a generic while scop, with iteration domain
1979 * { [t] : t >= 0 } around "scop_body". The scop consists of two parts,
1980 * one for evaluating the condition "cond" and one for the body.
1981 * "test_nr" is the sequence number of the virtual test variable that contains
1982 * the result of the condition and "stmt_nr" is the sequence number
1983 * of the statement that evaluates the condition.
1984 * If "scop_inc" is not NULL, then it is added at the end of the body,
1985 * after replacing any skip conditions resulting from continue statements
1986 * by the skip conditions resulting from break statements (if any).
1988 * The schedule is adjusted to reflect that the condition is evaluated
1989 * before the body is executed and the body is filtered to depend
1990 * on the result of the condition evaluating to true on all iterations
1991 * up to the current iteration, while the evaluation of the condition itself
1992 * is filtered to depend on the result of the condition evaluating to true
1993 * on all previous iterations.
1994 * The context of the scop representing the body is dropped
1995 * because we don't know how many times the body will be executed,
1998 * If the body contains any break, then it is taken into
1999 * account in infinite_domain (if the skip condition is affine)
2000 * or in scop_add_break (if the skip condition is not affine).
2002 struct pet_scop
*PetScan::extract_while(Expr
*cond
, int test_nr
, int stmt_nr
,
2003 struct pet_scop
*scop_body
, struct pet_scop
*scop_inc
)
2005 isl_id
*id
, *id_test
, *id_break_test
;
2008 isl_multi_pw_aff
*test_index
;
2009 struct pet_scop
*scop
;
2012 test_index
= pet_create_test_index(ctx
, test_nr
);
2013 scop
= extract_non_affine_condition(cond
, stmt_nr
,
2014 isl_multi_pw_aff_copy(test_index
));
2015 scop
= scop_add_array(scop
, test_index
, ast_context
);
2016 id_test
= isl_multi_pw_aff_get_tuple_id(test_index
, isl_dim_out
);
2017 isl_multi_pw_aff_free(test_index
);
2019 id
= isl_id_alloc(ctx
, "t", NULL
);
2020 domain
= infinite_domain(isl_id_copy(id
), scop_body
);
2021 ident
= identity_aff(domain
);
2023 has_var_break
= pet_scop_has_var_skip(scop_body
, pet_skip_later
);
2025 id_break_test
= pet_scop_get_skip_id(scop_body
, pet_skip_later
);
2027 scop
= pet_scop_prefix(scop
, 0);
2028 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), isl_aff_copy(ident
),
2029 isl_aff_copy(ident
), isl_id_copy(id
));
2030 scop_body
= pet_scop_reset_context(scop_body
);
2031 scop_body
= pet_scop_prefix(scop_body
, 1);
2033 scop_inc
= pet_scop_prefix(scop_inc
, 2);
2034 if (pet_scop_has_skip(scop_body
, pet_skip_later
)) {
2035 isl_multi_pw_aff
*skip
;
2036 skip
= pet_scop_get_skip(scop_body
, pet_skip_later
);
2037 scop_body
= pet_scop_set_skip(scop_body
,
2038 pet_skip_now
, skip
);
2040 pet_scop_reset_skip(scop_body
, pet_skip_now
);
2041 scop_body
= pet_scop_add_seq(ctx
, scop_body
, scop_inc
);
2043 scop_body
= pet_scop_embed(scop_body
, isl_set_copy(domain
),
2044 isl_aff_copy(ident
), ident
, id
);
2046 if (has_var_break
) {
2047 scop
= scop_add_break(scop
, isl_id_copy(id_break_test
),
2048 isl_set_copy(domain
), isl_val_one(ctx
));
2049 scop_body
= scop_add_break(scop_body
, id_break_test
,
2050 isl_set_copy(domain
), isl_val_one(ctx
));
2052 scop
= scop_add_while(scop
, scop_body
, id_test
, domain
,
2058 /* Check whether "cond" expresses a simple loop bound
2059 * on the only set dimension.
2060 * In particular, if "up" is set then "cond" should contain only
2061 * upper bounds on the set dimension.
2062 * Otherwise, it should contain only lower bounds.
2064 static bool is_simple_bound(__isl_keep isl_set
*cond
, __isl_keep isl_val
*inc
)
2066 if (isl_val_is_pos(inc
))
2067 return !isl_set_dim_has_any_lower_bound(cond
, isl_dim_set
, 0);
2069 return !isl_set_dim_has_any_upper_bound(cond
, isl_dim_set
, 0);
2072 /* Extend a condition on a given iteration of a loop to one that
2073 * imposes the same condition on all previous iterations.
2074 * "domain" expresses the lower [upper] bound on the iterations
2075 * when inc is positive [negative].
2077 * In particular, we construct the condition (when inc is positive)
2079 * forall i' : (domain(i') and i' <= i) => cond(i')
2081 * which is equivalent to
2083 * not exists i' : domain(i') and i' <= i and not cond(i')
2085 * We construct this set by negating cond, applying a map
2087 * { [i'] -> [i] : domain(i') and i' <= i }
2089 * and then negating the result again.
2091 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
2092 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2094 isl_map
*previous_to_this
;
2096 if (isl_val_is_pos(inc
))
2097 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
2099 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
2101 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
2103 cond
= isl_set_complement(cond
);
2104 cond
= isl_set_apply(cond
, previous_to_this
);
2105 cond
= isl_set_complement(cond
);
2112 /* Construct a domain of the form
2114 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2116 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
2117 __isl_take isl_pw_aff
*init
, __isl_take isl_val
*inc
)
2123 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
2124 dim
= isl_pw_aff_get_domain_space(init
);
2125 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2126 aff
= isl_aff_add_coefficient_val(aff
, isl_dim_in
, 0, inc
);
2127 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2129 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2130 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2131 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2132 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2134 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2136 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2138 return isl_set_params(set
);
2141 /* Assuming "cond" represents a bound on a loop where the loop
2142 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2145 * Under the given assumptions, wrapping is only possible if "cond" allows
2146 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2147 * increasing iterator and 0 in case of a decreasing iterator.
2149 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
,
2150 __isl_keep isl_val
*inc
)
2157 test
= isl_set_copy(cond
);
2159 ctx
= isl_set_get_ctx(test
);
2160 if (isl_val_is_neg(inc
))
2161 limit
= isl_val_zero(ctx
);
2163 limit
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2164 limit
= isl_val_2exp(limit
);
2165 limit
= isl_val_sub_ui(limit
, 1);
2168 test
= isl_set_fix_val(cond
, isl_dim_set
, 0, limit
);
2169 cw
= !isl_set_is_empty(test
);
2175 /* Given a one-dimensional space, construct the following affine expression
2178 * { [v] -> [v mod 2^width] }
2180 * where width is the number of bits used to represent the values
2181 * of the unsigned variable "iv".
2183 static __isl_give isl_aff
*compute_wrapping(__isl_take isl_space
*dim
,
2190 ctx
= isl_space_get_ctx(dim
);
2191 mod
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2192 mod
= isl_val_2exp(mod
);
2194 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2195 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2196 aff
= isl_aff_mod_val(aff
, mod
);
2201 /* Project out the parameter "id" from "set".
2203 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2204 __isl_keep isl_id
*id
)
2208 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2210 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2215 /* Compute the set of parameters for which "set1" is a subset of "set2".
2217 * set1 is a subset of set2 if
2219 * forall i in set1 : i in set2
2223 * not exists i in set1 and i not in set2
2227 * not exists i in set1 \ set2
2229 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2230 __isl_take isl_set
*set2
)
2232 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2235 /* Compute the set of parameter values for which "cond" holds
2236 * on the next iteration for each element of "dom".
2238 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2239 * and then compute the set of parameters for which the result is a subset
2242 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2243 __isl_take isl_set
*dom
, __isl_take isl_val
*inc
)
2249 space
= isl_set_get_space(dom
);
2250 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2251 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2252 aff
= isl_aff_add_constant_val(aff
, inc
);
2253 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2255 dom
= isl_set_apply(dom
, next
);
2257 return enforce_subset(dom
, cond
);
2260 /* Extract the for loop "stmt" as a while loop.
2261 * "iv" is the loop iterator. "init" is the initialization.
2262 * "inc" is the increment.
2264 * That is, the for loop has the form
2266 * for (iv = init; cond; iv += inc)
2277 * except that the skips resulting from any continue statements
2278 * in body do not apply to the increment, but are replaced by the skips
2279 * resulting from break statements.
2281 * If "iv" is declared in the for loop, then it is killed before
2282 * and after the loop.
2284 struct pet_scop
*PetScan::extract_non_affine_for(ForStmt
*stmt
, ValueDecl
*iv
,
2285 __isl_take pet_expr
*init
, __isl_take pet_expr
*inc
)
2288 int test_nr
, stmt_nr
;
2290 struct pet_scop
*scop_init
, *scop_inc
, *scop
, *scop_body
;
2292 struct pet_array
*array
;
2293 struct pet_scop
*scop_kill
;
2295 if (!allow_nested
) {
2300 clear_assignment(assigned_value
, iv
);
2302 declared
= !initialization_assignment(stmt
->getInit());
2304 expr_iv
= extract_access_expr(iv
);
2305 expr_iv
= mark_write(expr_iv
);
2306 type_size
= pet_expr_get_type_size(expr_iv
);
2307 init
= pet_expr_new_binary(type_size
, pet_op_assign
, expr_iv
, init
);
2308 scop_init
= extract(init
, stmt
->getInit()->getSourceRange(), false);
2309 scop_init
= pet_scop_prefix(scop_init
, declared
);
2313 scop_body
= extract(stmt
->getBody());
2315 pet_scop_free(scop_init
);
2319 expr_iv
= extract_access_expr(iv
);
2320 expr_iv
= mark_write(expr_iv
);
2321 type_size
= pet_expr_get_type_size(expr_iv
);
2322 inc
= pet_expr_new_binary(type_size
, pet_op_add_assign
, expr_iv
, inc
);
2323 scop_inc
= extract(inc
, stmt
->getInc()->getSourceRange(), false);
2325 pet_scop_free(scop_init
);
2326 pet_scop_free(scop_body
);
2330 scop
= extract_while(stmt
->getCond(), test_nr
, stmt_nr
, scop_body
,
2333 scop
= pet_scop_prefix(scop
, declared
+ 1);
2334 scop
= pet_scop_add_seq(ctx
, scop_init
, scop
);
2339 array
= extract_array(ctx
, iv
, NULL
);
2341 array
->declared
= 1;
2342 scop_kill
= kill(stmt
, array
);
2343 scop_kill
= pet_scop_prefix(scop_kill
, 0);
2344 scop
= pet_scop_add_seq(ctx
, scop_kill
, scop
);
2345 scop_kill
= kill(stmt
, array
);
2346 scop_kill
= pet_scop_add_array(scop_kill
, array
);
2347 scop_kill
= pet_scop_prefix(scop_kill
, 3);
2348 scop
= pet_scop_add_seq(ctx
, scop
, scop_kill
);
2353 /* Construct a pet_scop for a for statement.
2354 * The for loop is required to be of one of the following forms
2356 * for (i = init; condition; ++i)
2357 * for (i = init; condition; --i)
2358 * for (i = init; condition; i += constant)
2359 * for (i = init; condition; i -= constant)
2361 * The initialization of the for loop should either be an assignment
2362 * of a static affine value to an integer variable, or a declaration
2363 * of such a variable with initialization.
2365 * If the initialization or the increment do not satisfy the above
2366 * conditions, i.e., if the initialization is not static affine
2367 * or the increment is not constant, then the for loop is extracted
2368 * as a while loop instead.
2370 * The condition is allowed to contain nested accesses, provided
2371 * they are not being written to inside the body of the loop.
2372 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2373 * essentially treated as a while loop, with iteration domain
2374 * { [i] : i >= init }.
2376 * We extract a pet_scop for the body and then embed it in a loop with
2377 * iteration domain and schedule
2379 * { [i] : i >= init and condition' }
2384 * { [i] : i <= init and condition' }
2387 * Where condition' is equal to condition if the latter is
2388 * a simple upper [lower] bound and a condition that is extended
2389 * to apply to all previous iterations otherwise.
2391 * If the condition is non-affine, then we drop the condition from the
2392 * iteration domain and instead create a separate statement
2393 * for evaluating the condition. The body is then filtered to depend
2394 * on the result of the condition evaluating to true on all iterations
2395 * up to the current iteration, while the evaluation the condition itself
2396 * is filtered to depend on the result of the condition evaluating to true
2397 * on all previous iterations.
2398 * The context of the scop representing the body is dropped
2399 * because we don't know how many times the body will be executed,
2402 * If the stride of the loop is not 1, then "i >= init" is replaced by
2404 * (exists a: i = init + stride * a and a >= 0)
2406 * If the loop iterator i is unsigned, then wrapping may occur.
2407 * We therefore use a virtual iterator instead that does not wrap.
2408 * However, the condition in the code applies
2409 * to the wrapped value, so we need to change condition(i)
2410 * into condition([i % 2^width]). Similarly, we replace all accesses
2411 * to the original iterator by the wrapping of the virtual iterator.
2412 * Note that there may be no need to perform this final wrapping
2413 * if the loop condition (after wrapping) satisfies certain conditions.
2414 * However, the is_simple_bound condition is not enough since it doesn't
2415 * check if there even is an upper bound.
2417 * Wrapping on unsigned iterators can be avoided entirely if
2418 * loop condition is simple, the loop iterator is incremented
2419 * [decremented] by one and the last value before wrapping cannot
2420 * possibly satisfy the loop condition.
2422 * Before extracting a pet_scop from the body we remove all
2423 * assignments in assigned_value to variables that are assigned
2424 * somewhere in the body of the loop.
2426 * Valid parameters for a for loop are those for which the initial
2427 * value itself, the increment on each domain iteration and
2428 * the condition on both the initial value and
2429 * the result of incrementing the iterator for each iteration of the domain
2431 * If the loop condition is non-affine, then we only consider validity
2432 * of the initial value.
2434 * If the body contains any break, then we keep track of it in "skip"
2435 * (if the skip condition is affine) or it is handled in scop_add_break
2436 * (if the skip condition is not affine).
2437 * Note that the affine break condition needs to be considered with
2438 * respect to previous iterations in the virtual domain (if any).
2440 * If we were only able to extract part of the body, then simply
2443 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2445 BinaryOperator
*ass
;
2450 isl_local_space
*ls
;
2453 isl_set
*cond
= NULL
;
2454 isl_set
*skip
= NULL
;
2455 isl_id
*id
, *id_test
= NULL
, *id_break_test
;
2456 struct pet_scop
*scop
, *scop_cond
= NULL
;
2457 assigned_value_cache
cache(assigned_value
);
2463 bool has_affine_break
;
2465 isl_aff
*wrap
= NULL
;
2466 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2467 isl_set
*valid_init
;
2468 isl_set
*valid_cond
;
2469 isl_set
*valid_cond_init
;
2470 isl_set
*valid_cond_next
;
2473 pet_expr
*pe_init
, *pe_inc
;
2474 pet_context
*pc
, *pc_init_val
;
2476 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2477 return extract_infinite_for(stmt
);
2479 init
= stmt
->getInit();
2484 if ((ass
= initialization_assignment(init
)) != NULL
) {
2485 iv
= extract_induction_variable(ass
);
2488 lhs
= ass
->getLHS();
2489 rhs
= ass
->getRHS();
2490 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2491 VarDecl
*var
= extract_induction_variable(init
, decl
);
2495 rhs
= var
->getInit();
2496 lhs
= create_DeclRefExpr(var
);
2498 unsupported(stmt
->getInit());
2502 id
= create_decl_id(ctx
, iv
);
2504 assigned_value
.erase(iv
);
2505 clear_assignments
clear(assigned_value
);
2506 clear
.TraverseStmt(stmt
->getBody());
2508 pe_init
= extract_expr(rhs
);
2509 pe_inc
= extract_increment(stmt
, iv
);
2510 pc
= convert_assignments(ctx
, assigned_value
);
2511 pc_init_val
= pet_context_copy(pc
);
2512 pc_init_val
= pet_context_mark_unknown(pc_init_val
, isl_id_copy(id
));
2513 init_val
= pet_expr_extract_affine(pe_init
, pc_init_val
);
2514 pet_context_free(pc_init_val
);
2515 pa_inc
= pet_expr_extract_affine(pe_inc
, pc
);
2516 pet_context_free(pc
);
2517 inc
= pet_extract_cst(pa_inc
);
2518 if (!pe_init
|| !pe_inc
|| !inc
|| isl_val_is_nan(inc
) ||
2519 isl_pw_aff_involves_nan(pa_inc
) ||
2520 isl_pw_aff_involves_nan(init_val
)) {
2523 isl_pw_aff_free(pa_inc
);
2524 isl_pw_aff_free(init_val
);
2525 if (pe_init
&& pe_inc
&& !(pa_inc
&& !inc
))
2526 return extract_non_affine_for(stmt
, iv
,
2528 pet_expr_free(pe_init
);
2529 pet_expr_free(pe_inc
);
2532 pet_expr_free(pe_init
);
2533 pet_expr_free(pe_inc
);
2535 pa
= try_extract_nested_condition(stmt
->getCond());
2536 if (allow_nested
&& (!pa
|| pet_nested_any_in_pw_aff(pa
)))
2539 scop
= extract(stmt
->getBody());
2542 isl_pw_aff_free(init_val
);
2543 isl_pw_aff_free(pa_inc
);
2544 isl_pw_aff_free(pa
);
2549 valid_inc
= isl_pw_aff_domain(pa_inc
);
2551 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2553 has_affine_break
= scop
&&
2554 pet_scop_has_affine_skip(scop
, pet_skip_later
);
2555 if (has_affine_break
)
2556 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
2557 has_var_break
= scop
&& pet_scop_has_var_skip(scop
, pet_skip_later
);
2559 id_break_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
2561 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2562 isl_pw_aff_free(pa
);
2566 if (!allow_nested
&& !pa
)
2567 pa
= extract_condition(stmt
->getCond());
2568 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2569 cond
= isl_pw_aff_non_zero_set(pa
);
2570 if (allow_nested
&& !cond
) {
2571 isl_multi_pw_aff
*test_index
;
2572 int save_n_stmt
= n_stmt
;
2573 test_index
= pet_create_test_index(ctx
, n_test
++);
2575 scop_cond
= extract_non_affine_condition(stmt
->getCond(),
2576 n_stmt
++, isl_multi_pw_aff_copy(test_index
));
2577 n_stmt
= save_n_stmt
;
2578 scop_cond
= scop_add_array(scop_cond
, test_index
, ast_context
);
2579 id_test
= isl_multi_pw_aff_get_tuple_id(test_index
,
2581 isl_multi_pw_aff_free(test_index
);
2582 scop_cond
= pet_scop_prefix(scop_cond
, 0);
2583 scop
= pet_scop_reset_context(scop
);
2584 scop
= pet_scop_prefix(scop
, 1);
2585 cond
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2588 cond
= embed(cond
, isl_id_copy(id
));
2589 skip
= embed(skip
, isl_id_copy(id
));
2590 valid_cond
= isl_set_coalesce(valid_cond
);
2591 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
2592 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
2593 is_one
= isl_val_is_one(inc
) || isl_val_is_negone(inc
);
2594 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2596 valid_cond_init
= enforce_subset(
2597 isl_map_range(isl_map_from_pw_aff(isl_pw_aff_copy(init_val
))),
2598 isl_set_copy(valid_cond
));
2599 if (is_one
&& !is_virtual
) {
2600 isl_pw_aff_free(init_val
);
2601 pa
= extract_comparison(isl_val_is_pos(inc
) ? BO_GE
: BO_LE
,
2603 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2604 valid_init
= set_project_out_by_id(valid_init
, id
);
2605 domain
= isl_pw_aff_non_zero_set(pa
);
2607 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
2608 domain
= strided_domain(isl_id_copy(id
), init_val
,
2612 domain
= embed(domain
, isl_id_copy(id
));
2615 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2616 rev_wrap
= isl_map_from_aff(isl_aff_copy(wrap
));
2617 rev_wrap
= isl_map_reverse(rev_wrap
);
2618 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
2619 skip
= isl_set_apply(skip
, isl_map_copy(rev_wrap
));
2620 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
2621 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
2623 is_simple
= is_simple_bound(cond
, inc
);
2625 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2626 is_simple
= is_simple_bound(cond
, inc
);
2629 cond
= valid_for_each_iteration(cond
,
2630 isl_set_copy(domain
), isl_val_copy(inc
));
2631 domain
= isl_set_intersect(domain
, cond
);
2632 if (has_affine_break
) {
2633 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2634 skip
= after(skip
, isl_val_sgn(inc
));
2635 domain
= isl_set_subtract(domain
, skip
);
2637 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2638 ls
= isl_local_space_from_space(isl_set_get_space(domain
));
2639 sched
= isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
2640 if (isl_val_is_neg(inc
))
2641 sched
= isl_aff_neg(sched
);
2643 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
),
2645 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
2648 wrap
= identity_aff(domain
);
2650 scop_cond
= pet_scop_embed(scop_cond
, isl_set_copy(domain
),
2651 isl_aff_copy(sched
), isl_aff_copy(wrap
), isl_id_copy(id
));
2652 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), sched
, wrap
, id
);
2653 scop
= resolve_nested(scop
);
2655 scop
= scop_add_break(scop
, id_break_test
, isl_set_copy(domain
),
2658 scop
= scop_add_while(scop_cond
, scop
, id_test
, domain
,
2660 isl_set_free(valid_inc
);
2662 scop
= pet_scop_restrict_context(scop
, valid_inc
);
2663 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
2664 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
2665 isl_set_free(domain
);
2667 clear_assignment(assigned_value
, iv
);
2671 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid_init
));
2676 /* Try and construct a pet_scop corresponding to a compound statement.
2678 * "skip_declarations" is set if we should skip initial declarations
2679 * in the children of the compound statements. This then implies
2680 * that this sequence of children should not be treated as a block
2681 * since the initial statements may be skipped.
2683 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
, bool skip_declarations
)
2685 return extract(stmt
->children(), !skip_declarations
, skip_declarations
);
2688 /* For each nested access parameter in "space",
2689 * construct a corresponding pet_expr, place it in args and
2690 * record its position in "param2pos".
2691 * "n_arg" is the number of elements that are already in args.
2692 * The position recorded in "param2pos" takes this number into account.
2693 * If the pet_expr corresponding to a parameter is identical to
2694 * the pet_expr corresponding to an earlier parameter, then these two
2695 * parameters are made to refer to the same element in args.
2697 * Return the final number of elements in args or -1 if an error has occurred.
2699 int PetScan::extract_nested(__isl_keep isl_space
*space
,
2700 int n_arg
, pet_expr
**args
, std::map
<int,int> ¶m2pos
)
2704 nparam
= isl_space_dim(space
, isl_dim_param
);
2705 for (int i
= 0; i
< nparam
; ++i
) {
2707 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2709 if (!pet_nested_in_id(id
)) {
2714 args
[n_arg
] = pet_nested_extract_expr(id
);
2719 for (j
= 0; j
< n_arg
; ++j
)
2720 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
2724 pet_expr_free(args
[n_arg
]);
2728 param2pos
[i
] = n_arg
++;
2734 /* For each nested access parameter in the access relations in "expr",
2735 * construct a corresponding pet_expr, append it to the arguments of "expr"
2736 * and record its position in "param2pos" (relative to the initial
2737 * number of arguments).
2738 * n is the number of nested access parameters.
2740 __isl_give pet_expr
*PetScan::extract_nested(__isl_take pet_expr
*expr
, int n
,
2741 std::map
<int,int> ¶m2pos
)
2747 args
= isl_calloc_array(ctx
, pet_expr
*, n
);
2749 return pet_expr_free(expr
);
2751 n_arg
= pet_expr_get_n_arg(expr
);
2752 space
= pet_expr_access_get_parameter_space(expr
);
2753 n
= extract_nested(space
, 0, args
, param2pos
);
2754 isl_space_free(space
);
2757 expr
= pet_expr_free(expr
);
2759 expr
= pet_expr_set_n_arg(expr
, n_arg
+ n
);
2761 for (i
= 0; i
< n
; ++i
)
2762 expr
= pet_expr_set_arg(expr
, n_arg
+ i
, args
[i
]);
2768 /* Are "expr1" and "expr2" both array accesses such that
2769 * the access relation of "expr1" is a subset of that of "expr2"?
2770 * Only take into account the first "n_arg" arguments.
2772 static int is_sub_access(__isl_keep pet_expr
*expr1
, __isl_keep pet_expr
*expr2
,
2776 isl_map
*access1
, *access2
;
2780 if (!expr1
|| !expr2
)
2782 if (pet_expr_get_type(expr1
) != pet_expr_access
)
2784 if (pet_expr_get_type(expr2
) != pet_expr_access
)
2786 if (pet_expr_is_affine(expr1
))
2788 if (pet_expr_is_affine(expr2
))
2790 n1
= pet_expr_get_n_arg(expr1
);
2793 n2
= pet_expr_get_n_arg(expr2
);
2798 for (i
= 0; i
< n1
; ++i
) {
2799 pet_expr
*arg1
, *arg2
;
2801 arg1
= pet_expr_get_arg(expr1
, i
);
2802 arg2
= pet_expr_get_arg(expr2
, i
);
2803 equal
= pet_expr_is_equal(arg1
, arg2
);
2804 pet_expr_free(arg1
);
2805 pet_expr_free(arg2
);
2806 if (equal
< 0 || !equal
)
2809 id1
= pet_expr_access_get_id(expr1
);
2810 id2
= pet_expr_access_get_id(expr2
);
2818 access1
= pet_expr_access_get_access(expr1
);
2819 access2
= pet_expr_access_get_access(expr2
);
2820 is_subset
= isl_map_is_subset(access1
, access2
);
2821 isl_map_free(access1
);
2822 isl_map_free(access2
);
2827 /* Mark self dependences among the arguments of "expr" starting at "first".
2828 * These arguments have already been added to the list of arguments
2829 * but are not yet referenced directly from the index expression.
2830 * Instead, they are still referenced through parameters encoding
2833 * In particular, if "expr" is a read access, then check the arguments
2834 * starting at "first" to see if "expr" accesses a subset of
2835 * the elements accessed by the argument, or under more restrictive conditions.
2836 * If so, then this nested access can be removed from the constraints
2837 * governing the outer access. There is no point in restricting
2838 * accesses to an array if in order to evaluate the restriction,
2839 * we have to access the same elements (or more).
2841 * Rather than removing the argument at this point (which would
2842 * complicate the resolution of the other nested accesses), we simply
2843 * mark it here by replacing it by a NaN pet_expr.
2844 * These NaNs are then later removed in remove_marked_self_dependences.
2846 static __isl_give pet_expr
*mark_self_dependences(__isl_take pet_expr
*expr
,
2851 if (pet_expr_access_is_write(expr
))
2854 n
= pet_expr_get_n_arg(expr
);
2855 for (int i
= first
; i
< n
; ++i
) {
2859 arg
= pet_expr_get_arg(expr
, i
);
2860 mark
= is_sub_access(expr
, arg
, first
);
2863 return pet_expr_free(expr
);
2867 arg
= pet_expr_new_int(isl_val_nan(pet_expr_get_ctx(expr
)));
2868 expr
= pet_expr_set_arg(expr
, i
, arg
);
2874 /* Is "expr" a NaN integer expression?
2876 static int expr_is_nan(__isl_keep pet_expr
*expr
)
2881 if (pet_expr_get_type(expr
) != pet_expr_int
)
2884 v
= pet_expr_int_get_val(expr
);
2885 is_nan
= isl_val_is_nan(v
);
2891 /* Check if we have marked any self dependences (as NaNs)
2892 * in mark_self_dependences and remove them here.
2893 * It is safe to project them out since these arguments
2894 * can at most be referenced from the condition of the access relation,
2895 * but do not appear in the index expression.
2896 * "dim" is the dimension of the iteration domain.
2898 static __isl_give pet_expr
*remove_marked_self_dependences(
2899 __isl_take pet_expr
*expr
, int dim
, int first
)
2903 n
= pet_expr_get_n_arg(expr
);
2904 for (int i
= n
- 1; i
>= first
; --i
) {
2908 arg
= pet_expr_get_arg(expr
, i
);
2909 is_nan
= expr_is_nan(arg
);
2913 expr
= pet_expr_access_project_out_arg(expr
, dim
, i
);
2919 /* Look for parameters in any access relation in "expr" that
2920 * refer to nested accesses. In particular, these are
2921 * parameters with name "__pet_expr".
2923 * If there are any such parameters, then the domain of the index
2924 * expression and the access relation, which is either [] or
2925 * [[] -> [a_1,...,a_m]] at this point, is replaced by [[] -> [t_1,...,t_n]] or
2926 * [[] -> [a_1,...,a_m,t_1,...,t_n]], with m the original number of arguments
2927 * (n_arg) and n the number of these parameters
2928 * (after identifying identical nested accesses).
2930 * This transformation is performed in several steps.
2931 * We first extract the arguments in extract_nested.
2932 * param2pos maps the original parameter position to the position
2933 * of the argument beyond the initial (n_arg) number of arguments.
2934 * Then we move these parameters to input dimensions.
2935 * t2pos maps the positions of these temporary input dimensions
2936 * to the positions of the corresponding arguments.
2937 * Finally, we express these temporary dimensions in terms of the domain
2938 * [[] -> [a_1,...,a_m,t_1,...,t_n]] and precompose index expression and access
2939 * relations with this function.
2941 __isl_give pet_expr
*PetScan::resolve_nested(__isl_take pet_expr
*expr
)
2946 isl_local_space
*ls
;
2949 std::map
<int,int> param2pos
;
2950 std::map
<int,int> t2pos
;
2955 n_arg
= pet_expr_get_n_arg(expr
);
2956 for (int i
= 0; i
< n_arg
; ++i
) {
2958 arg
= pet_expr_get_arg(expr
, i
);
2959 arg
= resolve_nested(arg
);
2960 expr
= pet_expr_set_arg(expr
, i
, arg
);
2963 if (pet_expr_get_type(expr
) != pet_expr_access
)
2966 space
= pet_expr_access_get_parameter_space(expr
);
2967 n
= pet_nested_n_in_space(space
);
2968 isl_space_free(space
);
2972 expr
= extract_nested(expr
, n
, param2pos
);
2976 expr
= pet_expr_access_align_params(expr
);
2977 expr
= mark_self_dependences(expr
, n_arg
);
2982 space
= pet_expr_access_get_parameter_space(expr
);
2983 nparam
= isl_space_dim(space
, isl_dim_param
);
2984 for (int i
= nparam
- 1; i
>= 0; --i
) {
2985 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2986 if (!pet_nested_in_id(id
)) {
2991 expr
= pet_expr_access_move_dims(expr
,
2992 isl_dim_in
, n_arg
+ n
, isl_dim_param
, i
, 1);
2993 t2pos
[n
] = n_arg
+ param2pos
[i
];
2998 isl_space_free(space
);
3000 space
= pet_expr_access_get_parameter_space(expr
);
3001 space
= isl_space_set_from_params(space
);
3002 space
= isl_space_add_dims(space
, isl_dim_set
,
3003 pet_expr_get_n_arg(expr
));
3004 space
= isl_space_wrap(isl_space_from_range(space
));
3005 ls
= isl_local_space_from_space(isl_space_copy(space
));
3006 space
= isl_space_from_domain(space
);
3007 space
= isl_space_add_dims(space
, isl_dim_out
, n_arg
+ n
);
3008 ma
= isl_multi_aff_zero(space
);
3010 for (int i
= 0; i
< n_arg
; ++i
) {
3011 aff
= isl_aff_var_on_domain(isl_local_space_copy(ls
),
3013 ma
= isl_multi_aff_set_aff(ma
, i
, aff
);
3015 for (int i
= 0; i
< n
; ++i
) {
3016 aff
= isl_aff_var_on_domain(isl_local_space_copy(ls
),
3017 isl_dim_set
, t2pos
[i
]);
3018 ma
= isl_multi_aff_set_aff(ma
, n_arg
+ i
, aff
);
3020 isl_local_space_free(ls
);
3022 expr
= pet_expr_access_pullback_multi_aff(expr
, ma
);
3024 expr
= remove_marked_self_dependences(expr
, 0, n_arg
);
3029 /* Return the file offset of the expansion location of "Loc".
3031 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
3033 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
3036 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3038 /* Return a SourceLocation for the location after the first semicolon
3039 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3040 * call it and also skip trailing spaces and newline.
3042 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3043 const LangOptions
&LO
)
3045 return Lexer::findLocationAfterToken(loc
, tok::semi
, SM
, LO
, true);
3050 /* Return a SourceLocation for the location after the first semicolon
3051 * after "loc". If Lexer::findLocationAfterToken is not available,
3052 * we look in the underlying character data for the first semicolon.
3054 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3055 const LangOptions
&LO
)
3058 const char *s
= SM
.getCharacterData(loc
);
3060 semi
= strchr(s
, ';');
3062 return SourceLocation();
3063 return loc
.getFileLocWithOffset(semi
+ 1 - s
);
3068 /* If the token at "loc" is the first token on the line, then return
3069 * a location referring to the start of the line.
3070 * Otherwise, return "loc".
3072 * This function is used to extend a scop to the start of the line
3073 * if the first token of the scop is also the first token on the line.
3075 * We look for the first token on the line. If its location is equal to "loc",
3076 * then the latter is the location of the first token on the line.
3078 static SourceLocation
move_to_start_of_line_if_first_token(SourceLocation loc
,
3079 SourceManager
&SM
, const LangOptions
&LO
)
3081 std::pair
<FileID
, unsigned> file_offset_pair
;
3082 llvm::StringRef file
;
3085 SourceLocation token_loc
, line_loc
;
3088 loc
= SM
.getExpansionLoc(loc
);
3089 col
= SM
.getExpansionColumnNumber(loc
);
3090 line_loc
= loc
.getLocWithOffset(1 - col
);
3091 file_offset_pair
= SM
.getDecomposedLoc(line_loc
);
3092 file
= SM
.getBufferData(file_offset_pair
.first
, NULL
);
3093 pos
= file
.data() + file_offset_pair
.second
;
3095 Lexer
lexer(SM
.getLocForStartOfFile(file_offset_pair
.first
), LO
,
3096 file
.begin(), pos
, file
.end());
3097 lexer
.LexFromRawLexer(tok
);
3098 token_loc
= tok
.getLocation();
3100 if (token_loc
== loc
)
3106 /* If "expr" is an assume expression, then try and convert
3107 * its single argument to an affine expression.
3109 __isl_give pet_expr
*PetScan::resolve_assume(__isl_take pet_expr
*expr
)
3115 if (!pet_expr_is_assume(expr
))
3118 pc
= convert_assignments(ctx
, assigned_value
);
3119 expr
= pet_expr_resolve_assume(expr
, pc
);
3120 pet_context_free(pc
);
3125 /* Update start and end of "scop" to include the region covered by "range".
3126 * If "skip_semi" is set, then we assume "range" is followed by
3127 * a semicolon and also include this semicolon.
3129 struct pet_scop
*PetScan::update_scop_start_end(struct pet_scop
*scop
,
3130 SourceRange range
, bool skip_semi
)
3132 SourceLocation loc
= range
.getBegin();
3133 SourceManager
&SM
= PP
.getSourceManager();
3134 const LangOptions
&LO
= PP
.getLangOpts();
3135 unsigned start
, end
;
3137 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
);
3138 start
= getExpansionOffset(SM
, loc
);
3139 loc
= range
.getEnd();
3141 loc
= location_after_semi(loc
, SM
, LO
);
3143 loc
= PP
.getLocForEndOfToken(loc
);
3144 end
= getExpansionOffset(SM
, loc
);
3146 scop
= pet_scop_update_start_end(scop
, start
, end
);
3150 /* Convert a top-level pet_expr to a pet_scop with one statement.
3151 * This mainly involves resolving nested expression parameters
3152 * and setting the name of the iteration space.
3153 * The name is given by "label" if it is non-NULL. Otherwise,
3154 * it is of the form S_<n_stmt>.
3155 * start and end of the pet_scop are derived from "range" and "skip_semi".
3156 * In particular, if "skip_semi" is set then the semicolon following "range"
3159 struct pet_scop
*PetScan::extract(__isl_take pet_expr
*expr
, SourceRange range
,
3160 bool skip_semi
, __isl_take isl_id
*label
)
3162 struct pet_stmt
*ps
;
3163 struct pet_scop
*scop
;
3164 SourceLocation loc
= range
.getBegin();
3165 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3168 pc
= convert_assignments(ctx
, assigned_value
);
3169 expr
= pet_expr_plug_in_args(expr
, pc
);
3170 pet_context_free(pc
);
3172 expr
= resolve_nested(expr
);
3173 expr
= resolve_assume(expr
);
3174 ps
= pet_stmt_from_pet_expr(line
, label
, n_stmt
++, expr
);
3175 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3177 scop
= update_scop_start_end(scop
, range
, skip_semi
);
3181 /* Check whether "expr" is an affine constraint.
3183 bool PetScan::is_affine_condition(Expr
*expr
)
3187 cond
= extract_condition(expr
);
3188 isl_pw_aff_free(cond
);
3190 return cond
!= NULL
;
3193 /* Check if we can extract a condition from "expr".
3194 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3195 * If allow_nested is set, then the condition may involve parameters
3196 * corresponding to nested accesses.
3197 * We turn on autodetection so that we won't generate any warnings.
3199 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
3202 int save_autodetect
= options
->autodetect
;
3203 bool save_nesting
= nesting_enabled
;
3205 options
->autodetect
= 1;
3206 nesting_enabled
= allow_nested
;
3207 cond
= extract_condition(expr
);
3209 options
->autodetect
= save_autodetect
;
3210 nesting_enabled
= save_nesting
;
3215 /* If the top-level expression of "stmt" is an assignment, then
3216 * return that assignment as a BinaryOperator.
3217 * Otherwise return NULL.
3219 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
3221 BinaryOperator
*ass
;
3225 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
3228 ass
= cast
<BinaryOperator
>(stmt
);
3229 if(ass
->getOpcode() != BO_Assign
)
3235 /* Check if the given if statement is a conditional assignement
3236 * with a non-affine condition. If so, construct a pet_scop
3237 * corresponding to this conditional assignment. Otherwise return NULL.
3239 * In particular we check if "stmt" is of the form
3246 * where a is some array or scalar access.
3247 * The constructed pet_scop then corresponds to the expression
3249 * a = condition ? f(...) : g(...)
3251 * All access relations in f(...) are intersected with condition
3252 * while all access relation in g(...) are intersected with the complement.
3254 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
3256 BinaryOperator
*ass_then
, *ass_else
;
3257 pet_expr
*write_then
, *write_else
;
3258 isl_set
*cond
, *comp
;
3259 isl_multi_pw_aff
*index
;
3263 pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
;
3264 bool save_nesting
= nesting_enabled
;
3266 if (!options
->detect_conditional_assignment
)
3269 ass_then
= top_assignment_or_null(stmt
->getThen());
3270 ass_else
= top_assignment_or_null(stmt
->getElse());
3272 if (!ass_then
|| !ass_else
)
3275 if (is_affine_condition(stmt
->getCond()))
3278 write_then
= extract_access_expr(ass_then
->getLHS());
3279 write_else
= extract_access_expr(ass_else
->getLHS());
3281 equal
= pet_expr_is_equal(write_then
, write_else
);
3282 pet_expr_free(write_else
);
3283 if (equal
< 0 || !equal
) {
3284 pet_expr_free(write_then
);
3288 nesting_enabled
= allow_nested
;
3289 pa
= extract_condition(stmt
->getCond());
3290 nesting_enabled
= save_nesting
;
3291 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
3292 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
3293 index
= isl_multi_pw_aff_from_pw_aff(pa
);
3295 pe_cond
= pet_expr_from_index(index
);
3297 pe_then
= extract_expr(ass_then
->getRHS());
3298 pe_then
= pet_expr_restrict(pe_then
, cond
);
3299 pe_else
= extract_expr(ass_else
->getRHS());
3300 pe_else
= pet_expr_restrict(pe_else
, comp
);
3302 pe
= pet_expr_new_ternary(pe_cond
, pe_then
, pe_else
);
3303 write_then
= pet_expr_access_set_write(write_then
, 1);
3304 write_then
= pet_expr_access_set_read(write_then
, 0);
3305 type_size
= get_type_size(ass_then
->getType(), ast_context
);
3306 pe
= pet_expr_new_binary(type_size
, pet_op_assign
, write_then
, pe
);
3307 return extract(pe
, stmt
->getSourceRange(), false);
3310 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3311 * evaluating "cond" and writing the result to a virtual scalar,
3312 * as expressed by "index".
3314 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
, int stmt_nr
,
3315 __isl_take isl_multi_pw_aff
*index
)
3317 pet_expr
*expr
, *write
;
3318 struct pet_stmt
*ps
;
3319 SourceLocation loc
= cond
->getLocStart();
3320 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3323 write
= pet_expr_from_index(index
);
3324 write
= pet_expr_access_set_write(write
, 1);
3325 write
= pet_expr_access_set_read(write
, 0);
3326 expr
= extract_expr(cond
);
3328 pc
= convert_assignments(ctx
, assigned_value
);
3329 expr
= pet_expr_plug_in_args(expr
, pc
);
3330 pet_context_free(pc
);
3332 expr
= resolve_nested(expr
);
3333 expr
= pet_expr_new_binary(1, pet_op_assign
, write
, expr
);
3334 ps
= pet_stmt_from_pet_expr(line
, NULL
, stmt_nr
, expr
);
3335 return pet_scop_from_pet_stmt(ctx
, ps
);
3339 static __isl_give pet_expr
*embed_access(__isl_take pet_expr
*expr
,
3343 /* Precompose the access relation and the index expression associated
3344 * to "expr" with the function pointed to by "user",
3345 * thereby embedding the access relation in the domain of this function.
3346 * The initial domain of the access relation and the index expression
3347 * is the zero-dimensional domain.
3349 static __isl_give pet_expr
*embed_access(__isl_take pet_expr
*expr
, void *user
)
3351 isl_multi_aff
*ma
= (isl_multi_aff
*) user
;
3353 return pet_expr_access_pullback_multi_aff(expr
, isl_multi_aff_copy(ma
));
3356 /* Precompose all access relations in "expr" with "ma", thereby
3357 * embedding them in the domain of "ma".
3359 static __isl_give pet_expr
*embed(__isl_take pet_expr
*expr
,
3360 __isl_keep isl_multi_aff
*ma
)
3362 return pet_expr_map_access(expr
, &embed_access
, ma
);
3365 /* For each nested access parameter in the domain of "stmt",
3366 * construct a corresponding pet_expr, place it before the original
3367 * elements in stmt->args and record its position in "param2pos".
3368 * n is the number of nested access parameters.
3370 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
3371 std::map
<int,int> ¶m2pos
)
3378 n_arg
= stmt
->n_arg
;
3379 args
= isl_calloc_array(ctx
, pet_expr
*, n
+ n_arg
);
3383 space
= isl_set_get_space(stmt
->domain
);
3384 n_arg
= extract_nested(space
, 0, args
, param2pos
);
3385 isl_space_free(space
);
3390 for (i
= 0; i
< stmt
->n_arg
; ++i
)
3391 args
[n_arg
+ i
] = stmt
->args
[i
];
3394 stmt
->n_arg
+= n_arg
;
3399 for (i
= 0; i
< n
; ++i
)
3400 pet_expr_free(args
[i
]);
3403 pet_stmt_free(stmt
);
3407 /* Check whether any of the arguments i of "stmt" starting at position "n"
3408 * is equal to one of the first "n" arguments j.
3409 * If so, combine the constraints on arguments i and j and remove
3412 static struct pet_stmt
*remove_duplicate_arguments(struct pet_stmt
*stmt
, int n
)
3421 if (n
== stmt
->n_arg
)
3424 map
= isl_set_unwrap(stmt
->domain
);
3426 for (i
= stmt
->n_arg
- 1; i
>= n
; --i
) {
3427 for (j
= 0; j
< n
; ++j
)
3428 if (pet_expr_is_equal(stmt
->args
[i
], stmt
->args
[j
]))
3433 map
= isl_map_equate(map
, isl_dim_out
, i
, isl_dim_out
, j
);
3434 map
= isl_map_project_out(map
, isl_dim_out
, i
, 1);
3436 pet_expr_free(stmt
->args
[i
]);
3437 for (j
= i
; j
+ 1 < stmt
->n_arg
; ++j
)
3438 stmt
->args
[j
] = stmt
->args
[j
+ 1];
3442 stmt
->domain
= isl_map_wrap(map
);
3447 pet_stmt_free(stmt
);
3451 /* Look for parameters in the iteration domain of "stmt" that
3452 * refer to nested accesses. In particular, these are
3453 * parameters with name "__pet_expr".
3455 * If there are any such parameters, then as many extra variables
3456 * (after identifying identical nested accesses) are inserted in the
3457 * range of the map wrapped inside the domain, before the original variables.
3458 * If the original domain is not a wrapped map, then a new wrapped
3459 * map is created with zero output dimensions.
3460 * The parameters are then equated to the corresponding output dimensions
3461 * and subsequently projected out, from the iteration domain,
3462 * the schedule and the access relations.
3463 * For each of the output dimensions, a corresponding argument
3464 * expression is inserted. Initially they are created with
3465 * a zero-dimensional domain, so they have to be embedded
3466 * in the current iteration domain.
3467 * param2pos maps the position of the parameter to the position
3468 * of the corresponding output dimension in the wrapped map.
3470 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3478 std::map
<int,int> param2pos
;
3483 n
= pet_nested_n_in_set(stmt
->domain
);
3487 n_arg
= stmt
->n_arg
;
3488 stmt
= extract_nested(stmt
, n
, param2pos
);
3492 n
= stmt
->n_arg
- n_arg
;
3493 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3494 if (isl_set_is_wrapping(stmt
->domain
))
3495 map
= isl_set_unwrap(stmt
->domain
);
3497 map
= isl_map_from_domain(stmt
->domain
);
3498 map
= isl_map_insert_dims(map
, isl_dim_out
, 0, n
);
3500 for (int i
= nparam
- 1; i
>= 0; --i
) {
3503 if (!pet_nested_in_map(map
, i
))
3506 id
= pet_expr_access_get_id(stmt
->args
[param2pos
[i
]]);
3507 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3508 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3510 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3513 stmt
->domain
= isl_map_wrap(map
);
3515 space
= isl_space_unwrap(isl_set_get_space(stmt
->domain
));
3516 space
= isl_space_from_domain(isl_space_domain(space
));
3517 ma
= isl_multi_aff_zero(space
);
3518 for (int pos
= 0; pos
< n
; ++pos
)
3519 stmt
->args
[pos
] = embed(stmt
->args
[pos
], ma
);
3520 isl_multi_aff_free(ma
);
3522 stmt
= pet_stmt_remove_nested_parameters(stmt
);
3523 stmt
= remove_duplicate_arguments(stmt
, n
);
3528 /* For each statement in "scop", move the parameters that correspond
3529 * to nested access into the ranges of the domains and create
3530 * corresponding argument expressions.
3532 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3537 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3538 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3539 if (!scop
->stmts
[i
])
3545 pet_scop_free(scop
);
3549 /* Given an access expression "expr", is the variable accessed by
3550 * "expr" assigned anywhere inside "scop"?
3552 static bool is_assigned(__isl_keep pet_expr
*expr
, pet_scop
*scop
)
3554 bool assigned
= false;
3557 id
= pet_expr_access_get_id(expr
);
3558 assigned
= pet_scop_writes(scop
, id
);
3564 /* Are all nested access parameters in "pa" allowed given "scop".
3565 * In particular, is none of them written by anywhere inside "scop".
3567 * If "scop" has any skip conditions, then no nested access parameters
3568 * are allowed. In particular, if there is any nested access in a guard
3569 * for a piece of code containing a "continue", then we want to introduce
3570 * a separate statement for evaluating this guard so that we can express
3571 * that the result is false for all previous iterations.
3573 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3580 if (!pet_nested_any_in_pw_aff(pa
))
3583 if (pet_scop_has_skip(scop
, pet_skip_now
))
3586 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3587 for (int i
= 0; i
< nparam
; ++i
) {
3588 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3592 if (!pet_nested_in_id(id
)) {
3597 expr
= pet_nested_extract_expr(id
);
3598 allowed
= pet_expr_get_type(expr
) == pet_expr_access
&&
3599 !is_assigned(expr
, scop
);
3601 pet_expr_free(expr
);
3611 /* Construct a pet_scop for a non-affine if statement.
3613 * We create a separate statement that writes the result
3614 * of the non-affine condition to a virtual scalar.
3615 * A constraint requiring the value of this virtual scalar to be one
3616 * is added to the iteration domains of the then branch.
3617 * Similarly, a constraint requiring the value of this virtual scalar
3618 * to be zero is added to the iteration domains of the else branch, if any.
3619 * We adjust the schedules to ensure that the virtual scalar is written
3620 * before it is read.
3622 * If there are any breaks or continues in the then and/or else
3623 * branches, then we may have to compute a new skip condition.
3624 * This is handled using a pet_skip_info object.
3625 * On initialization, the object checks if skip conditions need
3626 * to be computed. If so, it does so in pet_skip_info_if_extract_index and
3627 * adds them in pet_skip_info_if_add.
3629 struct pet_scop
*PetScan::extract_non_affine_if(Expr
*cond
,
3630 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3631 bool have_else
, int stmt_id
)
3633 struct pet_scop
*scop
;
3634 isl_multi_pw_aff
*test_index
;
3636 int save_n_stmt
= n_stmt
;
3638 test_index
= pet_create_test_index(ctx
, n_test
++);
3640 scop
= extract_non_affine_condition(cond
, n_stmt
++,
3641 isl_multi_pw_aff_copy(test_index
));
3642 n_stmt
= save_n_stmt
;
3643 scop
= scop_add_array(scop
, test_index
, ast_context
);
3646 pet_skip_info_if_init(&skip
, ctx
, scop_then
, scop_else
, have_else
, 0);
3647 int_size
= ast_context
.getTypeInfo(ast_context
.IntTy
).first
/ 8;
3648 pet_skip_info_if_extract_index(&skip
, test_index
, int_size
,
3651 scop
= pet_scop_prefix(scop
, 0);
3652 scop_then
= pet_scop_prefix(scop_then
, 1);
3653 scop_then
= pet_scop_filter(scop_then
,
3654 isl_multi_pw_aff_copy(test_index
), 1);
3656 scop_else
= pet_scop_prefix(scop_else
, 1);
3657 scop_else
= pet_scop_filter(scop_else
, test_index
, 0);
3658 scop_then
= pet_scop_add_par(ctx
, scop_then
, scop_else
);
3660 isl_multi_pw_aff_free(test_index
);
3662 scop
= pet_scop_add_seq(ctx
, scop
, scop_then
);
3664 scop
= pet_skip_info_if_add(&skip
, scop
, 2);
3669 /* Construct a pet_scop for an if statement.
3671 * If the condition fits the pattern of a conditional assignment,
3672 * then it is handled by extract_conditional_assignment.
3673 * Otherwise, we do the following.
3675 * If the condition is affine, then the condition is added
3676 * to the iteration domains of the then branch, while the
3677 * opposite of the condition in added to the iteration domains
3678 * of the else branch, if any.
3679 * We allow the condition to be dynamic, i.e., to refer to
3680 * scalars or array elements that may be written to outside
3681 * of the given if statement. These nested accesses are then represented
3682 * as output dimensions in the wrapping iteration domain.
3683 * If it is also written _inside_ the then or else branch, then
3684 * we treat the condition as non-affine.
3685 * As explained in extract_non_affine_if, this will introduce
3686 * an extra statement.
3687 * For aesthetic reasons, we want this statement to have a statement
3688 * number that is lower than those of the then and else branches.
3689 * In order to evaluate if we will need such a statement, however, we
3690 * first construct scops for the then and else branches.
3691 * We therefore reserve a statement number if we might have to
3692 * introduce such an extra statement.
3694 * If the condition is not affine, then the scop is created in
3695 * extract_non_affine_if.
3697 * If there are any breaks or continues in the then and/or else
3698 * branches, then we may have to compute a new skip condition.
3699 * This is handled using a pet_skip_info object.
3700 * On initialization, the object checks if skip conditions need
3701 * to be computed. If so, it does so in pet_skip_info_if_extract_cond and
3702 * adds them in pet_skip_info_if_add.
3704 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
3706 struct pet_scop
*scop_then
, *scop_else
= NULL
, *scop
;
3713 clear_assignments
clear(assigned_value
);
3714 clear
.TraverseStmt(stmt
->getThen());
3715 if (stmt
->getElse())
3716 clear
.TraverseStmt(stmt
->getElse());
3718 scop
= extract_conditional_assignment(stmt
);
3722 cond
= try_extract_nested_condition(stmt
->getCond());
3723 if (allow_nested
&& (!cond
|| pet_nested_any_in_pw_aff(cond
)))
3727 assigned_value_cache
cache(assigned_value
);
3728 scop_then
= extract(stmt
->getThen());
3731 if (stmt
->getElse()) {
3732 assigned_value_cache
cache(assigned_value
);
3733 scop_else
= extract(stmt
->getElse());
3734 if (options
->autodetect
) {
3735 if (scop_then
&& !scop_else
) {
3737 isl_pw_aff_free(cond
);
3740 if (!scop_then
&& scop_else
) {
3742 isl_pw_aff_free(cond
);
3749 (!is_nested_allowed(cond
, scop_then
) ||
3750 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
3751 isl_pw_aff_free(cond
);
3754 if (allow_nested
&& !cond
)
3755 return extract_non_affine_if(stmt
->getCond(), scop_then
,
3756 scop_else
, stmt
->getElse(), stmt_id
);
3759 cond
= extract_condition(stmt
->getCond());
3762 pet_skip_info_if_init(&skip
, ctx
, scop_then
, scop_else
,
3763 stmt
->getElse() != NULL
, 1);
3764 pet_skip_info_if_extract_cond(&skip
, cond
, int_size
, &n_stmt
, &n_test
);
3766 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
3767 set
= isl_pw_aff_non_zero_set(cond
);
3768 scop
= pet_scop_restrict(scop_then
, isl_set_params(isl_set_copy(set
)));
3770 if (stmt
->getElse()) {
3771 set
= isl_set_subtract(isl_set_copy(valid
), set
);
3772 scop_else
= pet_scop_restrict(scop_else
, isl_set_params(set
));
3773 scop
= pet_scop_add_par(ctx
, scop
, scop_else
);
3776 scop
= resolve_nested(scop
);
3777 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid
));
3779 if (pet_skip_info_has_skip(&skip
))
3780 scop
= pet_scop_prefix(scop
, 0);
3781 scop
= pet_skip_info_if_add(&skip
, scop
, 1);
3786 /* Try and construct a pet_scop for a label statement.
3787 * We currently only allow labels on expression statements.
3789 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
3794 sub
= stmt
->getSubStmt();
3795 if (!isa
<Expr
>(sub
)) {
3800 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
3802 return extract(extract_expr(cast
<Expr
>(sub
)), stmt
->getSourceRange(),
3806 /* Return a one-dimensional multi piecewise affine expression that is equal
3807 * to the constant 1 and is defined over a zero-dimensional domain.
3809 static __isl_give isl_multi_pw_aff
*one_mpa(isl_ctx
*ctx
)
3812 isl_local_space
*ls
;
3815 space
= isl_space_set_alloc(ctx
, 0, 0);
3816 ls
= isl_local_space_from_space(space
);
3817 aff
= isl_aff_zero_on_domain(ls
);
3818 aff
= isl_aff_set_constant_si(aff
, 1);
3820 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
3823 /* Construct a pet_scop for a continue statement.
3825 * We simply create an empty scop with a universal pet_skip_now
3826 * skip condition. This skip condition will then be taken into
3827 * account by the enclosing loop construct, possibly after
3828 * being incorporated into outer skip conditions.
3830 struct pet_scop
*PetScan::extract(ContinueStmt
*stmt
)
3834 scop
= pet_scop_empty(ctx
);
3838 scop
= pet_scop_set_skip(scop
, pet_skip_now
, one_mpa(ctx
));
3843 /* Construct a pet_scop for a break statement.
3845 * We simply create an empty scop with both a universal pet_skip_now
3846 * skip condition and a universal pet_skip_later skip condition.
3847 * These skip conditions will then be taken into
3848 * account by the enclosing loop construct, possibly after
3849 * being incorporated into outer skip conditions.
3851 struct pet_scop
*PetScan::extract(BreakStmt
*stmt
)
3854 isl_multi_pw_aff
*skip
;
3856 scop
= pet_scop_empty(ctx
);
3860 skip
= one_mpa(ctx
);
3861 scop
= pet_scop_set_skip(scop
, pet_skip_now
,
3862 isl_multi_pw_aff_copy(skip
));
3863 scop
= pet_scop_set_skip(scop
, pet_skip_later
, skip
);
3868 /* Try and construct a pet_scop corresponding to "stmt".
3870 * If "stmt" is a compound statement, then "skip_declarations"
3871 * indicates whether we should skip initial declarations in the
3872 * compound statement.
3874 * If the constructed pet_scop is not a (possibly) partial representation
3875 * of "stmt", we update start and end of the pet_scop to those of "stmt".
3876 * In particular, if skip_declarations is set, then we may have skipped
3877 * declarations inside "stmt" and so the pet_scop may not represent
3878 * the entire "stmt".
3879 * Note that this function may be called with "stmt" referring to the entire
3880 * body of the function, including the outer braces. In such cases,
3881 * skip_declarations will be set and the braces will not be taken into
3882 * account in scop->start and scop->end.
3884 struct pet_scop
*PetScan::extract(Stmt
*stmt
, bool skip_declarations
)
3886 struct pet_scop
*scop
;
3888 if (isa
<Expr
>(stmt
))
3889 return extract(extract_expr(cast
<Expr
>(stmt
)),
3890 stmt
->getSourceRange(), true);
3892 switch (stmt
->getStmtClass()) {
3893 case Stmt::WhileStmtClass
:
3894 scop
= extract(cast
<WhileStmt
>(stmt
));
3896 case Stmt::ForStmtClass
:
3897 scop
= extract_for(cast
<ForStmt
>(stmt
));
3899 case Stmt::IfStmtClass
:
3900 scop
= extract(cast
<IfStmt
>(stmt
));
3902 case Stmt::CompoundStmtClass
:
3903 scop
= extract(cast
<CompoundStmt
>(stmt
), skip_declarations
);
3905 case Stmt::LabelStmtClass
:
3906 scop
= extract(cast
<LabelStmt
>(stmt
));
3908 case Stmt::ContinueStmtClass
:
3909 scop
= extract(cast
<ContinueStmt
>(stmt
));
3911 case Stmt::BreakStmtClass
:
3912 scop
= extract(cast
<BreakStmt
>(stmt
));
3914 case Stmt::DeclStmtClass
:
3915 scop
= extract(cast
<DeclStmt
>(stmt
));
3922 if (partial
|| skip_declarations
)
3925 scop
= update_scop_start_end(scop
, stmt
->getSourceRange(), false);
3930 /* Extract a clone of the kill statement in "scop".
3931 * "scop" is expected to have been created from a DeclStmt
3932 * and should have the kill as its first statement.
3934 struct pet_stmt
*PetScan::extract_kill(struct pet_scop
*scop
)
3937 struct pet_stmt
*stmt
;
3938 isl_multi_pw_aff
*index
;
3944 if (scop
->n_stmt
< 1)
3945 isl_die(ctx
, isl_error_internal
,
3946 "expecting at least one statement", return NULL
);
3947 stmt
= scop
->stmts
[0];
3948 if (!pet_stmt_is_kill(stmt
))
3949 isl_die(ctx
, isl_error_internal
,
3950 "expecting kill statement", return NULL
);
3952 arg
= pet_expr_get_arg(stmt
->body
, 0);
3953 index
= pet_expr_access_get_index(arg
);
3954 access
= pet_expr_access_get_access(arg
);
3956 index
= isl_multi_pw_aff_reset_tuple_id(index
, isl_dim_in
);
3957 access
= isl_map_reset_tuple_id(access
, isl_dim_in
);
3958 kill
= pet_expr_kill_from_access_and_index(access
, index
);
3959 return pet_stmt_from_pet_expr(stmt
->line
, NULL
, n_stmt
++, kill
);
3962 /* Mark all arrays in "scop" as being exposed.
3964 static struct pet_scop
*mark_exposed(struct pet_scop
*scop
)
3968 for (int i
= 0; i
< scop
->n_array
; ++i
)
3969 scop
->arrays
[i
]->exposed
= 1;
3973 /* Try and construct a pet_scop corresponding to (part of)
3974 * a sequence of statements.
3976 * "block" is set if the sequence respresents the children of
3977 * a compound statement.
3978 * "skip_declarations" is set if we should skip initial declarations
3979 * in the sequence of statements.
3981 * After extracting a statement, we update "assigned_value"
3982 * based on the top-level assignments in the statement
3983 * so that we can exploit them in subsequent statements in the same block.
3985 * If there are any breaks or continues in the individual statements,
3986 * then we may have to compute a new skip condition.
3987 * This is handled using a pet_skip_info object.
3988 * On initialization, the object checks if skip conditions need
3989 * to be computed. If so, it does so in pet_skip_info_seq_extract and
3990 * adds them in pet_skip_info_seq_add.
3992 * If "block" is set, then we need to insert kill statements at
3993 * the end of the block for any array that has been declared by
3994 * one of the statements in the sequence. Each of these declarations
3995 * results in the construction of a kill statement at the place
3996 * of the declaration, so we simply collect duplicates of
3997 * those kill statements and append these duplicates to the constructed scop.
3999 * If "block" is not set, then any array declared by one of the statements
4000 * in the sequence is marked as being exposed.
4002 * If autodetect is set, then we allow the extraction of only a subrange
4003 * of the sequence of statements. However, if there is at least one statement
4004 * for which we could not construct a scop and the final range contains
4005 * either no statements or at least one kill, then we discard the entire
4008 struct pet_scop
*PetScan::extract(StmtRange stmt_range
, bool block
,
4009 bool skip_declarations
)
4015 bool partial_range
= false;
4016 set
<struct pet_stmt
*> kills
;
4017 set
<struct pet_stmt
*>::iterator it
;
4019 int_size
= ast_context
.getTypeInfo(ast_context
.IntTy
).first
/ 8;
4021 scop
= pet_scop_empty(ctx
);
4022 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
4024 struct pet_scop
*scop_i
;
4026 if (scop
->n_stmt
== 0 && skip_declarations
&&
4027 child
->getStmtClass() == Stmt::DeclStmtClass
)
4030 scop_i
= extract(child
);
4031 if (scop
->n_stmt
!= 0 && partial
) {
4032 pet_scop_free(scop_i
);
4035 handle_writes(scop_i
);
4037 pet_skip_info_seq_init(&skip
, ctx
, scop
, scop_i
);
4038 pet_skip_info_seq_extract(&skip
, int_size
, &n_stmt
, &n_test
);
4039 if (pet_skip_info_has_skip(&skip
))
4040 scop_i
= pet_scop_prefix(scop_i
, 0);
4041 if (scop_i
&& child
->getStmtClass() == Stmt::DeclStmtClass
) {
4043 kills
.insert(extract_kill(scop_i
));
4045 scop_i
= mark_exposed(scop_i
);
4047 scop_i
= pet_scop_prefix(scop_i
, j
);
4048 if (options
->autodetect
) {
4050 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4052 partial_range
= true;
4053 if (scop
->n_stmt
!= 0 && !scop_i
)
4056 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4059 scop
= pet_skip_info_seq_add(&skip
, scop
, j
);
4061 if (partial
|| !scop
)
4065 for (it
= kills
.begin(); it
!= kills
.end(); ++it
) {
4067 scop_j
= pet_scop_from_pet_stmt(ctx
, *it
);
4068 scop_j
= pet_scop_prefix(scop_j
, j
);
4069 scop
= pet_scop_add_seq(ctx
, scop
, scop_j
);
4072 if (scop
&& partial_range
) {
4073 if (scop
->n_stmt
== 0 || kills
.size() != 0) {
4074 pet_scop_free(scop
);
4083 /* Check if the scop marked by the user is exactly this Stmt
4084 * or part of this Stmt.
4085 * If so, return a pet_scop corresponding to the marked region.
4086 * Otherwise, return NULL.
4088 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
4090 SourceManager
&SM
= PP
.getSourceManager();
4091 unsigned start_off
, end_off
;
4093 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
4094 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
4096 if (start_off
> loc
.end
)
4098 if (end_off
< loc
.start
)
4100 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
4101 return extract(stmt
);
4105 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
4106 Stmt
*child
= *start
;
4109 start_off
= getExpansionOffset(SM
, child
->getLocStart());
4110 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
4111 if (start_off
< loc
.start
&& end_off
>= loc
.end
)
4113 if (start_off
>= loc
.start
)
4118 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
4120 start_off
= SM
.getFileOffset(child
->getLocStart());
4121 if (start_off
>= loc
.end
)
4125 return extract(StmtRange(start
, end
), false, false);
4128 /* Set the size of index "pos" of "array" to "size".
4129 * In particular, add a constraint of the form
4133 * to array->extent and a constraint of the form
4137 * to array->context.
4139 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
4140 __isl_take isl_pw_aff
*size
)
4153 valid
= isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
)));
4154 array
->context
= isl_set_intersect(array
->context
, valid
);
4156 dim
= isl_set_get_space(array
->extent
);
4157 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
4158 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
4159 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
4160 index
= isl_pw_aff_alloc(univ
, aff
);
4162 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
4163 isl_set_dim(array
->extent
, isl_dim_set
));
4164 id
= isl_set_get_tuple_id(array
->extent
);
4165 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
4166 bound
= isl_pw_aff_lt_set(index
, size
);
4168 array
->extent
= isl_set_intersect(array
->extent
, bound
);
4170 if (!array
->context
|| !array
->extent
)
4171 return pet_array_free(array
);
4175 isl_pw_aff_free(size
);
4179 /* Figure out the size of the array at position "pos" and all
4180 * subsequent positions from "type" and update the corresponding
4181 * argument of "expr" accordingly.
4183 __isl_give pet_expr
*PetScan::set_upper_bounds(__isl_take pet_expr
*expr
,
4184 const Type
*type
, int pos
)
4186 const ArrayType
*atype
;
4192 if (type
->isPointerType()) {
4193 type
= type
->getPointeeType().getTypePtr();
4194 return set_upper_bounds(expr
, type
, pos
+ 1);
4196 if (!type
->isArrayType())
4199 type
= type
->getCanonicalTypeInternal().getTypePtr();
4200 atype
= cast
<ArrayType
>(type
);
4202 if (type
->isConstantArrayType()) {
4203 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
4204 size
= extract_expr(ca
->getSize());
4205 expr
= pet_expr_set_arg(expr
, pos
, size
);
4206 } else if (type
->isVariableArrayType()) {
4207 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
4208 size
= extract_expr(vla
->getSizeExpr());
4209 expr
= pet_expr_set_arg(expr
, pos
, size
);
4212 type
= atype
->getElementType().getTypePtr();
4214 return set_upper_bounds(expr
, type
, pos
+ 1);
4217 /* Does "expr" represent the "integer" infinity?
4219 static int is_infty(__isl_keep pet_expr
*expr
)
4224 if (pet_expr_get_type(expr
) != pet_expr_int
)
4226 v
= pet_expr_int_get_val(expr
);
4227 res
= isl_val_is_infty(v
);
4233 /* Figure out the dimensions of an array "array" based on its type
4234 * "type" and update "array" accordingly.
4236 * We first construct a pet_expr that holds the sizes of the array
4237 * in each dimension. The expression is initialized to infinity
4238 * and updated from the type.
4240 * The arguments of the size expression that have been updated
4241 * are then converted to an affine expression and incorporated
4242 * into the size of "array". If we are unable to convert
4243 * a size expression to an affine expression, then we leave
4244 * the corresponding size of "array" untouched.
4246 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
4249 int depth
= array_depth(type
);
4250 pet_expr
*expr
, *inf
;
4256 inf
= pet_expr_new_int(isl_val_infty(ctx
));
4257 expr
= pet_expr_new_call(ctx
, "bounds", depth
);
4258 for (int i
= 0; i
< depth
; ++i
)
4259 expr
= pet_expr_set_arg(expr
, i
, pet_expr_copy(inf
));
4262 expr
= set_upper_bounds(expr
, type
, 0);
4264 pc
= convert_assignments(ctx
, assigned_value
);
4265 for (int i
= 0; i
< depth
; ++i
) {
4269 arg
= pet_expr_get_arg(expr
, i
);
4270 if (!is_infty(arg
)) {
4271 size
= pet_expr_extract_affine(arg
, pc
);
4273 array
= pet_array_free(array
);
4274 else if (isl_pw_aff_involves_nan(size
))
4275 isl_pw_aff_free(size
);
4277 array
= update_size(array
, i
, size
);
4281 pet_expr_free(expr
);
4282 pet_context_free(pc
);
4287 /* Is "T" the type of a variable length array with static size?
4289 static bool is_vla_with_static_size(QualType T
)
4291 const VariableArrayType
*vlatype
;
4293 if (!T
->isVariableArrayType())
4295 vlatype
= cast
<VariableArrayType
>(T
);
4296 return vlatype
->getSizeModifier() == VariableArrayType::Static
;
4299 /* Return the type of "decl" as an array.
4301 * In particular, if "decl" is a parameter declaration that
4302 * is a variable length array with a static size, then
4303 * return the original type (i.e., the variable length array).
4304 * Otherwise, return the type of decl.
4306 static QualType
get_array_type(ValueDecl
*decl
)
4311 parm
= dyn_cast
<ParmVarDecl
>(decl
);
4313 return decl
->getType();
4315 T
= parm
->getOriginalType();
4316 if (!is_vla_with_static_size(T
))
4317 return decl
->getType();
4321 /* Does "decl" have definition that we can keep track of in a pet_type?
4323 static bool has_printable_definition(RecordDecl
*decl
)
4325 if (!decl
->getDeclName())
4327 return decl
->getLexicalDeclContext() == decl
->getDeclContext();
4330 /* Construct and return a pet_array corresponding to the variable "decl".
4331 * In particular, initialize array->extent to
4333 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4335 * and then call set_upper_bounds to set the upper bounds on the indices
4336 * based on the type of the variable.
4338 * If the base type is that of a record with a top-level definition and
4339 * if "types" is not null, then the RecordDecl corresponding to the type
4340 * is added to "types".
4342 * If the base type is that of a record with no top-level definition,
4343 * then we replace it by "<subfield>".
4345 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
,
4346 lex_recorddecl_set
*types
)
4348 struct pet_array
*array
;
4349 QualType qt
= get_array_type(decl
);
4350 const Type
*type
= qt
.getTypePtr();
4351 int depth
= array_depth(type
);
4352 QualType base
= pet_clang_base_type(qt
);
4357 array
= isl_calloc_type(ctx
, struct pet_array
);
4361 id
= create_decl_id(ctx
, decl
);
4362 dim
= isl_space_set_alloc(ctx
, 0, depth
);
4363 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
4365 array
->extent
= isl_set_nat_universe(dim
);
4367 dim
= isl_space_params_alloc(ctx
, 0);
4368 array
->context
= isl_set_universe(dim
);
4370 array
= set_upper_bounds(array
, type
);
4374 name
= base
.getAsString();
4376 if (types
&& base
->isRecordType()) {
4377 RecordDecl
*decl
= pet_clang_record_decl(base
);
4378 if (has_printable_definition(decl
))
4379 types
->insert(decl
);
4381 name
= "<subfield>";
4384 array
->element_type
= strdup(name
.c_str());
4385 array
->element_is_record
= base
->isRecordType();
4386 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
4391 /* Construct and return a pet_array corresponding to the sequence
4392 * of declarations "decls".
4393 * If the sequence contains a single declaration, then it corresponds
4394 * to a simple array access. Otherwise, it corresponds to a member access,
4395 * with the declaration for the substructure following that of the containing
4396 * structure in the sequence of declarations.
4397 * We start with the outermost substructure and then combine it with
4398 * information from the inner structures.
4400 * Additionally, keep track of all required types in "types".
4402 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
,
4403 vector
<ValueDecl
*> decls
, lex_recorddecl_set
*types
)
4405 struct pet_array
*array
;
4406 vector
<ValueDecl
*>::iterator it
;
4410 array
= extract_array(ctx
, *it
, types
);
4412 for (++it
; it
!= decls
.end(); ++it
) {
4413 struct pet_array
*parent
;
4414 const char *base_name
, *field_name
;
4418 array
= extract_array(ctx
, *it
, types
);
4420 return pet_array_free(parent
);
4422 base_name
= isl_set_get_tuple_name(parent
->extent
);
4423 field_name
= isl_set_get_tuple_name(array
->extent
);
4424 product_name
= pet_array_member_access_name(ctx
,
4425 base_name
, field_name
);
4427 array
->extent
= isl_set_product(isl_set_copy(parent
->extent
),
4430 array
->extent
= isl_set_set_tuple_name(array
->extent
,
4432 array
->context
= isl_set_intersect(array
->context
,
4433 isl_set_copy(parent
->context
));
4435 pet_array_free(parent
);
4438 if (!array
->extent
|| !array
->context
|| !product_name
)
4439 return pet_array_free(array
);
4445 /* Add a pet_type corresponding to "decl" to "scop, provided
4446 * it is a member of "types" and it has not been added before
4447 * (i.e., it is not a member of "types_done".
4449 * Since we want the user to be able to print the types
4450 * in the order in which they appear in the scop, we need to
4451 * make sure that types of fields in a structure appear before
4452 * that structure. We therefore call ourselves recursively
4453 * on the types of all record subfields.
4455 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
4456 RecordDecl
*decl
, Preprocessor
&PP
, lex_recorddecl_set
&types
,
4457 lex_recorddecl_set
&types_done
)
4460 llvm::raw_string_ostream
S(s
);
4461 RecordDecl::field_iterator it
;
4463 if (types
.find(decl
) == types
.end())
4465 if (types_done
.find(decl
) != types_done
.end())
4468 for (it
= decl
->field_begin(); it
!= decl
->field_end(); ++it
) {
4470 QualType type
= it
->getType();
4472 if (!type
->isRecordType())
4474 record
= pet_clang_record_decl(type
);
4475 scop
= add_type(ctx
, scop
, record
, PP
, types
, types_done
);
4478 if (strlen(decl
->getName().str().c_str()) == 0)
4481 decl
->print(S
, PrintingPolicy(PP
.getLangOpts()));
4484 scop
->types
[scop
->n_type
] = pet_type_alloc(ctx
,
4485 decl
->getName().str().c_str(), s
.c_str());
4486 if (!scop
->types
[scop
->n_type
])
4487 return pet_scop_free(scop
);
4489 types_done
.insert(decl
);
4496 /* Construct a list of pet_arrays, one for each array (or scalar)
4497 * accessed inside "scop", add this list to "scop" and return the result.
4499 * The context of "scop" is updated with the intersection of
4500 * the contexts of all arrays, i.e., constraints on the parameters
4501 * that ensure that the arrays have a valid (non-negative) size.
4503 * If the any of the extracted arrays refers to a member access,
4504 * then also add the required types to "scop".
4506 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
4509 array_desc_set arrays
;
4510 array_desc_set::iterator it
;
4511 lex_recorddecl_set types
;
4512 lex_recorddecl_set types_done
;
4513 lex_recorddecl_set::iterator types_it
;
4515 struct pet_array
**scop_arrays
;
4520 pet_scop_collect_arrays(scop
, arrays
);
4521 if (arrays
.size() == 0)
4524 n_array
= scop
->n_array
;
4526 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
4527 n_array
+ arrays
.size());
4530 scop
->arrays
= scop_arrays
;
4532 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
4533 struct pet_array
*array
;
4534 array
= extract_array(ctx
, *it
, &types
);
4535 scop
->arrays
[n_array
+ i
] = array
;
4536 if (!scop
->arrays
[n_array
+ i
])
4539 scop
->context
= isl_set_intersect(scop
->context
,
4540 isl_set_copy(array
->context
));
4545 if (types
.size() == 0)
4548 scop
->types
= isl_alloc_array(ctx
, struct pet_type
*, types
.size());
4552 for (types_it
= types
.begin(); types_it
!= types
.end(); ++types_it
)
4553 scop
= add_type(ctx
, scop
, *types_it
, PP
, types
, types_done
);
4557 pet_scop_free(scop
);
4561 /* Bound all parameters in scop->context to the possible values
4562 * of the corresponding C variable.
4564 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
4571 n
= isl_set_dim(scop
->context
, isl_dim_param
);
4572 for (int i
= 0; i
< n
; ++i
) {
4576 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
4577 if (pet_nested_in_id(id
)) {
4579 isl_die(isl_set_get_ctx(scop
->context
),
4581 "unresolved nested parameter", goto error
);
4583 decl
= (ValueDecl
*) isl_id_get_user(id
);
4586 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
4594 pet_scop_free(scop
);
4598 /* Construct a pet_scop from the given function.
4600 * If the scop was delimited by scop and endscop pragmas, then we override
4601 * the file offsets by those derived from the pragmas.
4603 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
4608 stmt
= fd
->getBody();
4610 if (options
->autodetect
)
4611 scop
= extract(stmt
, true);
4614 scop
= pet_scop_update_start_end(scop
, loc
.start
, loc
.end
);
4616 scop
= pet_scop_detect_parameter_accesses(scop
);
4617 scop
= scan_arrays(scop
);
4618 scop
= add_parameter_bounds(scop
);
4619 scop
= pet_scop_gist(scop
, value_bounds
);