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>
59 #include "scop_plus.h"
65 using namespace clang
;
67 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
77 return pet_op_post_inc
;
79 return pet_op_post_dec
;
81 return pet_op_pre_inc
;
83 return pet_op_pre_dec
;
89 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
93 return pet_op_add_assign
;
95 return pet_op_sub_assign
;
97 return pet_op_mul_assign
;
99 return pet_op_div_assign
;
101 return pet_op_assign
;
143 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
144 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
146 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
147 SourceLocation(), var
, false, var
->getInnerLocStart(),
148 var
->getType(), VK_LValue
);
150 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
151 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
153 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
154 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
158 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
160 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
161 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
165 /* Check if the element type corresponding to the given array type
166 * has a const qualifier.
168 static bool const_base(QualType qt
)
170 const Type
*type
= qt
.getTypePtr();
172 if (type
->isPointerType())
173 return const_base(type
->getPointeeType());
174 if (type
->isArrayType()) {
175 const ArrayType
*atype
;
176 type
= type
->getCanonicalTypeInternal().getTypePtr();
177 atype
= cast
<ArrayType
>(type
);
178 return const_base(atype
->getElementType());
181 return qt
.isConstQualified();
184 /* Create an isl_id that refers to the named declarator "decl".
186 static __isl_give isl_id
*create_decl_id(isl_ctx
*ctx
, NamedDecl
*decl
)
188 return isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
191 /* Mark "decl" as having an unknown value in "assigned_value".
193 * If no (known or unknown) value was assigned to "decl" before,
194 * then it may have been treated as a parameter before and may
195 * therefore appear in a value assigned to another variable.
196 * If so, this assignment needs to be turned into an unknown value too.
198 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
201 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
203 it
= assigned_value
.find(decl
);
205 assigned_value
[decl
] = NULL
;
207 if (it
!= assigned_value
.end())
210 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
211 isl_pw_aff
*pa
= it
->second
;
212 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
214 for (int i
= 0; i
< nparam
; ++i
) {
217 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
219 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
220 if (isl_id_get_user(id
) == decl
)
227 /* Look for any assignments to scalar variables in part of the parse
228 * tree and set assigned_value to NULL for each of them.
229 * Also reset assigned_value if the address of a scalar variable
230 * is being taken. As an exception, if the address is passed to a function
231 * that is declared to receive a const pointer, then assigned_value is
234 * This ensures that we won't use any previously stored value
235 * in the current subtree and its parents.
237 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
238 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
239 set
<UnaryOperator
*> skip
;
241 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
242 assigned_value(assigned_value
) {}
244 /* Check for "address of" operators whose value is passed
245 * to a const pointer argument and add them to "skip", so that
246 * we can skip them in VisitUnaryOperator.
248 bool VisitCallExpr(CallExpr
*expr
) {
250 fd
= expr
->getDirectCallee();
253 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
254 Expr
*arg
= expr
->getArg(i
);
256 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
257 ImplicitCastExpr
*ice
;
258 ice
= cast
<ImplicitCastExpr
>(arg
);
259 arg
= ice
->getSubExpr();
261 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
263 op
= cast
<UnaryOperator
>(arg
);
264 if (op
->getOpcode() != UO_AddrOf
)
266 if (const_base(fd
->getParamDecl(i
)->getType()))
272 bool VisitUnaryOperator(UnaryOperator
*expr
) {
277 switch (expr
->getOpcode()) {
287 if (skip
.find(expr
) != skip
.end())
290 arg
= expr
->getSubExpr();
291 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
293 ref
= cast
<DeclRefExpr
>(arg
);
294 decl
= ref
->getDecl();
295 clear_assignment(assigned_value
, decl
);
299 bool VisitBinaryOperator(BinaryOperator
*expr
) {
304 if (!expr
->isAssignmentOp())
306 lhs
= expr
->getLHS();
307 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
309 ref
= cast
<DeclRefExpr
>(lhs
);
310 decl
= ref
->getDecl();
311 clear_assignment(assigned_value
, decl
);
316 /* Keep a copy of the currently assigned values.
318 * Any variable that is assigned a value inside the current scope
319 * is removed again when we leave the scope (either because it wasn't
320 * stored in the cache or because it has a different value in the cache).
322 struct assigned_value_cache
{
323 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
324 map
<ValueDecl
*, isl_pw_aff
*> cache
;
326 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
327 assigned_value(assigned_value
), cache(assigned_value
) {}
328 ~assigned_value_cache() {
329 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
330 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
333 (cache
.find(it
->first
) != cache
.end() &&
334 cache
[it
->first
] != it
->second
))
335 cache
[it
->first
] = NULL
;
337 assigned_value
= cache
;
341 /* Convert the mapping from identifiers to values in "assigned_value"
342 * to a pet_context to be used by pet_expr_extract_*.
343 * In particular, the clang identifiers are wrapped in an isl_id and
344 * a NULL value (representing an unknown value) is replaced by a NaN.
346 static __isl_give pet_context
*convert_assignments(isl_ctx
*ctx
,
347 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
)
350 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
352 pc
= pet_context_alloc(isl_space_set_alloc(ctx
, 0, 0));
354 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
355 ValueDecl
*decl
= it
->first
;
356 isl_pw_aff
*pa
= it
->second
;
359 id
= create_decl_id(ctx
, decl
);
361 pc
= pet_context_set_value(pc
, id
, isl_pw_aff_copy(pa
));
363 pc
= pet_context_mark_unknown(pc
, id
);
369 /* Insert an expression into the collection of expressions,
370 * provided it is not already in there.
371 * The isl_pw_affs are freed in the destructor.
373 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
375 std::set
<isl_pw_aff
*>::iterator it
;
377 if (expressions
.find(expr
) == expressions
.end())
378 expressions
.insert(expr
);
380 isl_pw_aff_free(expr
);
385 std::set
<isl_pw_aff
*>::iterator it
;
387 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
388 isl_pw_aff_free(*it
);
390 isl_union_map_free(value_bounds
);
393 /* Report a diagnostic, unless autodetect is set.
395 void PetScan::report(Stmt
*stmt
, unsigned id
)
397 if (options
->autodetect
)
400 SourceLocation loc
= stmt
->getLocStart();
401 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
402 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
405 /* Called if we found something we (currently) cannot handle.
406 * We'll provide more informative warnings later.
408 * We only actually complain if autodetect is false.
410 void PetScan::unsupported(Stmt
*stmt
)
412 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
413 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
418 /* Report a missing prototype, unless autodetect is set.
420 void PetScan::report_prototype_required(Stmt
*stmt
)
422 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
423 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
424 "prototype required");
428 /* Report a missing increment, unless autodetect is set.
430 void PetScan::report_missing_increment(Stmt
*stmt
)
432 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
433 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
434 "missing increment");
438 /* Extract an integer from "expr".
440 __isl_give isl_val
*PetScan::extract_int(isl_ctx
*ctx
, IntegerLiteral
*expr
)
442 const Type
*type
= expr
->getType().getTypePtr();
443 int is_signed
= type
->hasSignedIntegerRepresentation();
444 llvm::APInt val
= expr
->getValue();
445 int is_negative
= is_signed
&& val
.isNegative();
451 v
= extract_unsigned(ctx
, val
);
458 /* Extract an integer from "val", which is assumed to be non-negative.
460 __isl_give isl_val
*PetScan::extract_unsigned(isl_ctx
*ctx
,
461 const llvm::APInt
&val
)
464 const uint64_t *data
;
466 data
= val
.getRawData();
467 n
= val
.getNumWords();
468 return isl_val_int_from_chunks(ctx
, n
, sizeof(uint64_t), data
);
471 /* Extract an integer from "expr".
472 * Return NULL if "expr" does not (obviously) represent an integer.
474 __isl_give isl_val
*PetScan::extract_int(clang::ParenExpr
*expr
)
476 return extract_int(expr
->getSubExpr());
479 /* Extract an integer from "expr".
480 * Return NULL if "expr" does not (obviously) represent an integer.
482 __isl_give isl_val
*PetScan::extract_int(clang::Expr
*expr
)
484 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
485 return extract_int(ctx
, cast
<IntegerLiteral
>(expr
));
486 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
487 return extract_int(cast
<ParenExpr
>(expr
));
493 /* Extract an affine expression from the APInt "val", which is assumed
494 * to be non-negative.
495 * If the value of "val" is "v", then the returned expression
500 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
502 isl_space
*space
= isl_space_set_alloc(ctx
, 0, 0);
503 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(space
));
504 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
505 isl_set
*dom
= isl_set_universe(space
);
508 v
= extract_unsigned(ctx
, val
);
509 aff
= isl_aff_add_constant_val(aff
, v
);
511 return isl_pw_aff_alloc(dom
, aff
);
514 /* Return the number of bits needed to represent the type "qt",
515 * if it is an integer type. Otherwise return 0.
516 * If qt is signed then return the opposite of the number of bits.
518 static int get_type_size(QualType qt
, ASTContext
&ast_context
)
522 if (!qt
->isIntegerType())
525 size
= ast_context
.getIntWidth(qt
);
526 if (!qt
->isUnsignedIntegerType())
532 /* Return the number of bits needed to represent the type of "decl",
533 * if it is an integer type. Otherwise return 0.
534 * If qt is signed then return the opposite of the number of bits.
536 static int get_type_size(ValueDecl
*decl
)
538 return get_type_size(decl
->getType(), decl
->getASTContext());
541 /* Bound parameter "pos" of "set" to the possible values of "decl".
543 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
544 unsigned pos
, ValueDecl
*decl
)
550 ctx
= isl_set_get_ctx(set
);
551 type_size
= get_type_size(decl
);
553 isl_die(ctx
, isl_error_invalid
, "not an integer type",
554 return isl_set_free(set
));
556 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
557 bound
= isl_val_int_from_ui(ctx
, type_size
);
558 bound
= isl_val_2exp(bound
);
559 bound
= isl_val_sub_ui(bound
, 1);
560 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
, bound
);
562 bound
= isl_val_int_from_ui(ctx
, -type_size
- 1);
563 bound
= isl_val_2exp(bound
);
564 bound
= isl_val_sub_ui(bound
, 1);
565 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
,
566 isl_val_copy(bound
));
567 bound
= isl_val_neg(bound
);
568 bound
= isl_val_sub_ui(bound
, 1);
569 set
= isl_set_lower_bound_val(set
, isl_dim_param
, pos
, bound
);
575 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
577 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
578 __isl_take isl_set
*dom
)
581 pa
= isl_set_indicator_function(set
);
582 pa
= isl_pw_aff_intersect_domain(pa
, isl_set_coalesce(dom
));
586 /* Extract an affine expression, if possible, from "expr".
587 * Otherwise return NULL.
589 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
595 pe
= extract_expr(expr
);
598 pc
= convert_assignments(ctx
, assigned_value
);
599 pc
= pet_context_set_allow_nested(pc
, nesting_enabled
);
600 pa
= pet_expr_extract_affine(pe
, pc
);
601 if (isl_pw_aff_involves_nan(pa
)) {
603 pa
= isl_pw_aff_free(pa
);
605 pet_context_free(pc
);
611 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ImplicitCastExpr
*expr
)
613 return extract_index(expr
->getSubExpr());
616 /* Return the depth of an array of the given type.
618 static int array_depth(const Type
*type
)
620 if (type
->isPointerType())
621 return 1 + array_depth(type
->getPointeeType().getTypePtr());
622 if (type
->isArrayType()) {
623 const ArrayType
*atype
;
624 type
= type
->getCanonicalTypeInternal().getTypePtr();
625 atype
= cast
<ArrayType
>(type
);
626 return 1 + array_depth(atype
->getElementType().getTypePtr());
631 /* Return the depth of the array accessed by the index expression "index".
632 * If "index" is an affine expression, i.e., if it does not access
633 * any array, then return 1.
634 * If "index" represent a member access, i.e., if its range is a wrapped
635 * relation, then return the sum of the depth of the array of structures
636 * and that of the member inside the structure.
638 static int extract_depth(__isl_keep isl_multi_pw_aff
*index
)
646 if (isl_multi_pw_aff_range_is_wrapping(index
)) {
647 int domain_depth
, range_depth
;
648 isl_multi_pw_aff
*domain
, *range
;
650 domain
= isl_multi_pw_aff_copy(index
);
651 domain
= isl_multi_pw_aff_range_factor_domain(domain
);
652 domain_depth
= extract_depth(domain
);
653 isl_multi_pw_aff_free(domain
);
654 range
= isl_multi_pw_aff_copy(index
);
655 range
= isl_multi_pw_aff_range_factor_range(range
);
656 range_depth
= extract_depth(range
);
657 isl_multi_pw_aff_free(range
);
659 return domain_depth
+ range_depth
;
662 if (!isl_multi_pw_aff_has_tuple_id(index
, isl_dim_out
))
665 id
= isl_multi_pw_aff_get_tuple_id(index
, isl_dim_out
);
668 decl
= (ValueDecl
*) isl_id_get_user(id
);
671 return array_depth(decl
->getType().getTypePtr());
674 /* Extract an index expression from a reference to a variable.
675 * If the variable has name "A", then the returned index expression
680 __isl_give isl_multi_pw_aff
*PetScan::extract_index(DeclRefExpr
*expr
)
682 return extract_index(expr
->getDecl());
685 /* Extract an index expression from a variable.
686 * If the variable has name "A", then the returned index expression
691 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ValueDecl
*decl
)
693 isl_id
*id
= create_decl_id(ctx
, decl
);
694 isl_space
*space
= isl_space_alloc(ctx
, 0, 0, 0);
696 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
698 return isl_multi_pw_aff_zero(space
);
701 /* Extract an index expression from an integer contant.
702 * If the value of the constant is "v", then the returned access relation
707 __isl_give isl_multi_pw_aff
*PetScan::extract_index(IntegerLiteral
*expr
)
709 isl_multi_pw_aff
*mpa
;
711 mpa
= isl_multi_pw_aff_from_pw_aff(extract_affine(expr
));
715 /* Try and extract an index expression from the given Expr.
716 * Return NULL if it doesn't work out.
718 __isl_give isl_multi_pw_aff
*PetScan::extract_index(Expr
*expr
)
720 switch (expr
->getStmtClass()) {
721 case Stmt::ImplicitCastExprClass
:
722 return extract_index(cast
<ImplicitCastExpr
>(expr
));
723 case Stmt::DeclRefExprClass
:
724 return extract_index(cast
<DeclRefExpr
>(expr
));
725 case Stmt::ArraySubscriptExprClass
:
726 return extract_index(cast
<ArraySubscriptExpr
>(expr
));
727 case Stmt::IntegerLiteralClass
:
728 return extract_index(cast
<IntegerLiteral
>(expr
));
729 case Stmt::MemberExprClass
:
730 return extract_index(cast
<MemberExpr
>(expr
));
737 /* Extract an index expression from the given array subscript expression.
738 * If nesting is allowed in general, then we turn it on while
739 * examining the index expression.
741 * We first extract an index expression from the base.
742 * This will result in an index expression with a range that corresponds
743 * to the earlier indices.
744 * We then extract the current index, restrict its domain
745 * to those values that result in a non-negative index and
746 * append the index to the base index expression.
748 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ArraySubscriptExpr
*expr
)
750 Expr
*base
= expr
->getBase();
751 Expr
*idx
= expr
->getIdx();
753 isl_multi_pw_aff
*base_access
;
754 isl_multi_pw_aff
*access
;
755 bool save_nesting
= nesting_enabled
;
757 nesting_enabled
= allow_nested
;
759 base_access
= extract_index(base
);
760 index
= extract_affine(idx
);
762 nesting_enabled
= save_nesting
;
764 access
= pet_array_subscript(base_access
, index
);
769 /* Extract an index expression from a member expression.
771 * If the base access (to the structure containing the member)
776 * and the member is called "f", then the member access is of
779 * [] -> A_f[A[..] -> f[]]
781 * If the member access is to an anonymous struct, then simply return
785 * If the member access in the source code is of the form
789 * then it is treated as
793 __isl_give isl_multi_pw_aff
*PetScan::extract_index(MemberExpr
*expr
)
795 Expr
*base
= expr
->getBase();
796 FieldDecl
*field
= cast
<FieldDecl
>(expr
->getMemberDecl());
797 isl_multi_pw_aff
*base_access
, *field_access
;
801 base_access
= extract_index(base
);
803 if (expr
->isArrow()) {
804 isl_space
*space
= isl_space_set_alloc(ctx
, 0, 0);
805 isl_local_space
*ls
= isl_local_space_from_space(space
);
806 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
807 isl_pw_aff
*index
= isl_pw_aff_from_aff(aff
);
808 base_access
= pet_array_subscript(base_access
, index
);
811 if (field
->isAnonymousStructOrUnion())
814 id
= create_decl_id(ctx
, field
);
815 space
= isl_multi_pw_aff_get_domain_space(base_access
);
816 space
= isl_space_from_domain(space
);
817 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
818 field_access
= isl_multi_pw_aff_zero(space
);
820 return pet_array_member(base_access
, field_access
);
823 /* Check if "expr" calls function "minmax" with two arguments and if so
824 * make lhs and rhs refer to these two arguments.
826 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
832 if (expr
->getStmtClass() != Stmt::CallExprClass
)
835 call
= cast
<CallExpr
>(expr
);
836 fd
= call
->getDirectCallee();
840 if (call
->getNumArgs() != 2)
843 name
= fd
->getDeclName().getAsString();
847 lhs
= call
->getArg(0);
848 rhs
= call
->getArg(1);
853 /* Check if "expr" is of the form min(lhs, rhs) and if so make
854 * lhs and rhs refer to the two arguments.
856 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
858 return is_minmax(expr
, "min", lhs
, rhs
);
861 /* Check if "expr" is of the form max(lhs, rhs) and if so make
862 * lhs and rhs refer to the two arguments.
864 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
866 return is_minmax(expr
, "max", lhs
, rhs
);
869 /* Extract an affine expressions representing the comparison "LHS op RHS"
870 * "comp" is the original statement that "LHS op RHS" is derived from
871 * and is used for diagnostics.
873 * If the comparison is of the form
877 * then the expression is constructed as the conjunction of
882 * A similar optimization is performed for max(a,b) <= c.
883 * We do this because that will lead to simpler representations
885 * If isl is ever enhanced to explicitly deal with min and max expressions,
886 * this optimization can be removed.
888 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
889 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
896 enum pet_op_type type
;
899 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
901 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
903 if (op
== BO_LT
|| op
== BO_LE
) {
905 if (is_min(RHS
, expr1
, expr2
)) {
906 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
907 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
908 return pet_and(lhs
, rhs
);
910 if (is_max(LHS
, expr1
, expr2
)) {
911 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
912 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
913 return pet_and(lhs
, rhs
);
917 lhs
= extract_affine(LHS
);
918 rhs
= extract_affine(RHS
);
920 type
= BinaryOperatorKind2pet_op_type(op
);
921 return pet_comparison(type
, lhs
, rhs
);
924 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
926 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
927 comp
->getRHS(), comp
);
930 /* Extract an affine expression from a boolean expression.
931 * In particular, return the expression "expr ? 1 : 0".
932 * Return NULL if we are unable to extract an affine expression.
934 * We first convert the clang::Expr to a pet_expr and
935 * then extract an affine expression from that pet_expr.
937 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
944 isl_set
*u
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
945 return indicator_function(u
, isl_set_copy(u
));
948 pe
= extract_expr(expr
);
949 pc
= convert_assignments(ctx
, assigned_value
);
950 pc
= pet_context_set_allow_nested(pc
, nesting_enabled
);
951 cond
= pet_expr_extract_affine_condition(pe
, pc
);
952 if (isl_pw_aff_involves_nan(cond
))
953 cond
= isl_pw_aff_free(cond
);
954 pet_context_free(pc
);
959 /* Mark the given access pet_expr as a write.
961 static __isl_give pet_expr
*mark_write(__isl_take pet_expr
*access
)
963 access
= pet_expr_access_set_write(access
, 1);
964 access
= pet_expr_access_set_read(access
, 0);
969 /* Construct a pet_expr representing a unary operator expression.
971 __isl_give pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
976 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
977 if (op
== pet_op_last
) {
982 arg
= extract_expr(expr
->getSubExpr());
984 if (expr
->isIncrementDecrementOp() &&
985 pet_expr_get_type(arg
) == pet_expr_access
) {
986 arg
= mark_write(arg
);
987 arg
= pet_expr_access_set_read(arg
, 1);
990 return pet_expr_new_unary(op
, arg
);
993 /* If the access expression "expr" writes to a (non-virtual) scalar,
994 * then mark the scalar as having an unknown value in "assigned_value".
996 static int clear_write(__isl_keep pet_expr
*expr
, void *user
)
1000 PetScan
*ps
= (PetScan
*) user
;
1002 if (!pet_expr_access_is_write(expr
))
1004 if (!pet_expr_is_scalar_access(expr
))
1007 id
= pet_expr_access_get_id(expr
);
1008 decl
= (ValueDecl
*) isl_id_get_user(id
);
1012 clear_assignment(ps
->assigned_value
, decl
);
1017 /* Take into account the writes in "stmt".
1018 * That is, first mark all scalar variables that are written by "stmt"
1019 * as having an unknown value. Afterwards,
1020 * if "stmt" is a top-level (i.e., unconditional) assignment
1021 * to a scalar variable, then update "assigned_value" accordingly.
1023 * In particular, if the lhs of the assignment is a scalar variable, then mark
1024 * the variable as having been assigned. If, furthermore, the rhs
1025 * is an affine expression, then keep track of this value in assigned_value
1026 * so that we can plug it in when we later come across the same variable.
1028 * We skip assignments to virtual arrays (those with NULL user pointer).
1030 void PetScan::handle_writes(struct pet_stmt
*stmt
)
1032 pet_expr
*body
= stmt
->body
;
1039 pet_expr_foreach_access_expr(body
, &clear_write
, this);
1041 if (!pet_stmt_is_assign(stmt
))
1043 if (!isl_set_plain_is_universe(stmt
->domain
))
1045 arg
= pet_expr_get_arg(body
, 0);
1046 if (!pet_expr_is_scalar_access(arg
)) {
1051 id
= pet_expr_access_get_id(arg
);
1052 decl
= (ValueDecl
*) isl_id_get_user(id
);
1059 arg
= pet_expr_get_arg(body
, 1);
1060 pc
= convert_assignments(ctx
, assigned_value
);
1061 pa
= pet_expr_extract_affine(arg
, pc
);
1062 pet_context_free(pc
);
1063 clear_assignment(assigned_value
, decl
);
1066 if (isl_pw_aff_involves_nan(pa
))
1067 pa
= isl_pw_aff_free(pa
);
1070 assigned_value
[decl
] = pa
;
1071 insert_expression(pa
);
1074 /* Update "assigned_value" based on the write accesses (and, in particular,
1075 * assignments) in "scop".
1077 void PetScan::handle_writes(struct pet_scop
*scop
)
1081 for (int i
= 0; i
< scop
->n_stmt
; ++i
)
1082 handle_writes(scop
->stmts
[i
]);
1085 /* Construct a pet_expr representing a binary operator expression.
1087 * If the top level operator is an assignment and the LHS is an access,
1088 * then we mark that access as a write. If the operator is a compound
1089 * assignment, the access is marked as both a read and a write.
1091 __isl_give pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1094 pet_expr
*lhs
, *rhs
;
1095 enum pet_op_type op
;
1097 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1098 if (op
== pet_op_last
) {
1103 lhs
= extract_expr(expr
->getLHS());
1104 rhs
= extract_expr(expr
->getRHS());
1106 if (expr
->isAssignmentOp() &&
1107 pet_expr_get_type(lhs
) == pet_expr_access
) {
1108 lhs
= mark_write(lhs
);
1109 if (expr
->isCompoundAssignmentOp())
1110 lhs
= pet_expr_access_set_read(lhs
, 1);
1113 type_size
= get_type_size(expr
->getType(), ast_context
);
1114 return pet_expr_new_binary(type_size
, op
, lhs
, rhs
);
1117 /* Construct a pet_scop with a single statement killing the entire
1120 struct pet_scop
*PetScan::kill(Stmt
*stmt
, struct pet_array
*array
)
1124 isl_multi_pw_aff
*index
;
1130 access
= isl_map_from_range(isl_set_copy(array
->extent
));
1131 id
= isl_set_get_tuple_id(array
->extent
);
1132 space
= isl_space_alloc(ctx
, 0, 0, 0);
1133 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
1134 index
= isl_multi_pw_aff_zero(space
);
1135 expr
= pet_expr_kill_from_access_and_index(access
, index
);
1136 return extract(expr
, stmt
->getSourceRange(), false);
1139 /* Construct a pet_scop for a (single) variable declaration.
1141 * The scop contains the variable being declared (as an array)
1142 * and a statement killing the array.
1144 * If the variable is initialized in the AST, then the scop
1145 * also contains an assignment to the variable.
1147 struct pet_scop
*PetScan::extract(DeclStmt
*stmt
)
1152 pet_expr
*lhs
, *rhs
, *pe
;
1153 struct pet_scop
*scop_decl
, *scop
;
1154 struct pet_array
*array
;
1156 if (!stmt
->isSingleDecl()) {
1161 decl
= stmt
->getSingleDecl();
1162 vd
= cast
<VarDecl
>(decl
);
1164 array
= extract_array(ctx
, vd
, NULL
);
1166 array
->declared
= 1;
1167 scop_decl
= kill(stmt
, array
);
1168 scop_decl
= pet_scop_add_array(scop_decl
, array
);
1173 lhs
= extract_access_expr(vd
);
1174 rhs
= extract_expr(vd
->getInit());
1176 lhs
= mark_write(lhs
);
1178 type_size
= get_type_size(vd
->getType(), ast_context
);
1179 pe
= pet_expr_new_binary(type_size
, pet_op_assign
, lhs
, rhs
);
1180 scop
= extract(pe
, stmt
->getSourceRange(), false);
1182 scop_decl
= pet_scop_prefix(scop_decl
, 0);
1183 scop
= pet_scop_prefix(scop
, 1);
1185 scop
= pet_scop_add_seq(ctx
, scop_decl
, scop
);
1190 /* Construct a pet_expr representing a conditional operation.
1192 __isl_give pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1194 pet_expr
*cond
, *lhs
, *rhs
;
1197 cond
= extract_expr(expr
->getCond());
1198 lhs
= extract_expr(expr
->getTrueExpr());
1199 rhs
= extract_expr(expr
->getFalseExpr());
1201 return pet_expr_new_ternary(cond
, lhs
, rhs
);
1204 __isl_give pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1206 return extract_expr(expr
->getSubExpr());
1209 /* Construct a pet_expr representing a floating point value.
1211 * If the floating point literal does not appear in a macro,
1212 * then we use the original representation in the source code
1213 * as the string representation. Otherwise, we use the pretty
1214 * printer to produce a string representation.
1216 __isl_give pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1220 const LangOptions
&LO
= PP
.getLangOpts();
1221 SourceLocation loc
= expr
->getLocation();
1223 if (!loc
.isMacroID()) {
1224 SourceManager
&SM
= PP
.getSourceManager();
1225 unsigned len
= Lexer::MeasureTokenLength(loc
, SM
, LO
);
1226 s
= string(SM
.getCharacterData(loc
), len
);
1228 llvm::raw_string_ostream
S(s
);
1229 expr
->printPretty(S
, 0, PrintingPolicy(LO
));
1232 d
= expr
->getValueAsApproximateDouble();
1233 return pet_expr_new_double(ctx
, d
, s
.c_str());
1236 /* Convert the index expression "index" into an access pet_expr of type "qt".
1238 __isl_give pet_expr
*PetScan::extract_access_expr(QualType qt
,
1239 __isl_take isl_multi_pw_aff
*index
)
1245 depth
= extract_depth(index
);
1246 type_size
= get_type_size(qt
, ast_context
);
1248 pe
= pet_expr_from_index_and_depth(type_size
, index
, depth
);
1253 /* Extract an index expression from "expr" and then convert it into
1254 * an access pet_expr.
1256 __isl_give pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1258 return extract_access_expr(expr
->getType(), extract_index(expr
));
1261 /* Extract an index expression from "decl" and then convert it into
1262 * an access pet_expr.
1264 __isl_give pet_expr
*PetScan::extract_access_expr(ValueDecl
*decl
)
1266 return extract_access_expr(decl
->getType(), extract_index(decl
));
1269 __isl_give pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1271 return extract_expr(expr
->getSubExpr());
1274 /* Extract an assume statement from the argument "expr"
1275 * of a __pencil_assume statement.
1277 __isl_give pet_expr
*PetScan::extract_assume(Expr
*expr
)
1282 cond
= try_extract_affine_condition(expr
);
1284 res
= extract_expr(expr
);
1286 isl_multi_pw_aff
*index
;
1287 index
= isl_multi_pw_aff_from_pw_aff(cond
);
1288 res
= pet_expr_from_index(index
);
1290 return pet_expr_new_unary(pet_op_assume
, res
);
1293 /* Construct a pet_expr corresponding to the function call argument "expr".
1294 * The argument appears in position "pos" of a call to function "fd".
1296 * If we are passing along a pointer to an array element
1297 * or an entire row or even higher dimensional slice of an array,
1298 * then the function being called may write into the array.
1300 * We assume here that if the function is declared to take a pointer
1301 * to a const type, then the function will perform a read
1302 * and that otherwise, it will perform a write.
1304 __isl_give pet_expr
*PetScan::extract_argument(FunctionDecl
*fd
, int pos
,
1308 int is_addr
= 0, is_partial
= 0;
1311 if (expr
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1312 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(expr
);
1313 expr
= ice
->getSubExpr();
1315 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1316 UnaryOperator
*op
= cast
<UnaryOperator
>(expr
);
1317 if (op
->getOpcode() == UO_AddrOf
) {
1319 expr
= op
->getSubExpr();
1322 res
= extract_expr(expr
);
1325 sc
= expr
->getStmtClass();
1326 if ((sc
== Stmt::ArraySubscriptExprClass
||
1327 sc
== Stmt::MemberExprClass
) &&
1328 array_depth(expr
->getType().getTypePtr()) > 0)
1330 if ((is_addr
|| is_partial
) &&
1331 pet_expr_get_type(res
) == pet_expr_access
) {
1333 if (!fd
->hasPrototype()) {
1334 report_prototype_required(expr
);
1335 return pet_expr_free(res
);
1337 parm
= fd
->getParamDecl(pos
);
1338 if (!const_base(parm
->getType()))
1339 res
= mark_write(res
);
1343 res
= pet_expr_new_unary(pet_op_address_of
, res
);
1347 /* Construct a pet_expr representing a function call.
1349 * In the special case of a "call" to __pencil_assume,
1350 * construct an assume expression instead.
1352 __isl_give pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1354 pet_expr
*res
= NULL
;
1359 fd
= expr
->getDirectCallee();
1365 name
= fd
->getDeclName().getAsString();
1366 n_arg
= expr
->getNumArgs();
1368 if (n_arg
== 1 && name
== "__pencil_assume")
1369 return extract_assume(expr
->getArg(0));
1371 res
= pet_expr_new_call(ctx
, name
.c_str(), n_arg
);
1375 for (int i
= 0; i
< n_arg
; ++i
) {
1376 Expr
*arg
= expr
->getArg(i
);
1377 res
= pet_expr_set_arg(res
, i
,
1378 PetScan::extract_argument(fd
, i
, arg
));
1384 /* Construct a pet_expr representing a (C style) cast.
1386 __isl_give pet_expr
*PetScan::extract_expr(CStyleCastExpr
*expr
)
1391 arg
= extract_expr(expr
->getSubExpr());
1395 type
= expr
->getTypeAsWritten();
1396 return pet_expr_new_cast(type
.getAsString().c_str(), arg
);
1399 /* Construct a pet_expr representing an integer.
1401 __isl_give pet_expr
*PetScan::extract_expr(IntegerLiteral
*expr
)
1403 return pet_expr_new_int(extract_int(expr
));
1406 /* Try and construct a pet_expr representing "expr".
1408 __isl_give pet_expr
*PetScan::extract_expr(Expr
*expr
)
1410 switch (expr
->getStmtClass()) {
1411 case Stmt::UnaryOperatorClass
:
1412 return extract_expr(cast
<UnaryOperator
>(expr
));
1413 case Stmt::CompoundAssignOperatorClass
:
1414 case Stmt::BinaryOperatorClass
:
1415 return extract_expr(cast
<BinaryOperator
>(expr
));
1416 case Stmt::ImplicitCastExprClass
:
1417 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1418 case Stmt::ArraySubscriptExprClass
:
1419 case Stmt::DeclRefExprClass
:
1420 case Stmt::MemberExprClass
:
1421 return extract_access_expr(expr
);
1422 case Stmt::IntegerLiteralClass
:
1423 return extract_expr(cast
<IntegerLiteral
>(expr
));
1424 case Stmt::FloatingLiteralClass
:
1425 return extract_expr(cast
<FloatingLiteral
>(expr
));
1426 case Stmt::ParenExprClass
:
1427 return extract_expr(cast
<ParenExpr
>(expr
));
1428 case Stmt::ConditionalOperatorClass
:
1429 return extract_expr(cast
<ConditionalOperator
>(expr
));
1430 case Stmt::CallExprClass
:
1431 return extract_expr(cast
<CallExpr
>(expr
));
1432 case Stmt::CStyleCastExprClass
:
1433 return extract_expr(cast
<CStyleCastExpr
>(expr
));
1440 /* Check if the given initialization statement is an assignment.
1441 * If so, return that assignment. Otherwise return NULL.
1443 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1445 BinaryOperator
*ass
;
1447 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1450 ass
= cast
<BinaryOperator
>(init
);
1451 if (ass
->getOpcode() != BO_Assign
)
1457 /* Check if the given initialization statement is a declaration
1458 * of a single variable.
1459 * If so, return that declaration. Otherwise return NULL.
1461 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1465 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1468 decl
= cast
<DeclStmt
>(init
);
1470 if (!decl
->isSingleDecl())
1473 return decl
->getSingleDecl();
1476 /* Given the assignment operator in the initialization of a for loop,
1477 * extract the induction variable, i.e., the (integer)variable being
1480 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1487 lhs
= init
->getLHS();
1488 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1493 ref
= cast
<DeclRefExpr
>(lhs
);
1494 decl
= ref
->getDecl();
1495 type
= decl
->getType().getTypePtr();
1497 if (!type
->isIntegerType()) {
1505 /* Given the initialization statement of a for loop and the single
1506 * declaration in this initialization statement,
1507 * extract the induction variable, i.e., the (integer) variable being
1510 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1514 vd
= cast
<VarDecl
>(decl
);
1516 const QualType type
= vd
->getType();
1517 if (!type
->isIntegerType()) {
1522 if (!vd
->getInit()) {
1530 /* Check that op is of the form iv++ or iv--.
1531 * Return a pet_expr representing "1" or "-1" accordingly.
1533 __isl_give pet_expr
*PetScan::extract_unary_increment(
1534 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1540 if (!op
->isIncrementDecrementOp()) {
1545 sub
= op
->getSubExpr();
1546 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1551 ref
= cast
<DeclRefExpr
>(sub
);
1552 if (ref
->getDecl() != iv
) {
1557 if (op
->isIncrementOp())
1558 v
= isl_val_one(ctx
);
1560 v
= isl_val_negone(ctx
);
1562 return pet_expr_new_int(v
);
1565 /* Check if op is of the form
1569 * and return the increment "expr - iv" as a pet_expr.
1571 __isl_give pet_expr
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1572 clang::ValueDecl
*iv
)
1577 pet_expr
*expr
, *expr_iv
;
1579 if (op
->getOpcode() != BO_Assign
) {
1585 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1590 ref
= cast
<DeclRefExpr
>(lhs
);
1591 if (ref
->getDecl() != iv
) {
1596 expr
= extract_expr(op
->getRHS());
1597 expr_iv
= extract_expr(lhs
);
1599 type_size
= get_type_size(iv
->getType(), ast_context
);
1600 return pet_expr_new_binary(type_size
, pet_op_sub
, expr
, expr_iv
);
1603 /* Check that op is of the form iv += cst or iv -= cst
1604 * and return a pet_expr corresponding to cst or -cst accordingly.
1606 __isl_give pet_expr
*PetScan::extract_compound_increment(
1607 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1613 BinaryOperatorKind opcode
;
1615 opcode
= op
->getOpcode();
1616 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1620 if (opcode
== BO_SubAssign
)
1624 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1629 ref
= cast
<DeclRefExpr
>(lhs
);
1630 if (ref
->getDecl() != iv
) {
1635 expr
= extract_expr(op
->getRHS());
1637 expr
= pet_expr_new_unary(pet_op_minus
, expr
);
1642 /* Check that the increment of the given for loop increments
1643 * (or decrements) the induction variable "iv" and return
1644 * the increment as a pet_expr if successful.
1646 __isl_give pet_expr
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1649 Stmt
*inc
= stmt
->getInc();
1652 report_missing_increment(stmt
);
1656 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1657 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1658 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1659 return extract_compound_increment(
1660 cast
<CompoundAssignOperator
>(inc
), iv
);
1661 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1662 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1668 /* Embed the given iteration domain in an extra outer loop
1669 * with induction variable "var".
1670 * If this variable appeared as a parameter in the constraints,
1671 * it is replaced by the new outermost dimension.
1673 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1674 __isl_take isl_id
*var
)
1678 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1679 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1681 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1682 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1689 /* Return those elements in the space of "cond" that come after
1690 * (based on "sign") an element in "cond".
1692 static __isl_give isl_set
*after(__isl_take isl_set
*cond
, int sign
)
1694 isl_map
*previous_to_this
;
1697 previous_to_this
= isl_map_lex_lt(isl_set_get_space(cond
));
1699 previous_to_this
= isl_map_lex_gt(isl_set_get_space(cond
));
1701 cond
= isl_set_apply(cond
, previous_to_this
);
1706 /* Create the infinite iteration domain
1708 * { [id] : id >= 0 }
1710 * If "scop" has an affine skip of type pet_skip_later,
1711 * then remove those iterations i that have an earlier iteration
1712 * where the skip condition is satisfied, meaning that iteration i
1714 * Since we are dealing with a loop without loop iterator,
1715 * the skip condition cannot refer to the current loop iterator and
1716 * so effectively, the returned set is of the form
1718 * { [0]; [id] : id >= 1 and not skip }
1720 static __isl_give isl_set
*infinite_domain(__isl_take isl_id
*id
,
1721 struct pet_scop
*scop
)
1723 isl_ctx
*ctx
= isl_id_get_ctx(id
);
1727 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
1728 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, id
);
1730 if (!pet_scop_has_affine_skip(scop
, pet_skip_later
))
1733 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
1734 skip
= embed(skip
, isl_id_copy(id
));
1735 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
1736 domain
= isl_set_subtract(domain
, after(skip
, 1));
1741 /* Create an identity affine expression on the space containing "domain",
1742 * which is assumed to be one-dimensional.
1744 static __isl_give isl_aff
*identity_aff(__isl_keep isl_set
*domain
)
1746 isl_local_space
*ls
;
1748 ls
= isl_local_space_from_space(isl_set_get_space(domain
));
1749 return isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
1752 /* Create an affine expression that maps elements
1753 * of a single-dimensional array "id_test" to the previous element
1754 * (according to "inc"), provided this element belongs to "domain".
1755 * That is, create the affine expression
1757 * { id[x] -> id[x - inc] : x - inc in domain }
1759 static __isl_give isl_multi_pw_aff
*map_to_previous(__isl_take isl_id
*id_test
,
1760 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
1763 isl_local_space
*ls
;
1765 isl_multi_pw_aff
*prev
;
1767 space
= isl_set_get_space(domain
);
1768 ls
= isl_local_space_from_space(space
);
1769 aff
= isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
1770 aff
= isl_aff_add_constant_val(aff
, isl_val_neg(inc
));
1771 prev
= isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
1772 domain
= isl_set_preimage_multi_pw_aff(domain
,
1773 isl_multi_pw_aff_copy(prev
));
1774 prev
= isl_multi_pw_aff_intersect_domain(prev
, domain
);
1775 prev
= isl_multi_pw_aff_set_tuple_id(prev
, isl_dim_out
, id_test
);
1780 /* Add an implication to "scop" expressing that if an element of
1781 * virtual array "id_test" has value "satisfied" then all previous elements
1782 * of this array also have that value. The set of previous elements
1783 * is bounded by "domain". If "sign" is negative then the iterator
1784 * is decreasing and we express that all subsequent array elements
1785 * (but still defined previously) have the same value.
1787 static struct pet_scop
*add_implication(struct pet_scop
*scop
,
1788 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
, int sign
,
1794 domain
= isl_set_set_tuple_id(domain
, id_test
);
1795 space
= isl_set_get_space(domain
);
1797 map
= isl_map_lex_ge(space
);
1799 map
= isl_map_lex_le(space
);
1800 map
= isl_map_intersect_range(map
, domain
);
1801 scop
= pet_scop_add_implication(scop
, map
, satisfied
);
1806 /* Add a filter to "scop" that imposes that it is only executed
1807 * when the variable identified by "id_test" has a zero value
1808 * for all previous iterations of "domain".
1810 * In particular, add a filter that imposes that the array
1811 * has a zero value at the previous iteration of domain and
1812 * add an implication that implies that it then has that
1813 * value for all previous iterations.
1815 static struct pet_scop
*scop_add_break(struct pet_scop
*scop
,
1816 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
,
1817 __isl_take isl_val
*inc
)
1819 isl_multi_pw_aff
*prev
;
1820 int sign
= isl_val_sgn(inc
);
1822 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
1823 scop
= add_implication(scop
, id_test
, domain
, sign
, 0);
1824 scop
= pet_scop_filter(scop
, prev
, 0);
1829 /* Construct a pet_scop for an infinite loop around the given body.
1831 * We extract a pet_scop for the body and then embed it in a loop with
1840 * If the body contains any break, then it is taken into
1841 * account in infinite_domain (if the skip condition is affine)
1842 * or in scop_add_break (if the skip condition is not affine).
1844 * If we were only able to extract part of the body, then simply
1847 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
1849 isl_id
*id
, *id_test
;
1852 struct pet_scop
*scop
;
1855 scop
= extract(body
);
1861 id
= isl_id_alloc(ctx
, "t", NULL
);
1862 domain
= infinite_domain(isl_id_copy(id
), scop
);
1863 ident
= identity_aff(domain
);
1865 has_var_break
= pet_scop_has_var_skip(scop
, pet_skip_later
);
1867 id_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
1869 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
1870 isl_aff_copy(ident
), ident
, id
);
1872 scop
= scop_add_break(scop
, id_test
, domain
, isl_val_one(ctx
));
1874 isl_set_free(domain
);
1879 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1885 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
1887 clear_assignments
clear(assigned_value
);
1888 clear
.TraverseStmt(stmt
->getBody());
1890 return extract_infinite_loop(stmt
->getBody());
1893 /* Add an array with the given extent (range of "index") to the list
1894 * of arrays in "scop" and return the extended pet_scop.
1895 * The array is marked as attaining values 0 and 1 only and
1896 * as each element being assigned at most once.
1898 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
1899 __isl_keep isl_multi_pw_aff
*index
, clang::ASTContext
&ast_ctx
)
1901 int int_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
1903 return pet_scop_add_boolean_array(scop
, isl_multi_pw_aff_copy(index
),
1907 /* Construct a pet_scop for a while loop of the form
1912 * In particular, construct a scop for an infinite loop around body and
1913 * intersect the domain with the affine expression.
1914 * Note that this intersection may result in an empty loop.
1916 struct pet_scop
*PetScan::extract_affine_while(__isl_take isl_pw_aff
*pa
,
1919 struct pet_scop
*scop
;
1923 valid
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
1924 dom
= isl_pw_aff_non_zero_set(pa
);
1925 scop
= extract_infinite_loop(body
);
1926 scop
= pet_scop_restrict(scop
, isl_set_params(dom
));
1927 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid
));
1932 /* Construct a scop for a while, given the scops for the condition
1933 * and the body, the filter identifier and the iteration domain of
1936 * In particular, the scop for the condition is filtered to depend
1937 * on "id_test" evaluating to true for all previous iterations
1938 * of the loop, while the scop for the body is filtered to depend
1939 * on "id_test" evaluating to true for all iterations up to the
1940 * current iteration.
1941 * The actual filter only imposes that this virtual array has
1942 * value one on the previous or the current iteration.
1943 * The fact that this condition also applies to the previous
1944 * iterations is enforced by an implication.
1946 * These filtered scops are then combined into a single scop.
1948 * "sign" is positive if the iterator increases and negative
1951 static struct pet_scop
*scop_add_while(struct pet_scop
*scop_cond
,
1952 struct pet_scop
*scop_body
, __isl_take isl_id
*id_test
,
1953 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
1955 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
1957 isl_multi_pw_aff
*test_index
;
1958 isl_multi_pw_aff
*prev
;
1959 int sign
= isl_val_sgn(inc
);
1960 struct pet_scop
*scop
;
1962 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
1963 scop_cond
= pet_scop_filter(scop_cond
, prev
, 1);
1965 space
= isl_space_map_from_set(isl_set_get_space(domain
));
1966 test_index
= isl_multi_pw_aff_identity(space
);
1967 test_index
= isl_multi_pw_aff_set_tuple_id(test_index
, isl_dim_out
,
1968 isl_id_copy(id_test
));
1969 scop_body
= pet_scop_filter(scop_body
, test_index
, 1);
1971 scop
= pet_scop_add_seq(ctx
, scop_cond
, scop_body
);
1972 scop
= add_implication(scop
, id_test
, domain
, sign
, 1);
1977 /* Check if the while loop is of the form
1979 * while (affine expression)
1982 * If so, call extract_affine_while to construct a scop.
1984 * Otherwise, extract the body and pass control to extract_while
1985 * to extend the iteration domain with an infinite loop.
1986 * If we were only able to extract part of the body, then simply
1989 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
1992 int test_nr
, stmt_nr
;
1994 struct pet_scop
*scop_body
;
1996 cond
= stmt
->getCond();
2002 clear_assignments
clear(assigned_value
);
2003 clear
.TraverseStmt(stmt
->getBody());
2005 pa
= try_extract_affine_condition(cond
);
2007 return extract_affine_while(pa
, stmt
->getBody());
2009 if (!allow_nested
) {
2016 scop_body
= extract(stmt
->getBody());
2020 return extract_while(cond
, test_nr
, stmt_nr
, scop_body
, NULL
);
2023 /* Construct a generic while scop, with iteration domain
2024 * { [t] : t >= 0 } around "scop_body". The scop consists of two parts,
2025 * one for evaluating the condition "cond" and one for the body.
2026 * "test_nr" is the sequence number of the virtual test variable that contains
2027 * the result of the condition and "stmt_nr" is the sequence number
2028 * of the statement that evaluates the condition.
2029 * If "scop_inc" is not NULL, then it is added at the end of the body,
2030 * after replacing any skip conditions resulting from continue statements
2031 * by the skip conditions resulting from break statements (if any).
2033 * The schedule is adjusted to reflect that the condition is evaluated
2034 * before the body is executed and the body is filtered to depend
2035 * on the result of the condition evaluating to true on all iterations
2036 * up to the current iteration, while the evaluation of the condition itself
2037 * is filtered to depend on the result of the condition evaluating to true
2038 * on all previous iterations.
2039 * The context of the scop representing the body is dropped
2040 * because we don't know how many times the body will be executed,
2043 * If the body contains any break, then it is taken into
2044 * account in infinite_domain (if the skip condition is affine)
2045 * or in scop_add_break (if the skip condition is not affine).
2047 struct pet_scop
*PetScan::extract_while(Expr
*cond
, int test_nr
, int stmt_nr
,
2048 struct pet_scop
*scop_body
, struct pet_scop
*scop_inc
)
2050 isl_id
*id
, *id_test
, *id_break_test
;
2053 isl_multi_pw_aff
*test_index
;
2054 struct pet_scop
*scop
;
2057 test_index
= pet_create_test_index(ctx
, test_nr
);
2058 scop
= extract_non_affine_condition(cond
, stmt_nr
,
2059 isl_multi_pw_aff_copy(test_index
));
2060 scop
= scop_add_array(scop
, test_index
, ast_context
);
2061 id_test
= isl_multi_pw_aff_get_tuple_id(test_index
, isl_dim_out
);
2062 isl_multi_pw_aff_free(test_index
);
2064 id
= isl_id_alloc(ctx
, "t", NULL
);
2065 domain
= infinite_domain(isl_id_copy(id
), scop_body
);
2066 ident
= identity_aff(domain
);
2068 has_var_break
= pet_scop_has_var_skip(scop_body
, pet_skip_later
);
2070 id_break_test
= pet_scop_get_skip_id(scop_body
, pet_skip_later
);
2072 scop
= pet_scop_prefix(scop
, 0);
2073 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), isl_aff_copy(ident
),
2074 isl_aff_copy(ident
), isl_id_copy(id
));
2075 scop_body
= pet_scop_reset_context(scop_body
);
2076 scop_body
= pet_scop_prefix(scop_body
, 1);
2078 scop_inc
= pet_scop_prefix(scop_inc
, 2);
2079 if (pet_scop_has_skip(scop_body
, pet_skip_later
)) {
2080 isl_multi_pw_aff
*skip
;
2081 skip
= pet_scop_get_skip(scop_body
, pet_skip_later
);
2082 scop_body
= pet_scop_set_skip(scop_body
,
2083 pet_skip_now
, skip
);
2085 pet_scop_reset_skip(scop_body
, pet_skip_now
);
2086 scop_body
= pet_scop_add_seq(ctx
, scop_body
, scop_inc
);
2088 scop_body
= pet_scop_embed(scop_body
, isl_set_copy(domain
),
2089 isl_aff_copy(ident
), ident
, id
);
2091 if (has_var_break
) {
2092 scop
= scop_add_break(scop
, isl_id_copy(id_break_test
),
2093 isl_set_copy(domain
), isl_val_one(ctx
));
2094 scop_body
= scop_add_break(scop_body
, id_break_test
,
2095 isl_set_copy(domain
), isl_val_one(ctx
));
2097 scop
= scop_add_while(scop
, scop_body
, id_test
, domain
,
2103 /* Check whether "cond" expresses a simple loop bound
2104 * on the only set dimension.
2105 * In particular, if "up" is set then "cond" should contain only
2106 * upper bounds on the set dimension.
2107 * Otherwise, it should contain only lower bounds.
2109 static bool is_simple_bound(__isl_keep isl_set
*cond
, __isl_keep isl_val
*inc
)
2111 if (isl_val_is_pos(inc
))
2112 return !isl_set_dim_has_any_lower_bound(cond
, isl_dim_set
, 0);
2114 return !isl_set_dim_has_any_upper_bound(cond
, isl_dim_set
, 0);
2117 /* Extend a condition on a given iteration of a loop to one that
2118 * imposes the same condition on all previous iterations.
2119 * "domain" expresses the lower [upper] bound on the iterations
2120 * when inc is positive [negative].
2122 * In particular, we construct the condition (when inc is positive)
2124 * forall i' : (domain(i') and i' <= i) => cond(i')
2126 * which is equivalent to
2128 * not exists i' : domain(i') and i' <= i and not cond(i')
2130 * We construct this set by negating cond, applying a map
2132 * { [i'] -> [i] : domain(i') and i' <= i }
2134 * and then negating the result again.
2136 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
2137 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2139 isl_map
*previous_to_this
;
2141 if (isl_val_is_pos(inc
))
2142 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
2144 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
2146 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
2148 cond
= isl_set_complement(cond
);
2149 cond
= isl_set_apply(cond
, previous_to_this
);
2150 cond
= isl_set_complement(cond
);
2157 /* Construct a domain of the form
2159 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2161 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
2162 __isl_take isl_pw_aff
*init
, __isl_take isl_val
*inc
)
2168 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
2169 dim
= isl_pw_aff_get_domain_space(init
);
2170 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2171 aff
= isl_aff_add_coefficient_val(aff
, isl_dim_in
, 0, inc
);
2172 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2174 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2175 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2176 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2177 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2179 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2181 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2183 return isl_set_params(set
);
2186 /* Assuming "cond" represents a bound on a loop where the loop
2187 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2190 * Under the given assumptions, wrapping is only possible if "cond" allows
2191 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2192 * increasing iterator and 0 in case of a decreasing iterator.
2194 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
,
2195 __isl_keep isl_val
*inc
)
2202 test
= isl_set_copy(cond
);
2204 ctx
= isl_set_get_ctx(test
);
2205 if (isl_val_is_neg(inc
))
2206 limit
= isl_val_zero(ctx
);
2208 limit
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2209 limit
= isl_val_2exp(limit
);
2210 limit
= isl_val_sub_ui(limit
, 1);
2213 test
= isl_set_fix_val(cond
, isl_dim_set
, 0, limit
);
2214 cw
= !isl_set_is_empty(test
);
2220 /* Given a one-dimensional space, construct the following affine expression
2223 * { [v] -> [v mod 2^width] }
2225 * where width is the number of bits used to represent the values
2226 * of the unsigned variable "iv".
2228 static __isl_give isl_aff
*compute_wrapping(__isl_take isl_space
*dim
,
2235 ctx
= isl_space_get_ctx(dim
);
2236 mod
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2237 mod
= isl_val_2exp(mod
);
2239 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2240 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2241 aff
= isl_aff_mod_val(aff
, mod
);
2246 /* Project out the parameter "id" from "set".
2248 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2249 __isl_keep isl_id
*id
)
2253 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2255 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2260 /* Compute the set of parameters for which "set1" is a subset of "set2".
2262 * set1 is a subset of set2 if
2264 * forall i in set1 : i in set2
2268 * not exists i in set1 and i not in set2
2272 * not exists i in set1 \ set2
2274 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2275 __isl_take isl_set
*set2
)
2277 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2280 /* Compute the set of parameter values for which "cond" holds
2281 * on the next iteration for each element of "dom".
2283 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2284 * and then compute the set of parameters for which the result is a subset
2287 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2288 __isl_take isl_set
*dom
, __isl_take isl_val
*inc
)
2294 space
= isl_set_get_space(dom
);
2295 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2296 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2297 aff
= isl_aff_add_constant_val(aff
, inc
);
2298 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2300 dom
= isl_set_apply(dom
, next
);
2302 return enforce_subset(dom
, cond
);
2305 /* Extract the for loop "stmt" as a while loop.
2306 * "iv" is the loop iterator. "init" is the initialization.
2307 * "inc" is the increment.
2309 * That is, the for loop has the form
2311 * for (iv = init; cond; iv += inc)
2322 * except that the skips resulting from any continue statements
2323 * in body do not apply to the increment, but are replaced by the skips
2324 * resulting from break statements.
2326 * If "iv" is declared in the for loop, then it is killed before
2327 * and after the loop.
2329 struct pet_scop
*PetScan::extract_non_affine_for(ForStmt
*stmt
, ValueDecl
*iv
,
2330 __isl_take pet_expr
*init
, __isl_take pet_expr
*inc
)
2333 int test_nr
, stmt_nr
;
2335 struct pet_scop
*scop_init
, *scop_inc
, *scop
, *scop_body
;
2337 struct pet_array
*array
;
2338 struct pet_scop
*scop_kill
;
2340 if (!allow_nested
) {
2345 clear_assignment(assigned_value
, iv
);
2347 declared
= !initialization_assignment(stmt
->getInit());
2349 expr_iv
= extract_access_expr(iv
);
2350 expr_iv
= mark_write(expr_iv
);
2351 type_size
= pet_expr_get_type_size(expr_iv
);
2352 init
= pet_expr_new_binary(type_size
, pet_op_assign
, expr_iv
, init
);
2353 scop_init
= extract(init
, stmt
->getInit()->getSourceRange(), false);
2354 scop_init
= pet_scop_prefix(scop_init
, declared
);
2358 scop_body
= extract(stmt
->getBody());
2360 pet_scop_free(scop_init
);
2364 expr_iv
= extract_access_expr(iv
);
2365 expr_iv
= mark_write(expr_iv
);
2366 type_size
= pet_expr_get_type_size(expr_iv
);
2367 inc
= pet_expr_new_binary(type_size
, pet_op_add_assign
, expr_iv
, inc
);
2368 scop_inc
= extract(inc
, stmt
->getInc()->getSourceRange(), false);
2370 pet_scop_free(scop_init
);
2371 pet_scop_free(scop_body
);
2375 scop
= extract_while(stmt
->getCond(), test_nr
, stmt_nr
, scop_body
,
2378 scop
= pet_scop_prefix(scop
, declared
+ 1);
2379 scop
= pet_scop_add_seq(ctx
, scop_init
, scop
);
2384 array
= extract_array(ctx
, iv
, NULL
);
2386 array
->declared
= 1;
2387 scop_kill
= kill(stmt
, array
);
2388 scop_kill
= pet_scop_prefix(scop_kill
, 0);
2389 scop
= pet_scop_add_seq(ctx
, scop_kill
, scop
);
2390 scop_kill
= kill(stmt
, array
);
2391 scop_kill
= pet_scop_add_array(scop_kill
, array
);
2392 scop_kill
= pet_scop_prefix(scop_kill
, 3);
2393 scop
= pet_scop_add_seq(ctx
, scop
, scop_kill
);
2398 /* Construct a pet_scop for a for statement.
2399 * The for loop is required to be of one of the following forms
2401 * for (i = init; condition; ++i)
2402 * for (i = init; condition; --i)
2403 * for (i = init; condition; i += constant)
2404 * for (i = init; condition; i -= constant)
2406 * The initialization of the for loop should either be an assignment
2407 * of a static affine value to an integer variable, or a declaration
2408 * of such a variable with initialization.
2410 * If the initialization or the increment do not satisfy the above
2411 * conditions, i.e., if the initialization is not static affine
2412 * or the increment is not constant, then the for loop is extracted
2413 * as a while loop instead.
2415 * The condition is allowed to contain nested accesses, provided
2416 * they are not being written to inside the body of the loop.
2417 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2418 * essentially treated as a while loop, with iteration domain
2419 * { [i] : i >= init }.
2421 * We extract a pet_scop for the body and then embed it in a loop with
2422 * iteration domain and schedule
2424 * { [i] : i >= init and condition' }
2429 * { [i] : i <= init and condition' }
2432 * Where condition' is equal to condition if the latter is
2433 * a simple upper [lower] bound and a condition that is extended
2434 * to apply to all previous iterations otherwise.
2436 * If the condition is non-affine, then we drop the condition from the
2437 * iteration domain and instead create a separate statement
2438 * for evaluating the condition. The body is then filtered to depend
2439 * on the result of the condition evaluating to true on all iterations
2440 * up to the current iteration, while the evaluation the condition itself
2441 * is filtered to depend on the result of the condition evaluating to true
2442 * on all previous iterations.
2443 * The context of the scop representing the body is dropped
2444 * because we don't know how many times the body will be executed,
2447 * If the stride of the loop is not 1, then "i >= init" is replaced by
2449 * (exists a: i = init + stride * a and a >= 0)
2451 * If the loop iterator i is unsigned, then wrapping may occur.
2452 * We therefore use a virtual iterator instead that does not wrap.
2453 * However, the condition in the code applies
2454 * to the wrapped value, so we need to change condition(i)
2455 * into condition([i % 2^width]). Similarly, we replace all accesses
2456 * to the original iterator by the wrapping of the virtual iterator.
2457 * Note that there may be no need to perform this final wrapping
2458 * if the loop condition (after wrapping) satisfies certain conditions.
2459 * However, the is_simple_bound condition is not enough since it doesn't
2460 * check if there even is an upper bound.
2462 * Wrapping on unsigned iterators can be avoided entirely if
2463 * loop condition is simple, the loop iterator is incremented
2464 * [decremented] by one and the last value before wrapping cannot
2465 * possibly satisfy the loop condition.
2467 * Before extracting a pet_scop from the body we remove all
2468 * assignments in assigned_value to variables that are assigned
2469 * somewhere in the body of the loop.
2471 * Valid parameters for a for loop are those for which the initial
2472 * value itself, the increment on each domain iteration and
2473 * the condition on both the initial value and
2474 * the result of incrementing the iterator for each iteration of the domain
2476 * If the loop condition is non-affine, then we only consider validity
2477 * of the initial value.
2479 * If the body contains any break, then we keep track of it in "skip"
2480 * (if the skip condition is affine) or it is handled in scop_add_break
2481 * (if the skip condition is not affine).
2482 * Note that the affine break condition needs to be considered with
2483 * respect to previous iterations in the virtual domain (if any).
2485 * If we were only able to extract part of the body, then simply
2488 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2490 BinaryOperator
*ass
;
2495 isl_local_space
*ls
;
2498 isl_set
*cond
= NULL
;
2499 isl_set
*skip
= NULL
;
2500 isl_id
*id
, *id_test
= NULL
, *id_break_test
;
2501 struct pet_scop
*scop
, *scop_cond
= NULL
;
2502 assigned_value_cache
cache(assigned_value
);
2508 bool has_affine_break
;
2510 isl_aff
*wrap
= NULL
;
2511 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2512 isl_set
*valid_init
;
2513 isl_set
*valid_cond
;
2514 isl_set
*valid_cond_init
;
2515 isl_set
*valid_cond_next
;
2518 pet_expr
*pe_init
, *pe_inc
;
2519 pet_context
*pc
, *pc_init_val
;
2521 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2522 return extract_infinite_for(stmt
);
2524 init
= stmt
->getInit();
2529 if ((ass
= initialization_assignment(init
)) != NULL
) {
2530 iv
= extract_induction_variable(ass
);
2533 lhs
= ass
->getLHS();
2534 rhs
= ass
->getRHS();
2535 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2536 VarDecl
*var
= extract_induction_variable(init
, decl
);
2540 rhs
= var
->getInit();
2541 lhs
= create_DeclRefExpr(var
);
2543 unsupported(stmt
->getInit());
2547 id
= create_decl_id(ctx
, iv
);
2549 assigned_value
.erase(iv
);
2550 clear_assignments
clear(assigned_value
);
2551 clear
.TraverseStmt(stmt
->getBody());
2553 pe_init
= extract_expr(rhs
);
2554 pe_inc
= extract_increment(stmt
, iv
);
2555 pc
= convert_assignments(ctx
, assigned_value
);
2556 pc_init_val
= pet_context_copy(pc
);
2557 pc_init_val
= pet_context_mark_unknown(pc_init_val
, isl_id_copy(id
));
2558 init_val
= pet_expr_extract_affine(pe_init
, pc_init_val
);
2559 pet_context_free(pc_init_val
);
2560 pa_inc
= pet_expr_extract_affine(pe_inc
, pc
);
2561 pet_context_free(pc
);
2562 inc
= pet_extract_cst(pa_inc
);
2563 if (!pe_init
|| !pe_inc
|| !inc
|| isl_val_is_nan(inc
) ||
2564 isl_pw_aff_involves_nan(pa_inc
) ||
2565 isl_pw_aff_involves_nan(init_val
)) {
2568 isl_pw_aff_free(pa_inc
);
2569 isl_pw_aff_free(init_val
);
2570 if (pe_init
&& pe_inc
&& !(pa_inc
&& !inc
))
2571 return extract_non_affine_for(stmt
, iv
,
2573 pet_expr_free(pe_init
);
2574 pet_expr_free(pe_inc
);
2577 pet_expr_free(pe_init
);
2578 pet_expr_free(pe_inc
);
2580 pa
= try_extract_nested_condition(stmt
->getCond());
2581 if (allow_nested
&& (!pa
|| pet_nested_any_in_pw_aff(pa
)))
2584 scop
= extract(stmt
->getBody());
2587 isl_pw_aff_free(init_val
);
2588 isl_pw_aff_free(pa_inc
);
2589 isl_pw_aff_free(pa
);
2594 valid_inc
= isl_pw_aff_domain(pa_inc
);
2596 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2598 has_affine_break
= scop
&&
2599 pet_scop_has_affine_skip(scop
, pet_skip_later
);
2600 if (has_affine_break
)
2601 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
2602 has_var_break
= scop
&& pet_scop_has_var_skip(scop
, pet_skip_later
);
2604 id_break_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
2606 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2607 isl_pw_aff_free(pa
);
2611 if (!allow_nested
&& !pa
)
2612 pa
= try_extract_affine_condition(stmt
->getCond());
2613 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2614 cond
= isl_pw_aff_non_zero_set(pa
);
2615 if (allow_nested
&& !cond
) {
2616 isl_multi_pw_aff
*test_index
;
2617 int save_n_stmt
= n_stmt
;
2618 test_index
= pet_create_test_index(ctx
, n_test
++);
2620 scop_cond
= extract_non_affine_condition(stmt
->getCond(),
2621 n_stmt
++, isl_multi_pw_aff_copy(test_index
));
2622 n_stmt
= save_n_stmt
;
2623 scop_cond
= scop_add_array(scop_cond
, test_index
, ast_context
);
2624 id_test
= isl_multi_pw_aff_get_tuple_id(test_index
,
2626 isl_multi_pw_aff_free(test_index
);
2627 scop_cond
= pet_scop_prefix(scop_cond
, 0);
2628 scop
= pet_scop_reset_context(scop
);
2629 scop
= pet_scop_prefix(scop
, 1);
2630 cond
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2633 cond
= embed(cond
, isl_id_copy(id
));
2634 skip
= embed(skip
, isl_id_copy(id
));
2635 valid_cond
= isl_set_coalesce(valid_cond
);
2636 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
2637 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
2638 is_one
= isl_val_is_one(inc
) || isl_val_is_negone(inc
);
2639 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2641 valid_cond_init
= enforce_subset(
2642 isl_map_range(isl_map_from_pw_aff(isl_pw_aff_copy(init_val
))),
2643 isl_set_copy(valid_cond
));
2644 if (is_one
&& !is_virtual
) {
2645 isl_pw_aff_free(init_val
);
2646 pa
= extract_comparison(isl_val_is_pos(inc
) ? BO_GE
: BO_LE
,
2648 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2649 valid_init
= set_project_out_by_id(valid_init
, id
);
2650 domain
= isl_pw_aff_non_zero_set(pa
);
2652 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
2653 domain
= strided_domain(isl_id_copy(id
), init_val
,
2657 domain
= embed(domain
, isl_id_copy(id
));
2660 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2661 rev_wrap
= isl_map_from_aff(isl_aff_copy(wrap
));
2662 rev_wrap
= isl_map_reverse(rev_wrap
);
2663 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
2664 skip
= isl_set_apply(skip
, isl_map_copy(rev_wrap
));
2665 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
2666 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
2668 is_simple
= is_simple_bound(cond
, inc
);
2670 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2671 is_simple
= is_simple_bound(cond
, inc
);
2674 cond
= valid_for_each_iteration(cond
,
2675 isl_set_copy(domain
), isl_val_copy(inc
));
2676 domain
= isl_set_intersect(domain
, cond
);
2677 if (has_affine_break
) {
2678 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2679 skip
= after(skip
, isl_val_sgn(inc
));
2680 domain
= isl_set_subtract(domain
, skip
);
2682 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2683 ls
= isl_local_space_from_space(isl_set_get_space(domain
));
2684 sched
= isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
2685 if (isl_val_is_neg(inc
))
2686 sched
= isl_aff_neg(sched
);
2688 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
),
2690 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
2693 wrap
= identity_aff(domain
);
2695 scop_cond
= pet_scop_embed(scop_cond
, isl_set_copy(domain
),
2696 isl_aff_copy(sched
), isl_aff_copy(wrap
), isl_id_copy(id
));
2697 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), sched
, wrap
, id
);
2698 scop
= resolve_nested(scop
);
2700 scop
= scop_add_break(scop
, id_break_test
, isl_set_copy(domain
),
2703 scop
= scop_add_while(scop_cond
, scop
, id_test
, domain
,
2705 isl_set_free(valid_inc
);
2707 scop
= pet_scop_restrict_context(scop
, valid_inc
);
2708 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
2709 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
2710 isl_set_free(domain
);
2712 clear_assignment(assigned_value
, iv
);
2716 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid_init
));
2721 /* Try and construct a pet_scop corresponding to a compound statement.
2723 * "skip_declarations" is set if we should skip initial declarations
2724 * in the children of the compound statements. This then implies
2725 * that this sequence of children should not be treated as a block
2726 * since the initial statements may be skipped.
2728 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
, bool skip_declarations
)
2730 return extract(stmt
->children(), !skip_declarations
, skip_declarations
);
2733 /* For each nested access parameter in "space",
2734 * construct a corresponding pet_expr, place it in args and
2735 * record its position in "param2pos".
2736 * "n_arg" is the number of elements that are already in args.
2737 * The position recorded in "param2pos" takes this number into account.
2738 * If the pet_expr corresponding to a parameter is identical to
2739 * the pet_expr corresponding to an earlier parameter, then these two
2740 * parameters are made to refer to the same element in args.
2742 * Return the final number of elements in args or -1 if an error has occurred.
2744 int PetScan::extract_nested(__isl_keep isl_space
*space
,
2745 int n_arg
, pet_expr
**args
, std::map
<int,int> ¶m2pos
)
2749 nparam
= isl_space_dim(space
, isl_dim_param
);
2750 for (int i
= 0; i
< nparam
; ++i
) {
2752 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2754 if (!pet_nested_in_id(id
)) {
2759 args
[n_arg
] = pet_nested_extract_expr(id
);
2764 for (j
= 0; j
< n_arg
; ++j
)
2765 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
2769 pet_expr_free(args
[n_arg
]);
2773 param2pos
[i
] = n_arg
++;
2779 /* For each nested access parameter in the access relations in "expr",
2780 * construct a corresponding pet_expr, place it in the arguments of "expr"
2781 * and record its position in "param2pos".
2782 * n is the number of nested access parameters.
2784 __isl_give pet_expr
*PetScan::extract_nested(__isl_take pet_expr
*expr
, int n
,
2785 std::map
<int,int> ¶m2pos
)
2791 args
= isl_calloc_array(ctx
, pet_expr
*, n
);
2793 return pet_expr_free(expr
);
2795 space
= pet_expr_access_get_parameter_space(expr
);
2796 n
= extract_nested(space
, 0, args
, param2pos
);
2797 isl_space_free(space
);
2800 expr
= pet_expr_free(expr
);
2802 expr
= pet_expr_set_n_arg(expr
, n
);
2804 for (i
= 0; i
< n
; ++i
)
2805 expr
= pet_expr_set_arg(expr
, i
, args
[i
]);
2811 /* Look for parameters in any access relation in "expr" that
2812 * refer to nested accesses. In particular, these are
2813 * parameters with name "__pet_expr".
2815 * If there are any such parameters, then the domain of the index
2816 * expression and the access relation, which is still [] at this point,
2817 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
2818 * (after identifying identical nested accesses).
2820 * This transformation is performed in several steps.
2821 * We first extract the arguments in extract_nested.
2822 * param2pos maps the original parameter position to the position
2824 * Then we move these parameters to input dimensions.
2825 * t2pos maps the positions of these temporary input dimensions
2826 * to the positions of the corresponding arguments.
2827 * Finally, we express these temporary dimensions in terms of the domain
2828 * [[] -> [t_1,...,t_n]] and precompose index expression and access
2829 * relations with this function.
2831 __isl_give pet_expr
*PetScan::resolve_nested(__isl_take pet_expr
*expr
)
2836 isl_local_space
*ls
;
2839 std::map
<int,int> param2pos
;
2840 std::map
<int,int> t2pos
;
2845 n
= pet_expr_get_n_arg(expr
);
2846 for (int i
= 0; i
< n
; ++i
) {
2848 arg
= pet_expr_get_arg(expr
, i
);
2849 arg
= resolve_nested(arg
);
2850 expr
= pet_expr_set_arg(expr
, i
, arg
);
2853 if (pet_expr_get_type(expr
) != pet_expr_access
)
2856 space
= pet_expr_access_get_parameter_space(expr
);
2857 n
= pet_nested_n_in_space(space
);
2858 isl_space_free(space
);
2862 expr
= extract_nested(expr
, n
, param2pos
);
2866 expr
= pet_expr_access_align_params(expr
);
2871 space
= pet_expr_access_get_parameter_space(expr
);
2872 nparam
= isl_space_dim(space
, isl_dim_param
);
2873 for (int i
= nparam
- 1; i
>= 0; --i
) {
2874 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2875 if (!pet_nested_in_id(id
)) {
2880 expr
= pet_expr_access_move_dims(expr
,
2881 isl_dim_in
, n
, isl_dim_param
, i
, 1);
2882 t2pos
[n
] = param2pos
[i
];
2887 isl_space_free(space
);
2889 space
= pet_expr_access_get_parameter_space(expr
);
2890 space
= isl_space_set_from_params(space
);
2891 space
= isl_space_add_dims(space
, isl_dim_set
,
2892 pet_expr_get_n_arg(expr
));
2893 space
= isl_space_wrap(isl_space_from_range(space
));
2894 ls
= isl_local_space_from_space(isl_space_copy(space
));
2895 space
= isl_space_from_domain(space
);
2896 space
= isl_space_add_dims(space
, isl_dim_out
, n
);
2897 ma
= isl_multi_aff_zero(space
);
2899 for (int i
= 0; i
< n
; ++i
) {
2900 aff
= isl_aff_var_on_domain(isl_local_space_copy(ls
),
2901 isl_dim_set
, t2pos
[i
]);
2902 ma
= isl_multi_aff_set_aff(ma
, i
, aff
);
2904 isl_local_space_free(ls
);
2906 expr
= pet_expr_access_pullback_multi_aff(expr
, ma
);
2911 /* Return the file offset of the expansion location of "Loc".
2913 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
2915 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
2918 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
2920 /* Return a SourceLocation for the location after the first semicolon
2921 * after "loc". If Lexer::findLocationAfterToken is available, we simply
2922 * call it and also skip trailing spaces and newline.
2924 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
2925 const LangOptions
&LO
)
2927 return Lexer::findLocationAfterToken(loc
, tok::semi
, SM
, LO
, true);
2932 /* Return a SourceLocation for the location after the first semicolon
2933 * after "loc". If Lexer::findLocationAfterToken is not available,
2934 * we look in the underlying character data for the first semicolon.
2936 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
2937 const LangOptions
&LO
)
2940 const char *s
= SM
.getCharacterData(loc
);
2942 semi
= strchr(s
, ';');
2944 return SourceLocation();
2945 return loc
.getFileLocWithOffset(semi
+ 1 - s
);
2950 /* If the token at "loc" is the first token on the line, then return
2951 * a location referring to the start of the line.
2952 * Otherwise, return "loc".
2954 * This function is used to extend a scop to the start of the line
2955 * if the first token of the scop is also the first token on the line.
2957 * We look for the first token on the line. If its location is equal to "loc",
2958 * then the latter is the location of the first token on the line.
2960 static SourceLocation
move_to_start_of_line_if_first_token(SourceLocation loc
,
2961 SourceManager
&SM
, const LangOptions
&LO
)
2963 std::pair
<FileID
, unsigned> file_offset_pair
;
2964 llvm::StringRef file
;
2967 SourceLocation token_loc
, line_loc
;
2970 loc
= SM
.getExpansionLoc(loc
);
2971 col
= SM
.getExpansionColumnNumber(loc
);
2972 line_loc
= loc
.getLocWithOffset(1 - col
);
2973 file_offset_pair
= SM
.getDecomposedLoc(line_loc
);
2974 file
= SM
.getBufferData(file_offset_pair
.first
, NULL
);
2975 pos
= file
.data() + file_offset_pair
.second
;
2977 Lexer
lexer(SM
.getLocForStartOfFile(file_offset_pair
.first
), LO
,
2978 file
.begin(), pos
, file
.end());
2979 lexer
.LexFromRawLexer(tok
);
2980 token_loc
= tok
.getLocation();
2982 if (token_loc
== loc
)
2988 /* Update start and end of "scop" to include the region covered by "range".
2989 * If "skip_semi" is set, then we assume "range" is followed by
2990 * a semicolon and also include this semicolon.
2992 struct pet_scop
*PetScan::update_scop_start_end(struct pet_scop
*scop
,
2993 SourceRange range
, bool skip_semi
)
2995 SourceLocation loc
= range
.getBegin();
2996 SourceManager
&SM
= PP
.getSourceManager();
2997 const LangOptions
&LO
= PP
.getLangOpts();
2998 unsigned start
, end
;
3000 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
);
3001 start
= getExpansionOffset(SM
, loc
);
3002 loc
= range
.getEnd();
3004 loc
= location_after_semi(loc
, SM
, LO
);
3006 loc
= PP
.getLocForEndOfToken(loc
);
3007 end
= getExpansionOffset(SM
, loc
);
3009 scop
= pet_scop_update_start_end(scop
, start
, end
);
3013 /* Convert a top-level pet_expr to a pet_scop with one statement.
3014 * This mainly involves resolving nested expression parameters
3015 * and setting the name of the iteration space.
3016 * The name is given by "label" if it is non-NULL. Otherwise,
3017 * it is of the form S_<n_stmt>.
3018 * start and end of the pet_scop are derived from "range" and "skip_semi".
3019 * In particular, if "skip_semi" is set then the semicolon following "range"
3022 struct pet_scop
*PetScan::extract(__isl_take pet_expr
*expr
, SourceRange range
,
3023 bool skip_semi
, __isl_take isl_id
*label
)
3025 struct pet_stmt
*ps
;
3026 struct pet_scop
*scop
;
3027 SourceLocation loc
= range
.getBegin();
3028 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3030 expr
= resolve_nested(expr
);
3031 ps
= pet_stmt_from_pet_expr(line
, label
, n_stmt
++, expr
);
3032 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3034 scop
= update_scop_start_end(scop
, range
, skip_semi
);
3038 /* Check if we can extract an affine constraint from "expr".
3039 * Return the constraint as an isl_set if we can and NULL otherwise.
3040 * We turn on autodetection so that we won't generate any warnings
3041 * and turn off nesting, so that we won't accept any non-affine constructs.
3043 __isl_give isl_pw_aff
*PetScan::try_extract_affine_condition(Expr
*expr
)
3046 int save_autodetect
= options
->autodetect
;
3047 bool save_nesting
= nesting_enabled
;
3049 options
->autodetect
= 1;
3050 nesting_enabled
= false;
3052 cond
= extract_condition(expr
);
3054 options
->autodetect
= save_autodetect
;
3055 nesting_enabled
= save_nesting
;
3060 /* Check whether "expr" is an affine constraint.
3062 bool PetScan::is_affine_condition(Expr
*expr
)
3066 cond
= try_extract_affine_condition(expr
);
3067 isl_pw_aff_free(cond
);
3069 return cond
!= NULL
;
3072 /* Check if we can extract a condition from "expr".
3073 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3074 * If allow_nested is set, then the condition may involve parameters
3075 * corresponding to nested accesses.
3076 * We turn on autodetection so that we won't generate any warnings.
3078 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
3081 int save_autodetect
= options
->autodetect
;
3082 bool save_nesting
= nesting_enabled
;
3084 options
->autodetect
= 1;
3085 nesting_enabled
= allow_nested
;
3086 cond
= extract_condition(expr
);
3088 options
->autodetect
= save_autodetect
;
3089 nesting_enabled
= save_nesting
;
3094 /* If the top-level expression of "stmt" is an assignment, then
3095 * return that assignment as a BinaryOperator.
3096 * Otherwise return NULL.
3098 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
3100 BinaryOperator
*ass
;
3104 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
3107 ass
= cast
<BinaryOperator
>(stmt
);
3108 if(ass
->getOpcode() != BO_Assign
)
3114 /* Check if the given if statement is a conditional assignement
3115 * with a non-affine condition. If so, construct a pet_scop
3116 * corresponding to this conditional assignment. Otherwise return NULL.
3118 * In particular we check if "stmt" is of the form
3125 * where a is some array or scalar access.
3126 * The constructed pet_scop then corresponds to the expression
3128 * a = condition ? f(...) : g(...)
3130 * All access relations in f(...) are intersected with condition
3131 * while all access relation in g(...) are intersected with the complement.
3133 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
3135 BinaryOperator
*ass_then
, *ass_else
;
3136 pet_expr
*write_then
, *write_else
;
3137 isl_set
*cond
, *comp
;
3138 isl_multi_pw_aff
*index
;
3142 pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
;
3143 bool save_nesting
= nesting_enabled
;
3145 if (!options
->detect_conditional_assignment
)
3148 ass_then
= top_assignment_or_null(stmt
->getThen());
3149 ass_else
= top_assignment_or_null(stmt
->getElse());
3151 if (!ass_then
|| !ass_else
)
3154 if (is_affine_condition(stmt
->getCond()))
3157 write_then
= extract_access_expr(ass_then
->getLHS());
3158 write_else
= extract_access_expr(ass_else
->getLHS());
3160 equal
= pet_expr_is_equal(write_then
, write_else
);
3161 pet_expr_free(write_else
);
3162 if (equal
< 0 || !equal
) {
3163 pet_expr_free(write_then
);
3167 nesting_enabled
= allow_nested
;
3168 pa
= extract_condition(stmt
->getCond());
3169 nesting_enabled
= save_nesting
;
3170 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
3171 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
3172 index
= isl_multi_pw_aff_from_pw_aff(pa
);
3174 pe_cond
= pet_expr_from_index(index
);
3176 pe_then
= extract_expr(ass_then
->getRHS());
3177 pe_then
= pet_expr_restrict(pe_then
, cond
);
3178 pe_else
= extract_expr(ass_else
->getRHS());
3179 pe_else
= pet_expr_restrict(pe_else
, comp
);
3181 pe
= pet_expr_new_ternary(pe_cond
, pe_then
, pe_else
);
3182 write_then
= pet_expr_access_set_write(write_then
, 1);
3183 write_then
= pet_expr_access_set_read(write_then
, 0);
3184 type_size
= get_type_size(ass_then
->getType(), ast_context
);
3185 pe
= pet_expr_new_binary(type_size
, pet_op_assign
, write_then
, pe
);
3186 return extract(pe
, stmt
->getSourceRange(), false);
3189 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3190 * evaluating "cond" and writing the result to a virtual scalar,
3191 * as expressed by "index".
3193 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
, int stmt_nr
,
3194 __isl_take isl_multi_pw_aff
*index
)
3196 pet_expr
*expr
, *write
;
3197 struct pet_stmt
*ps
;
3198 SourceLocation loc
= cond
->getLocStart();
3199 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3201 write
= pet_expr_from_index(index
);
3202 write
= pet_expr_access_set_write(write
, 1);
3203 write
= pet_expr_access_set_read(write
, 0);
3204 expr
= extract_expr(cond
);
3205 expr
= resolve_nested(expr
);
3206 expr
= pet_expr_new_binary(1, pet_op_assign
, write
, expr
);
3207 ps
= pet_stmt_from_pet_expr(line
, NULL
, stmt_nr
, expr
);
3208 return pet_scop_from_pet_stmt(ctx
, ps
);
3212 static __isl_give pet_expr
*embed_access(__isl_take pet_expr
*expr
,
3216 /* Precompose the access relation and the index expression associated
3217 * to "expr" with the function pointed to by "user",
3218 * thereby embedding the access relation in the domain of this function.
3219 * The initial domain of the access relation and the index expression
3220 * is the zero-dimensional domain.
3222 static __isl_give pet_expr
*embed_access(__isl_take pet_expr
*expr
, void *user
)
3224 isl_multi_aff
*ma
= (isl_multi_aff
*) user
;
3226 return pet_expr_access_pullback_multi_aff(expr
, isl_multi_aff_copy(ma
));
3229 /* Precompose all access relations in "expr" with "ma", thereby
3230 * embedding them in the domain of "ma".
3232 static __isl_give pet_expr
*embed(__isl_take pet_expr
*expr
,
3233 __isl_keep isl_multi_aff
*ma
)
3235 return pet_expr_map_access(expr
, &embed_access
, ma
);
3238 /* For each nested access parameter in the domain of "stmt",
3239 * construct a corresponding pet_expr, place it before the original
3240 * elements in stmt->args and record its position in "param2pos".
3241 * n is the number of nested access parameters.
3243 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
3244 std::map
<int,int> ¶m2pos
)
3251 n_arg
= stmt
->n_arg
;
3252 args
= isl_calloc_array(ctx
, pet_expr
*, n
+ n_arg
);
3256 space
= isl_set_get_space(stmt
->domain
);
3257 n_arg
= extract_nested(space
, 0, args
, param2pos
);
3258 isl_space_free(space
);
3263 for (i
= 0; i
< stmt
->n_arg
; ++i
)
3264 args
[n_arg
+ i
] = stmt
->args
[i
];
3267 stmt
->n_arg
+= n_arg
;
3272 for (i
= 0; i
< n
; ++i
)
3273 pet_expr_free(args
[i
]);
3276 pet_stmt_free(stmt
);
3280 /* Check whether any of the arguments i of "stmt" starting at position "n"
3281 * is equal to one of the first "n" arguments j.
3282 * If so, combine the constraints on arguments i and j and remove
3285 static struct pet_stmt
*remove_duplicate_arguments(struct pet_stmt
*stmt
, int n
)
3294 if (n
== stmt
->n_arg
)
3297 map
= isl_set_unwrap(stmt
->domain
);
3299 for (i
= stmt
->n_arg
- 1; i
>= n
; --i
) {
3300 for (j
= 0; j
< n
; ++j
)
3301 if (pet_expr_is_equal(stmt
->args
[i
], stmt
->args
[j
]))
3306 map
= isl_map_equate(map
, isl_dim_out
, i
, isl_dim_out
, j
);
3307 map
= isl_map_project_out(map
, isl_dim_out
, i
, 1);
3309 pet_expr_free(stmt
->args
[i
]);
3310 for (j
= i
; j
+ 1 < stmt
->n_arg
; ++j
)
3311 stmt
->args
[j
] = stmt
->args
[j
+ 1];
3315 stmt
->domain
= isl_map_wrap(map
);
3320 pet_stmt_free(stmt
);
3324 /* Look for parameters in the iteration domain of "stmt" that
3325 * refer to nested accesses. In particular, these are
3326 * parameters with name "__pet_expr".
3328 * If there are any such parameters, then as many extra variables
3329 * (after identifying identical nested accesses) are inserted in the
3330 * range of the map wrapped inside the domain, before the original variables.
3331 * If the original domain is not a wrapped map, then a new wrapped
3332 * map is created with zero output dimensions.
3333 * The parameters are then equated to the corresponding output dimensions
3334 * and subsequently projected out, from the iteration domain,
3335 * the schedule and the access relations.
3336 * For each of the output dimensions, a corresponding argument
3337 * expression is inserted. Initially they are created with
3338 * a zero-dimensional domain, so they have to be embedded
3339 * in the current iteration domain.
3340 * param2pos maps the position of the parameter to the position
3341 * of the corresponding output dimension in the wrapped map.
3343 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3351 std::map
<int,int> param2pos
;
3356 n
= pet_nested_n_in_set(stmt
->domain
);
3360 n_arg
= stmt
->n_arg
;
3361 stmt
= extract_nested(stmt
, n
, param2pos
);
3365 n
= stmt
->n_arg
- n_arg
;
3366 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3367 if (isl_set_is_wrapping(stmt
->domain
))
3368 map
= isl_set_unwrap(stmt
->domain
);
3370 map
= isl_map_from_domain(stmt
->domain
);
3371 map
= isl_map_insert_dims(map
, isl_dim_out
, 0, n
);
3373 for (int i
= nparam
- 1; i
>= 0; --i
) {
3376 if (!pet_nested_in_map(map
, i
))
3379 id
= pet_expr_access_get_id(stmt
->args
[param2pos
[i
]]);
3380 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3381 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3383 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3386 stmt
->domain
= isl_map_wrap(map
);
3388 space
= isl_space_unwrap(isl_set_get_space(stmt
->domain
));
3389 space
= isl_space_from_domain(isl_space_domain(space
));
3390 ma
= isl_multi_aff_zero(space
);
3391 for (int pos
= 0; pos
< n
; ++pos
)
3392 stmt
->args
[pos
] = embed(stmt
->args
[pos
], ma
);
3393 isl_multi_aff_free(ma
);
3395 stmt
= pet_stmt_remove_nested_parameters(stmt
);
3396 stmt
= remove_duplicate_arguments(stmt
, n
);
3401 /* For each statement in "scop", move the parameters that correspond
3402 * to nested access into the ranges of the domains and create
3403 * corresponding argument expressions.
3405 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3410 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3411 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3412 if (!scop
->stmts
[i
])
3418 pet_scop_free(scop
);
3422 /* Given an access expression "expr", is the variable accessed by
3423 * "expr" assigned anywhere inside "scop"?
3425 static bool is_assigned(__isl_keep pet_expr
*expr
, pet_scop
*scop
)
3427 bool assigned
= false;
3430 id
= pet_expr_access_get_id(expr
);
3431 assigned
= pet_scop_writes(scop
, id
);
3437 /* Are all nested access parameters in "pa" allowed given "scop".
3438 * In particular, is none of them written by anywhere inside "scop".
3440 * If "scop" has any skip conditions, then no nested access parameters
3441 * are allowed. In particular, if there is any nested access in a guard
3442 * for a piece of code containing a "continue", then we want to introduce
3443 * a separate statement for evaluating this guard so that we can express
3444 * that the result is false for all previous iterations.
3446 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3453 if (!pet_nested_any_in_pw_aff(pa
))
3456 if (pet_scop_has_skip(scop
, pet_skip_now
))
3459 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3460 for (int i
= 0; i
< nparam
; ++i
) {
3461 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3465 if (!pet_nested_in_id(id
)) {
3470 expr
= pet_nested_extract_expr(id
);
3471 allowed
= pet_expr_get_type(expr
) == pet_expr_access
&&
3472 !is_assigned(expr
, scop
);
3474 pet_expr_free(expr
);
3484 /* Construct a pet_scop for a non-affine if statement.
3486 * We create a separate statement that writes the result
3487 * of the non-affine condition to a virtual scalar.
3488 * A constraint requiring the value of this virtual scalar to be one
3489 * is added to the iteration domains of the then branch.
3490 * Similarly, a constraint requiring the value of this virtual scalar
3491 * to be zero is added to the iteration domains of the else branch, if any.
3492 * We adjust the schedules to ensure that the virtual scalar is written
3493 * before it is read.
3495 * If there are any breaks or continues in the then and/or else
3496 * branches, then we may have to compute a new skip condition.
3497 * This is handled using a pet_skip_info object.
3498 * On initialization, the object checks if skip conditions need
3499 * to be computed. If so, it does so in pet_skip_info_if_extract_index and
3500 * adds them in pet_skip_info_if_add.
3502 struct pet_scop
*PetScan::extract_non_affine_if(Expr
*cond
,
3503 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3504 bool have_else
, int stmt_id
)
3506 struct pet_scop
*scop
;
3507 isl_multi_pw_aff
*test_index
;
3509 int save_n_stmt
= n_stmt
;
3511 test_index
= pet_create_test_index(ctx
, n_test
++);
3513 scop
= extract_non_affine_condition(cond
, n_stmt
++,
3514 isl_multi_pw_aff_copy(test_index
));
3515 n_stmt
= save_n_stmt
;
3516 scop
= scop_add_array(scop
, test_index
, ast_context
);
3519 pet_skip_info_if_init(&skip
, ctx
, scop_then
, scop_else
, have_else
, 0);
3520 int_size
= ast_context
.getTypeInfo(ast_context
.IntTy
).first
/ 8;
3521 pet_skip_info_if_extract_index(&skip
, test_index
, int_size
,
3524 scop
= pet_scop_prefix(scop
, 0);
3525 scop_then
= pet_scop_prefix(scop_then
, 1);
3526 scop_then
= pet_scop_filter(scop_then
,
3527 isl_multi_pw_aff_copy(test_index
), 1);
3529 scop_else
= pet_scop_prefix(scop_else
, 1);
3530 scop_else
= pet_scop_filter(scop_else
, test_index
, 0);
3531 scop_then
= pet_scop_add_par(ctx
, scop_then
, scop_else
);
3533 isl_multi_pw_aff_free(test_index
);
3535 scop
= pet_scop_add_seq(ctx
, scop
, scop_then
);
3537 scop
= pet_skip_info_if_add(&skip
, scop
, 2);
3542 /* Construct a pet_scop for an if statement.
3544 * If the condition fits the pattern of a conditional assignment,
3545 * then it is handled by extract_conditional_assignment.
3546 * Otherwise, we do the following.
3548 * If the condition is affine, then the condition is added
3549 * to the iteration domains of the then branch, while the
3550 * opposite of the condition in added to the iteration domains
3551 * of the else branch, if any.
3552 * We allow the condition to be dynamic, i.e., to refer to
3553 * scalars or array elements that may be written to outside
3554 * of the given if statement. These nested accesses are then represented
3555 * as output dimensions in the wrapping iteration domain.
3556 * If it is also written _inside_ the then or else branch, then
3557 * we treat the condition as non-affine.
3558 * As explained in extract_non_affine_if, this will introduce
3559 * an extra statement.
3560 * For aesthetic reasons, we want this statement to have a statement
3561 * number that is lower than those of the then and else branches.
3562 * In order to evaluate if we will need such a statement, however, we
3563 * first construct scops for the then and else branches.
3564 * We therefore reserve a statement number if we might have to
3565 * introduce such an extra statement.
3567 * If the condition is not affine, then the scop is created in
3568 * extract_non_affine_if.
3570 * If there are any breaks or continues in the then and/or else
3571 * branches, then we may have to compute a new skip condition.
3572 * This is handled using a pet_skip_info object.
3573 * On initialization, the object checks if skip conditions need
3574 * to be computed. If so, it does so in pet_skip_info_if_extract_cond and
3575 * adds them in pet_skip_info_if_add.
3577 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
3579 struct pet_scop
*scop_then
, *scop_else
= NULL
, *scop
;
3586 clear_assignments
clear(assigned_value
);
3587 clear
.TraverseStmt(stmt
->getThen());
3588 if (stmt
->getElse())
3589 clear
.TraverseStmt(stmt
->getElse());
3591 scop
= extract_conditional_assignment(stmt
);
3595 cond
= try_extract_nested_condition(stmt
->getCond());
3596 if (allow_nested
&& (!cond
|| pet_nested_any_in_pw_aff(cond
)))
3600 assigned_value_cache
cache(assigned_value
);
3601 scop_then
= extract(stmt
->getThen());
3604 if (stmt
->getElse()) {
3605 assigned_value_cache
cache(assigned_value
);
3606 scop_else
= extract(stmt
->getElse());
3607 if (options
->autodetect
) {
3608 if (scop_then
&& !scop_else
) {
3610 isl_pw_aff_free(cond
);
3613 if (!scop_then
&& scop_else
) {
3615 isl_pw_aff_free(cond
);
3622 (!is_nested_allowed(cond
, scop_then
) ||
3623 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
3624 isl_pw_aff_free(cond
);
3627 if (allow_nested
&& !cond
)
3628 return extract_non_affine_if(stmt
->getCond(), scop_then
,
3629 scop_else
, stmt
->getElse(), stmt_id
);
3632 cond
= extract_condition(stmt
->getCond());
3635 pet_skip_info_if_init(&skip
, ctx
, scop_then
, scop_else
,
3636 stmt
->getElse() != NULL
, 1);
3637 pet_skip_info_if_extract_cond(&skip
, cond
, int_size
, &n_stmt
, &n_test
);
3639 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
3640 set
= isl_pw_aff_non_zero_set(cond
);
3641 scop
= pet_scop_restrict(scop_then
, isl_set_params(isl_set_copy(set
)));
3643 if (stmt
->getElse()) {
3644 set
= isl_set_subtract(isl_set_copy(valid
), set
);
3645 scop_else
= pet_scop_restrict(scop_else
, isl_set_params(set
));
3646 scop
= pet_scop_add_par(ctx
, scop
, scop_else
);
3649 scop
= resolve_nested(scop
);
3650 scop
= pet_scop_restrict_context(scop
, isl_set_params(valid
));
3652 if (pet_skip_info_has_skip(&skip
))
3653 scop
= pet_scop_prefix(scop
, 0);
3654 scop
= pet_skip_info_if_add(&skip
, scop
, 1);
3659 /* Try and construct a pet_scop for a label statement.
3660 * We currently only allow labels on expression statements.
3662 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
3667 sub
= stmt
->getSubStmt();
3668 if (!isa
<Expr
>(sub
)) {
3673 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
3675 return extract(extract_expr(cast
<Expr
>(sub
)), stmt
->getSourceRange(),
3679 /* Return a one-dimensional multi piecewise affine expression that is equal
3680 * to the constant 1 and is defined over a zero-dimensional domain.
3682 static __isl_give isl_multi_pw_aff
*one_mpa(isl_ctx
*ctx
)
3685 isl_local_space
*ls
;
3688 space
= isl_space_set_alloc(ctx
, 0, 0);
3689 ls
= isl_local_space_from_space(space
);
3690 aff
= isl_aff_zero_on_domain(ls
);
3691 aff
= isl_aff_set_constant_si(aff
, 1);
3693 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
3696 /* Construct a pet_scop for a continue statement.
3698 * We simply create an empty scop with a universal pet_skip_now
3699 * skip condition. This skip condition will then be taken into
3700 * account by the enclosing loop construct, possibly after
3701 * being incorporated into outer skip conditions.
3703 struct pet_scop
*PetScan::extract(ContinueStmt
*stmt
)
3707 scop
= pet_scop_empty(ctx
);
3711 scop
= pet_scop_set_skip(scop
, pet_skip_now
, one_mpa(ctx
));
3716 /* Construct a pet_scop for a break statement.
3718 * We simply create an empty scop with both a universal pet_skip_now
3719 * skip condition and a universal pet_skip_later skip condition.
3720 * These skip conditions will then be taken into
3721 * account by the enclosing loop construct, possibly after
3722 * being incorporated into outer skip conditions.
3724 struct pet_scop
*PetScan::extract(BreakStmt
*stmt
)
3727 isl_multi_pw_aff
*skip
;
3729 scop
= pet_scop_empty(ctx
);
3733 skip
= one_mpa(ctx
);
3734 scop
= pet_scop_set_skip(scop
, pet_skip_now
,
3735 isl_multi_pw_aff_copy(skip
));
3736 scop
= pet_scop_set_skip(scop
, pet_skip_later
, skip
);
3741 /* Try and construct a pet_scop corresponding to "stmt".
3743 * If "stmt" is a compound statement, then "skip_declarations"
3744 * indicates whether we should skip initial declarations in the
3745 * compound statement.
3747 * If the constructed pet_scop is not a (possibly) partial representation
3748 * of "stmt", we update start and end of the pet_scop to those of "stmt".
3749 * In particular, if skip_declarations is set, then we may have skipped
3750 * declarations inside "stmt" and so the pet_scop may not represent
3751 * the entire "stmt".
3752 * Note that this function may be called with "stmt" referring to the entire
3753 * body of the function, including the outer braces. In such cases,
3754 * skip_declarations will be set and the braces will not be taken into
3755 * account in scop->start and scop->end.
3757 struct pet_scop
*PetScan::extract(Stmt
*stmt
, bool skip_declarations
)
3759 struct pet_scop
*scop
;
3761 if (isa
<Expr
>(stmt
))
3762 return extract(extract_expr(cast
<Expr
>(stmt
)),
3763 stmt
->getSourceRange(), true);
3765 switch (stmt
->getStmtClass()) {
3766 case Stmt::WhileStmtClass
:
3767 scop
= extract(cast
<WhileStmt
>(stmt
));
3769 case Stmt::ForStmtClass
:
3770 scop
= extract_for(cast
<ForStmt
>(stmt
));
3772 case Stmt::IfStmtClass
:
3773 scop
= extract(cast
<IfStmt
>(stmt
));
3775 case Stmt::CompoundStmtClass
:
3776 scop
= extract(cast
<CompoundStmt
>(stmt
), skip_declarations
);
3778 case Stmt::LabelStmtClass
:
3779 scop
= extract(cast
<LabelStmt
>(stmt
));
3781 case Stmt::ContinueStmtClass
:
3782 scop
= extract(cast
<ContinueStmt
>(stmt
));
3784 case Stmt::BreakStmtClass
:
3785 scop
= extract(cast
<BreakStmt
>(stmt
));
3787 case Stmt::DeclStmtClass
:
3788 scop
= extract(cast
<DeclStmt
>(stmt
));
3795 if (partial
|| skip_declarations
)
3798 scop
= update_scop_start_end(scop
, stmt
->getSourceRange(), false);
3803 /* Extract a clone of the kill statement in "scop".
3804 * "scop" is expected to have been created from a DeclStmt
3805 * and should have the kill as its first statement.
3807 struct pet_stmt
*PetScan::extract_kill(struct pet_scop
*scop
)
3810 struct pet_stmt
*stmt
;
3811 isl_multi_pw_aff
*index
;
3817 if (scop
->n_stmt
< 1)
3818 isl_die(ctx
, isl_error_internal
,
3819 "expecting at least one statement", return NULL
);
3820 stmt
= scop
->stmts
[0];
3821 if (!pet_stmt_is_kill(stmt
))
3822 isl_die(ctx
, isl_error_internal
,
3823 "expecting kill statement", return NULL
);
3825 arg
= pet_expr_get_arg(stmt
->body
, 0);
3826 index
= pet_expr_access_get_index(arg
);
3827 access
= pet_expr_access_get_access(arg
);
3829 index
= isl_multi_pw_aff_reset_tuple_id(index
, isl_dim_in
);
3830 access
= isl_map_reset_tuple_id(access
, isl_dim_in
);
3831 kill
= pet_expr_kill_from_access_and_index(access
, index
);
3832 return pet_stmt_from_pet_expr(stmt
->line
, NULL
, n_stmt
++, kill
);
3835 /* Mark all arrays in "scop" as being exposed.
3837 static struct pet_scop
*mark_exposed(struct pet_scop
*scop
)
3841 for (int i
= 0; i
< scop
->n_array
; ++i
)
3842 scop
->arrays
[i
]->exposed
= 1;
3846 /* Try and construct a pet_scop corresponding to (part of)
3847 * a sequence of statements.
3849 * "block" is set if the sequence respresents the children of
3850 * a compound statement.
3851 * "skip_declarations" is set if we should skip initial declarations
3852 * in the sequence of statements.
3854 * After extracting a statement, we update "assigned_value"
3855 * based on the top-level assignments in the statement
3856 * so that we can exploit them in subsequent statements in the same block.
3858 * If there are any breaks or continues in the individual statements,
3859 * then we may have to compute a new skip condition.
3860 * This is handled using a pet_skip_info object.
3861 * On initialization, the object checks if skip conditions need
3862 * to be computed. If so, it does so in pet_skip_info_seq_extract and
3863 * adds them in pet_skip_info_seq_add.
3865 * If "block" is set, then we need to insert kill statements at
3866 * the end of the block for any array that has been declared by
3867 * one of the statements in the sequence. Each of these declarations
3868 * results in the construction of a kill statement at the place
3869 * of the declaration, so we simply collect duplicates of
3870 * those kill statements and append these duplicates to the constructed scop.
3872 * If "block" is not set, then any array declared by one of the statements
3873 * in the sequence is marked as being exposed.
3875 * If autodetect is set, then we allow the extraction of only a subrange
3876 * of the sequence of statements. However, if there is at least one statement
3877 * for which we could not construct a scop and the final range contains
3878 * either no statements or at least one kill, then we discard the entire
3881 struct pet_scop
*PetScan::extract(StmtRange stmt_range
, bool block
,
3882 bool skip_declarations
)
3888 bool partial_range
= false;
3889 set
<struct pet_stmt
*> kills
;
3890 set
<struct pet_stmt
*>::iterator it
;
3892 int_size
= ast_context
.getTypeInfo(ast_context
.IntTy
).first
/ 8;
3894 scop
= pet_scop_empty(ctx
);
3895 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
3897 struct pet_scop
*scop_i
;
3899 if (scop
->n_stmt
== 0 && skip_declarations
&&
3900 child
->getStmtClass() == Stmt::DeclStmtClass
)
3903 scop_i
= extract(child
);
3904 if (scop
->n_stmt
!= 0 && partial
) {
3905 pet_scop_free(scop_i
);
3908 handle_writes(scop_i
);
3910 pet_skip_info_seq_init(&skip
, ctx
, scop
, scop_i
);
3911 pet_skip_info_seq_extract(&skip
, int_size
, &n_stmt
, &n_test
);
3912 if (pet_skip_info_has_skip(&skip
))
3913 scop_i
= pet_scop_prefix(scop_i
, 0);
3914 if (scop_i
&& child
->getStmtClass() == Stmt::DeclStmtClass
) {
3916 kills
.insert(extract_kill(scop_i
));
3918 scop_i
= mark_exposed(scop_i
);
3920 scop_i
= pet_scop_prefix(scop_i
, j
);
3921 if (options
->autodetect
) {
3923 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
3925 partial_range
= true;
3926 if (scop
->n_stmt
!= 0 && !scop_i
)
3929 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
3932 scop
= pet_skip_info_seq_add(&skip
, scop
, j
);
3934 if (partial
|| !scop
)
3938 for (it
= kills
.begin(); it
!= kills
.end(); ++it
) {
3940 scop_j
= pet_scop_from_pet_stmt(ctx
, *it
);
3941 scop_j
= pet_scop_prefix(scop_j
, j
);
3942 scop
= pet_scop_add_seq(ctx
, scop
, scop_j
);
3945 if (scop
&& partial_range
) {
3946 if (scop
->n_stmt
== 0 || kills
.size() != 0) {
3947 pet_scop_free(scop
);
3956 /* Check if the scop marked by the user is exactly this Stmt
3957 * or part of this Stmt.
3958 * If so, return a pet_scop corresponding to the marked region.
3959 * Otherwise, return NULL.
3961 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
3963 SourceManager
&SM
= PP
.getSourceManager();
3964 unsigned start_off
, end_off
;
3966 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
3967 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
3969 if (start_off
> loc
.end
)
3971 if (end_off
< loc
.start
)
3973 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
3974 return extract(stmt
);
3978 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
3979 Stmt
*child
= *start
;
3982 start_off
= getExpansionOffset(SM
, child
->getLocStart());
3983 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
3984 if (start_off
< loc
.start
&& end_off
>= loc
.end
)
3986 if (start_off
>= loc
.start
)
3991 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
3993 start_off
= SM
.getFileOffset(child
->getLocStart());
3994 if (start_off
>= loc
.end
)
3998 return extract(StmtRange(start
, end
), false, false);
4001 /* Set the size of index "pos" of "array" to "size".
4002 * In particular, add a constraint of the form
4006 * to array->extent and a constraint of the form
4010 * to array->context.
4012 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
4013 __isl_take isl_pw_aff
*size
)
4023 valid
= isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
)));
4024 array
->context
= isl_set_intersect(array
->context
, valid
);
4026 dim
= isl_set_get_space(array
->extent
);
4027 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
4028 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
4029 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
4030 index
= isl_pw_aff_alloc(univ
, aff
);
4032 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
4033 isl_set_dim(array
->extent
, isl_dim_set
));
4034 id
= isl_set_get_tuple_id(array
->extent
);
4035 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
4036 bound
= isl_pw_aff_lt_set(index
, size
);
4038 array
->extent
= isl_set_intersect(array
->extent
, bound
);
4040 if (!array
->context
|| !array
->extent
)
4045 pet_array_free(array
);
4049 /* Figure out the size of the array at position "pos" and all
4050 * subsequent positions from "type" and update "array" accordingly.
4052 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
4053 const Type
*type
, int pos
)
4055 const ArrayType
*atype
;
4061 if (type
->isPointerType()) {
4062 type
= type
->getPointeeType().getTypePtr();
4063 return set_upper_bounds(array
, type
, pos
+ 1);
4065 if (!type
->isArrayType())
4068 type
= type
->getCanonicalTypeInternal().getTypePtr();
4069 atype
= cast
<ArrayType
>(type
);
4071 if (type
->isConstantArrayType()) {
4072 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
4073 size
= extract_affine(ca
->getSize());
4074 array
= update_size(array
, pos
, size
);
4075 } else if (type
->isVariableArrayType()) {
4076 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
4077 size
= extract_affine(vla
->getSizeExpr());
4078 array
= update_size(array
, pos
, size
);
4081 type
= atype
->getElementType().getTypePtr();
4083 return set_upper_bounds(array
, type
, pos
+ 1);
4086 /* Is "T" the type of a variable length array with static size?
4088 static bool is_vla_with_static_size(QualType T
)
4090 const VariableArrayType
*vlatype
;
4092 if (!T
->isVariableArrayType())
4094 vlatype
= cast
<VariableArrayType
>(T
);
4095 return vlatype
->getSizeModifier() == VariableArrayType::Static
;
4098 /* Return the type of "decl" as an array.
4100 * In particular, if "decl" is a parameter declaration that
4101 * is a variable length array with a static size, then
4102 * return the original type (i.e., the variable length array).
4103 * Otherwise, return the type of decl.
4105 static QualType
get_array_type(ValueDecl
*decl
)
4110 parm
= dyn_cast
<ParmVarDecl
>(decl
);
4112 return decl
->getType();
4114 T
= parm
->getOriginalType();
4115 if (!is_vla_with_static_size(T
))
4116 return decl
->getType();
4120 /* Does "decl" have definition that we can keep track of in a pet_type?
4122 static bool has_printable_definition(RecordDecl
*decl
)
4124 if (!decl
->getDeclName())
4126 return decl
->getLexicalDeclContext() == decl
->getDeclContext();
4129 /* Construct and return a pet_array corresponding to the variable "decl".
4130 * In particular, initialize array->extent to
4132 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4134 * and then call set_upper_bounds to set the upper bounds on the indices
4135 * based on the type of the variable.
4137 * If the base type is that of a record with a top-level definition and
4138 * if "types" is not null, then the RecordDecl corresponding to the type
4139 * is added to "types".
4141 * If the base type is that of a record with no top-level definition,
4142 * then we replace it by "<subfield>".
4144 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
,
4145 lex_recorddecl_set
*types
)
4147 struct pet_array
*array
;
4148 QualType qt
= get_array_type(decl
);
4149 const Type
*type
= qt
.getTypePtr();
4150 int depth
= array_depth(type
);
4151 QualType base
= pet_clang_base_type(qt
);
4156 array
= isl_calloc_type(ctx
, struct pet_array
);
4160 id
= create_decl_id(ctx
, decl
);
4161 dim
= isl_space_set_alloc(ctx
, 0, depth
);
4162 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
4164 array
->extent
= isl_set_nat_universe(dim
);
4166 dim
= isl_space_params_alloc(ctx
, 0);
4167 array
->context
= isl_set_universe(dim
);
4169 array
= set_upper_bounds(array
, type
, 0);
4173 name
= base
.getAsString();
4175 if (types
&& base
->isRecordType()) {
4176 RecordDecl
*decl
= pet_clang_record_decl(base
);
4177 if (has_printable_definition(decl
))
4178 types
->insert(decl
);
4180 name
= "<subfield>";
4183 array
->element_type
= strdup(name
.c_str());
4184 array
->element_is_record
= base
->isRecordType();
4185 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
4190 /* Construct and return a pet_array corresponding to the sequence
4191 * of declarations "decls".
4192 * If the sequence contains a single declaration, then it corresponds
4193 * to a simple array access. Otherwise, it corresponds to a member access,
4194 * with the declaration for the substructure following that of the containing
4195 * structure in the sequence of declarations.
4196 * We start with the outermost substructure and then combine it with
4197 * information from the inner structures.
4199 * Additionally, keep track of all required types in "types".
4201 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
,
4202 vector
<ValueDecl
*> decls
, lex_recorddecl_set
*types
)
4204 struct pet_array
*array
;
4205 vector
<ValueDecl
*>::iterator it
;
4209 array
= extract_array(ctx
, *it
, types
);
4211 for (++it
; it
!= decls
.end(); ++it
) {
4212 struct pet_array
*parent
;
4213 const char *base_name
, *field_name
;
4217 array
= extract_array(ctx
, *it
, types
);
4219 return pet_array_free(parent
);
4221 base_name
= isl_set_get_tuple_name(parent
->extent
);
4222 field_name
= isl_set_get_tuple_name(array
->extent
);
4223 product_name
= pet_array_member_access_name(ctx
,
4224 base_name
, field_name
);
4226 array
->extent
= isl_set_product(isl_set_copy(parent
->extent
),
4229 array
->extent
= isl_set_set_tuple_name(array
->extent
,
4231 array
->context
= isl_set_intersect(array
->context
,
4232 isl_set_copy(parent
->context
));
4234 pet_array_free(parent
);
4237 if (!array
->extent
|| !array
->context
|| !product_name
)
4238 return pet_array_free(array
);
4244 /* Add a pet_type corresponding to "decl" to "scop, provided
4245 * it is a member of "types" and it has not been added before
4246 * (i.e., it is not a member of "types_done".
4248 * Since we want the user to be able to print the types
4249 * in the order in which they appear in the scop, we need to
4250 * make sure that types of fields in a structure appear before
4251 * that structure. We therefore call ourselves recursively
4252 * on the types of all record subfields.
4254 static struct pet_scop
*add_type(isl_ctx
*ctx
, struct pet_scop
*scop
,
4255 RecordDecl
*decl
, Preprocessor
&PP
, lex_recorddecl_set
&types
,
4256 lex_recorddecl_set
&types_done
)
4259 llvm::raw_string_ostream
S(s
);
4260 RecordDecl::field_iterator it
;
4262 if (types
.find(decl
) == types
.end())
4264 if (types_done
.find(decl
) != types_done
.end())
4267 for (it
= decl
->field_begin(); it
!= decl
->field_end(); ++it
) {
4269 QualType type
= it
->getType();
4271 if (!type
->isRecordType())
4273 record
= pet_clang_record_decl(type
);
4274 scop
= add_type(ctx
, scop
, record
, PP
, types
, types_done
);
4277 if (strlen(decl
->getName().str().c_str()) == 0)
4280 decl
->print(S
, PrintingPolicy(PP
.getLangOpts()));
4283 scop
->types
[scop
->n_type
] = pet_type_alloc(ctx
,
4284 decl
->getName().str().c_str(), s
.c_str());
4285 if (!scop
->types
[scop
->n_type
])
4286 return pet_scop_free(scop
);
4288 types_done
.insert(decl
);
4295 /* Construct a list of pet_arrays, one for each array (or scalar)
4296 * accessed inside "scop", add this list to "scop" and return the result.
4298 * The context of "scop" is updated with the intersection of
4299 * the contexts of all arrays, i.e., constraints on the parameters
4300 * that ensure that the arrays have a valid (non-negative) size.
4302 * If the any of the extracted arrays refers to a member access,
4303 * then also add the required types to "scop".
4305 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
4308 array_desc_set arrays
;
4309 array_desc_set::iterator it
;
4310 lex_recorddecl_set types
;
4311 lex_recorddecl_set types_done
;
4312 lex_recorddecl_set::iterator types_it
;
4314 struct pet_array
**scop_arrays
;
4319 pet_scop_collect_arrays(scop
, arrays
);
4320 if (arrays
.size() == 0)
4323 n_array
= scop
->n_array
;
4325 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
4326 n_array
+ arrays
.size());
4329 scop
->arrays
= scop_arrays
;
4331 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
4332 struct pet_array
*array
;
4333 array
= extract_array(ctx
, *it
, &types
);
4334 scop
->arrays
[n_array
+ i
] = array
;
4335 if (!scop
->arrays
[n_array
+ i
])
4338 scop
->context
= isl_set_intersect(scop
->context
,
4339 isl_set_copy(array
->context
));
4344 if (types
.size() == 0)
4347 scop
->types
= isl_alloc_array(ctx
, struct pet_type
*, types
.size());
4351 for (types_it
= types
.begin(); types_it
!= types
.end(); ++types_it
)
4352 scop
= add_type(ctx
, scop
, *types_it
, PP
, types
, types_done
);
4356 pet_scop_free(scop
);
4360 /* Bound all parameters in scop->context to the possible values
4361 * of the corresponding C variable.
4363 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
4370 n
= isl_set_dim(scop
->context
, isl_dim_param
);
4371 for (int i
= 0; i
< n
; ++i
) {
4375 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
4376 if (pet_nested_in_id(id
)) {
4378 isl_die(isl_set_get_ctx(scop
->context
),
4380 "unresolved nested parameter", goto error
);
4382 decl
= (ValueDecl
*) isl_id_get_user(id
);
4385 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
4393 pet_scop_free(scop
);
4397 /* Construct a pet_scop from the given function.
4399 * If the scop was delimited by scop and endscop pragmas, then we override
4400 * the file offsets by those derived from the pragmas.
4402 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
4407 stmt
= fd
->getBody();
4409 if (options
->autodetect
)
4410 scop
= extract(stmt
, true);
4413 scop
= pet_scop_update_start_end(scop
, loc
.start
, loc
.end
);
4415 scop
= pet_scop_detect_parameter_accesses(scop
);
4416 scop
= scan_arrays(scop
);
4417 scop
= add_parameter_bounds(scop
);
4418 scop
= pet_scop_gist(scop
, value_bounds
);