2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012 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
38 #include <clang/AST/ASTContext.h>
39 #include <clang/AST/ASTDiagnostic.h>
40 #include <clang/AST/Expr.h>
41 #include <clang/AST/RecursiveASTVisitor.h>
44 #include <isl/space.h>
51 #include "scop_plus.h"
56 using namespace clang
;
58 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
59 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
61 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
62 SourceLocation(), var
, false, var
->getInnerLocStart(),
63 var
->getType(), VK_LValue
);
65 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
66 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
68 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
69 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
73 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
75 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
76 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
80 /* Check if the element type corresponding to the given array type
81 * has a const qualifier.
83 static bool const_base(QualType qt
)
85 const Type
*type
= qt
.getTypePtr();
87 if (type
->isPointerType())
88 return const_base(type
->getPointeeType());
89 if (type
->isArrayType()) {
90 const ArrayType
*atype
;
91 type
= type
->getCanonicalTypeInternal().getTypePtr();
92 atype
= cast
<ArrayType
>(type
);
93 return const_base(atype
->getElementType());
96 return qt
.isConstQualified();
99 /* Mark "decl" as having an unknown value in "assigned_value".
101 * If no (known or unknown) value was assigned to "decl" before,
102 * then it may have been treated as a parameter before and may
103 * therefore appear in a value assigned to another variable.
104 * If so, this assignment needs to be turned into an unknown value too.
106 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
109 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
111 it
= assigned_value
.find(decl
);
113 assigned_value
[decl
] = NULL
;
115 if (it
== assigned_value
.end())
118 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
119 isl_pw_aff
*pa
= it
->second
;
120 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
122 for (int i
= 0; i
< nparam
; ++i
) {
125 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
127 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
128 if (isl_id_get_user(id
) == decl
)
135 /* Look for any assignments to scalar variables in part of the parse
136 * tree and set assigned_value to NULL for each of them.
137 * Also reset assigned_value if the address of a scalar variable
138 * is being taken. As an exception, if the address is passed to a function
139 * that is declared to receive a const pointer, then assigned_value is
142 * This ensures that we won't use any previously stored value
143 * in the current subtree and its parents.
145 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
146 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
147 set
<UnaryOperator
*> skip
;
149 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
150 assigned_value(assigned_value
) {}
152 /* Check for "address of" operators whose value is passed
153 * to a const pointer argument and add them to "skip", so that
154 * we can skip them in VisitUnaryOperator.
156 bool VisitCallExpr(CallExpr
*expr
) {
158 fd
= expr
->getDirectCallee();
161 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
162 Expr
*arg
= expr
->getArg(i
);
164 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
165 ImplicitCastExpr
*ice
;
166 ice
= cast
<ImplicitCastExpr
>(arg
);
167 arg
= ice
->getSubExpr();
169 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
171 op
= cast
<UnaryOperator
>(arg
);
172 if (op
->getOpcode() != UO_AddrOf
)
174 if (const_base(fd
->getParamDecl(i
)->getType()))
180 bool VisitUnaryOperator(UnaryOperator
*expr
) {
185 if (expr
->getOpcode() != UO_AddrOf
)
187 if (skip
.find(expr
) != skip
.end())
190 arg
= expr
->getSubExpr();
191 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
193 ref
= cast
<DeclRefExpr
>(arg
);
194 decl
= ref
->getDecl();
195 clear_assignment(assigned_value
, decl
);
199 bool VisitBinaryOperator(BinaryOperator
*expr
) {
204 if (!expr
->isAssignmentOp())
206 lhs
= expr
->getLHS();
207 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
209 ref
= cast
<DeclRefExpr
>(lhs
);
210 decl
= ref
->getDecl();
211 clear_assignment(assigned_value
, decl
);
216 /* Keep a copy of the currently assigned values.
218 * Any variable that is assigned a value inside the current scope
219 * is removed again when we leave the scope (either because it wasn't
220 * stored in the cache or because it has a different value in the cache).
222 struct assigned_value_cache
{
223 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
224 map
<ValueDecl
*, isl_pw_aff
*> cache
;
226 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
227 assigned_value(assigned_value
), cache(assigned_value
) {}
228 ~assigned_value_cache() {
229 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
230 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
233 (cache
.find(it
->first
) != cache
.end() &&
234 cache
[it
->first
] != it
->second
))
235 cache
[it
->first
] = NULL
;
237 assigned_value
= cache
;
241 /* Insert an expression into the collection of expressions,
242 * provided it is not already in there.
243 * The isl_pw_affs are freed in the destructor.
245 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
247 std::set
<isl_pw_aff
*>::iterator it
;
249 if (expressions
.find(expr
) == expressions
.end())
250 expressions
.insert(expr
);
252 isl_pw_aff_free(expr
);
257 std::set
<isl_pw_aff
*>::iterator it
;
259 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
260 isl_pw_aff_free(*it
);
262 isl_union_map_free(value_bounds
);
265 /* Called if we found something we (currently) cannot handle.
266 * We'll provide more informative warnings later.
268 * We only actually complain if autodetect is false.
270 void PetScan::unsupported(Stmt
*stmt
, const char *msg
)
272 if (options
->autodetect
)
275 SourceLocation loc
= stmt
->getLocStart();
276 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
277 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
278 msg
? msg
: "unsupported");
279 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
282 /* Extract an integer from "expr" and store it in "v".
284 int PetScan::extract_int(IntegerLiteral
*expr
, isl_int
*v
)
286 const Type
*type
= expr
->getType().getTypePtr();
287 int is_signed
= type
->hasSignedIntegerRepresentation();
290 int64_t i
= expr
->getValue().getSExtValue();
291 isl_int_set_si(*v
, i
);
293 uint64_t i
= expr
->getValue().getZExtValue();
294 isl_int_set_ui(*v
, i
);
300 /* Extract an integer from "expr" and store it in "v".
301 * Return -1 if "expr" does not (obviously) represent an integer.
303 int PetScan::extract_int(clang::ParenExpr
*expr
, isl_int
*v
)
305 return extract_int(expr
->getSubExpr(), v
);
308 /* Extract an integer from "expr" and store it in "v".
309 * Return -1 if "expr" does not (obviously) represent an integer.
311 int PetScan::extract_int(clang::Expr
*expr
, isl_int
*v
)
313 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
314 return extract_int(cast
<IntegerLiteral
>(expr
), v
);
315 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
316 return extract_int(cast
<ParenExpr
>(expr
), v
);
322 /* Extract an affine expression from the IntegerLiteral "expr".
324 __isl_give isl_pw_aff
*PetScan::extract_affine(IntegerLiteral
*expr
)
326 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
327 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
328 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
329 isl_set
*dom
= isl_set_universe(dim
);
333 extract_int(expr
, &v
);
334 aff
= isl_aff_add_constant(aff
, v
);
337 return isl_pw_aff_alloc(dom
, aff
);
340 /* Extract an affine expression from the APInt "val".
342 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
344 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
345 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
346 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
347 isl_set
*dom
= isl_set_universe(dim
);
351 isl_int_set_ui(v
, val
.getZExtValue());
352 aff
= isl_aff_add_constant(aff
, v
);
355 return isl_pw_aff_alloc(dom
, aff
);
358 __isl_give isl_pw_aff
*PetScan::extract_affine(ImplicitCastExpr
*expr
)
360 return extract_affine(expr
->getSubExpr());
363 static unsigned get_type_size(ValueDecl
*decl
)
365 return decl
->getASTContext().getIntWidth(decl
->getType());
368 /* Bound parameter "pos" of "set" to the possible values of "decl".
370 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
371 unsigned pos
, ValueDecl
*decl
)
378 width
= get_type_size(decl
);
379 if (decl
->getType()->isUnsignedIntegerType()) {
380 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
381 isl_int_set_si(v
, 1);
382 isl_int_mul_2exp(v
, v
, width
);
383 isl_int_sub_ui(v
, v
, 1);
384 set
= isl_set_upper_bound(set
, isl_dim_param
, pos
, v
);
386 isl_int_set_si(v
, 1);
387 isl_int_mul_2exp(v
, v
, width
- 1);
388 isl_int_sub_ui(v
, v
, 1);
389 set
= isl_set_upper_bound(set
, isl_dim_param
, pos
, v
);
391 isl_int_sub_ui(v
, v
, 1);
392 set
= isl_set_lower_bound(set
, isl_dim_param
, pos
, v
);
400 /* Extract an affine expression from the DeclRefExpr "expr".
402 * If the variable has been assigned a value, then we check whether
403 * we know what (affine) value was assigned.
404 * If so, we return this value. Otherwise we convert "expr"
405 * to an extra parameter (provided nesting_enabled is set).
407 * Otherwise, we simply return an expression that is equal
408 * to a parameter corresponding to the referenced variable.
410 __isl_give isl_pw_aff
*PetScan::extract_affine(DeclRefExpr
*expr
)
412 ValueDecl
*decl
= expr
->getDecl();
413 const Type
*type
= decl
->getType().getTypePtr();
419 if (!type
->isIntegerType()) {
424 if (assigned_value
.find(decl
) != assigned_value
.end()) {
425 if (assigned_value
[decl
])
426 return isl_pw_aff_copy(assigned_value
[decl
]);
428 return nested_access(expr
);
431 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
432 dim
= isl_space_params_alloc(ctx
, 1);
434 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
436 dom
= isl_set_universe(isl_space_copy(dim
));
437 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
438 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
440 return isl_pw_aff_alloc(dom
, aff
);
443 /* Extract an affine expression from an integer division operation.
444 * In particular, if "expr" is lhs/rhs, then return
446 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
448 * The second argument (rhs) is required to be a (positive) integer constant.
450 __isl_give isl_pw_aff
*PetScan::extract_affine_div(BinaryOperator
*expr
)
453 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
458 rhs_expr
= expr
->getRHS();
460 if (extract_int(rhs_expr
, &v
) < 0) {
465 lhs
= extract_affine(expr
->getLHS());
466 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
468 lhs
= isl_pw_aff_scale_down(lhs
, v
);
471 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(lhs
));
472 lhs_c
= isl_pw_aff_ceil(lhs
);
473 res
= isl_pw_aff_cond(isl_set_indicator_function(cond
), lhs_f
, lhs_c
);
478 /* Extract an affine expression from a modulo operation.
479 * In particular, if "expr" is lhs/rhs, then return
481 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
483 * The second argument (rhs) is required to be a (positive) integer constant.
485 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
488 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
493 rhs_expr
= expr
->getRHS();
494 if (rhs_expr
->getStmtClass() != Stmt::IntegerLiteralClass
) {
499 lhs
= extract_affine(expr
->getLHS());
500 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
503 extract_int(cast
<IntegerLiteral
>(rhs_expr
), &v
);
504 res
= isl_pw_aff_scale_down(isl_pw_aff_copy(lhs
), v
);
506 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(res
));
507 lhs_c
= isl_pw_aff_ceil(res
);
508 res
= isl_pw_aff_cond(isl_set_indicator_function(cond
), lhs_f
, lhs_c
);
510 res
= isl_pw_aff_scale(res
, v
);
513 res
= isl_pw_aff_sub(lhs
, res
);
518 /* Extract an affine expression from a multiplication operation.
519 * This is only allowed if at least one of the two arguments
520 * is a (piecewise) constant.
522 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
527 lhs
= extract_affine(expr
->getLHS());
528 rhs
= extract_affine(expr
->getRHS());
530 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
531 isl_pw_aff_free(lhs
);
532 isl_pw_aff_free(rhs
);
537 return isl_pw_aff_mul(lhs
, rhs
);
540 /* Extract an affine expression from an addition or subtraction operation.
542 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
547 lhs
= extract_affine(expr
->getLHS());
548 rhs
= extract_affine(expr
->getRHS());
550 switch (expr
->getOpcode()) {
552 return isl_pw_aff_add(lhs
, rhs
);
554 return isl_pw_aff_sub(lhs
, rhs
);
556 isl_pw_aff_free(lhs
);
557 isl_pw_aff_free(rhs
);
567 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
573 isl_int_set_si(mod
, 1);
574 isl_int_mul_2exp(mod
, mod
, width
);
576 pwaff
= isl_pw_aff_mod(pwaff
, mod
);
583 /* Limit the domain of "pwaff" to those elements where the function
586 * 2^{width-1} <= pwaff < 2^{width-1}
588 static __isl_give isl_pw_aff
*avoid_overflow(__isl_take isl_pw_aff
*pwaff
,
592 isl_space
*space
= isl_pw_aff_get_domain_space(pwaff
);
593 isl_local_space
*ls
= isl_local_space_from_space(space
);
599 isl_int_set_si(v
, 1);
600 isl_int_mul_2exp(v
, v
, width
- 1);
602 bound
= isl_aff_zero_on_domain(ls
);
603 bound
= isl_aff_add_constant(bound
, v
);
604 b
= isl_pw_aff_from_aff(bound
);
606 dom
= isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff
), isl_pw_aff_copy(b
));
607 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
609 b
= isl_pw_aff_neg(b
);
610 dom
= isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff
), b
);
611 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
618 /* Handle potential overflows on signed computations.
620 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
621 * the we adjust the domain of "pa" to avoid overflows.
623 __isl_give isl_pw_aff
*PetScan::signed_overflow(__isl_take isl_pw_aff
*pa
,
626 if (options
->signed_overflow
== PET_OVERFLOW_AVOID
)
627 pa
= avoid_overflow(pa
, width
);
632 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
634 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
635 __isl_take isl_set
*dom
)
638 pa
= isl_set_indicator_function(set
);
639 pa
= isl_pw_aff_intersect_domain(pa
, dom
);
643 /* Extract an affine expression from some binary operations.
644 * If the result of the expression is unsigned, then we wrap it
645 * based on the size of the type. Otherwise, we ensure that
646 * no overflow occurs.
648 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
653 switch (expr
->getOpcode()) {
656 res
= extract_affine_add(expr
);
659 res
= extract_affine_div(expr
);
662 res
= extract_affine_mod(expr
);
665 res
= extract_affine_mul(expr
);
675 return extract_condition(expr
);
681 width
= ast_context
.getIntWidth(expr
->getType());
682 if (expr
->getType()->isUnsignedIntegerType())
683 res
= wrap(res
, width
);
685 res
= signed_overflow(res
, width
);
690 /* Extract an affine expression from a negation operation.
692 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
694 if (expr
->getOpcode() == UO_Minus
)
695 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
696 if (expr
->getOpcode() == UO_LNot
)
697 return extract_condition(expr
);
703 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
705 return extract_affine(expr
->getSubExpr());
708 /* Extract an affine expression from some special function calls.
709 * In particular, we handle "min", "max", "ceild" and "floord".
710 * In case of the latter two, the second argument needs to be
711 * a (positive) integer constant.
713 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
717 isl_pw_aff
*aff1
, *aff2
;
719 fd
= expr
->getDirectCallee();
725 name
= fd
->getDeclName().getAsString();
726 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
727 !(expr
->getNumArgs() == 2 && name
== "max") &&
728 !(expr
->getNumArgs() == 2 && name
== "floord") &&
729 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
734 if (name
== "min" || name
== "max") {
735 aff1
= extract_affine(expr
->getArg(0));
736 aff2
= extract_affine(expr
->getArg(1));
739 aff1
= isl_pw_aff_min(aff1
, aff2
);
741 aff1
= isl_pw_aff_max(aff1
, aff2
);
742 } else if (name
== "floord" || name
== "ceild") {
744 Expr
*arg2
= expr
->getArg(1);
746 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
750 aff1
= extract_affine(expr
->getArg(0));
752 extract_int(cast
<IntegerLiteral
>(arg2
), &v
);
753 aff1
= isl_pw_aff_scale_down(aff1
, v
);
755 if (name
== "floord")
756 aff1
= isl_pw_aff_floor(aff1
);
758 aff1
= isl_pw_aff_ceil(aff1
);
767 /* This method is called when we come across an access that is
768 * nested in what is supposed to be an affine expression.
769 * If nesting is allowed, we return a new parameter that corresponds
770 * to this nested access. Otherwise, we simply complain.
772 * Note that we currently don't allow nested accesses themselves
773 * to contain any nested accesses, so we check if we can extract
774 * the access without any nesting and complain if we can't.
776 * The new parameter is resolved in resolve_nested.
778 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
786 if (!nesting_enabled
) {
791 allow_nested
= false;
792 access
= extract_access(expr
);
798 isl_map_free(access
);
800 id
= isl_id_alloc(ctx
, NULL
, expr
);
801 dim
= isl_space_params_alloc(ctx
, 1);
803 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
805 dom
= isl_set_universe(isl_space_copy(dim
));
806 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
807 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
809 return isl_pw_aff_alloc(dom
, aff
);
812 /* Affine expressions are not supposed to contain array accesses,
813 * but if nesting is allowed, we return a parameter corresponding
814 * to the array access.
816 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
818 return nested_access(expr
);
821 /* Extract an affine expression from a conditional operation.
823 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
825 isl_pw_aff
*cond
, *lhs
, *rhs
, *res
;
827 cond
= extract_condition(expr
->getCond());
828 lhs
= extract_affine(expr
->getTrueExpr());
829 rhs
= extract_affine(expr
->getFalseExpr());
831 return isl_pw_aff_cond(cond
, lhs
, rhs
);
834 /* Extract an affine expression, if possible, from "expr".
835 * Otherwise return NULL.
837 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
839 switch (expr
->getStmtClass()) {
840 case Stmt::ImplicitCastExprClass
:
841 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
842 case Stmt::IntegerLiteralClass
:
843 return extract_affine(cast
<IntegerLiteral
>(expr
));
844 case Stmt::DeclRefExprClass
:
845 return extract_affine(cast
<DeclRefExpr
>(expr
));
846 case Stmt::BinaryOperatorClass
:
847 return extract_affine(cast
<BinaryOperator
>(expr
));
848 case Stmt::UnaryOperatorClass
:
849 return extract_affine(cast
<UnaryOperator
>(expr
));
850 case Stmt::ParenExprClass
:
851 return extract_affine(cast
<ParenExpr
>(expr
));
852 case Stmt::CallExprClass
:
853 return extract_affine(cast
<CallExpr
>(expr
));
854 case Stmt::ArraySubscriptExprClass
:
855 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
856 case Stmt::ConditionalOperatorClass
:
857 return extract_affine(cast
<ConditionalOperator
>(expr
));
864 __isl_give isl_map
*PetScan::extract_access(ImplicitCastExpr
*expr
)
866 return extract_access(expr
->getSubExpr());
869 /* Return the depth of an array of the given type.
871 static int array_depth(const Type
*type
)
873 if (type
->isPointerType())
874 return 1 + array_depth(type
->getPointeeType().getTypePtr());
875 if (type
->isArrayType()) {
876 const ArrayType
*atype
;
877 type
= type
->getCanonicalTypeInternal().getTypePtr();
878 atype
= cast
<ArrayType
>(type
);
879 return 1 + array_depth(atype
->getElementType().getTypePtr());
884 /* Return the element type of the given array type.
886 static QualType
base_type(QualType qt
)
888 const Type
*type
= qt
.getTypePtr();
890 if (type
->isPointerType())
891 return base_type(type
->getPointeeType());
892 if (type
->isArrayType()) {
893 const ArrayType
*atype
;
894 type
= type
->getCanonicalTypeInternal().getTypePtr();
895 atype
= cast
<ArrayType
>(type
);
896 return base_type(atype
->getElementType());
901 /* Extract an access relation from a reference to a variable.
902 * If the variable has name "A" and its type corresponds to an
903 * array of depth d, then the returned access relation is of the
906 * { [] -> A[i_1,...,i_d] }
908 __isl_give isl_map
*PetScan::extract_access(DeclRefExpr
*expr
)
910 ValueDecl
*decl
= expr
->getDecl();
911 int depth
= array_depth(decl
->getType().getTypePtr());
912 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
913 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, depth
);
916 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
918 access_rel
= isl_map_universe(dim
);
923 /* Extract an access relation from an integer contant.
924 * If the value of the constant is "v", then the returned access relation
929 __isl_give isl_map
*PetScan::extract_access(IntegerLiteral
*expr
)
931 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr
)));
934 /* Try and extract an access relation from the given Expr.
935 * Return NULL if it doesn't work out.
937 __isl_give isl_map
*PetScan::extract_access(Expr
*expr
)
939 switch (expr
->getStmtClass()) {
940 case Stmt::ImplicitCastExprClass
:
941 return extract_access(cast
<ImplicitCastExpr
>(expr
));
942 case Stmt::DeclRefExprClass
:
943 return extract_access(cast
<DeclRefExpr
>(expr
));
944 case Stmt::ArraySubscriptExprClass
:
945 return extract_access(cast
<ArraySubscriptExpr
>(expr
));
946 case Stmt::IntegerLiteralClass
:
947 return extract_access(cast
<IntegerLiteral
>(expr
));
954 /* Assign the affine expression "index" to the output dimension "pos" of "map",
955 * restrict the domain to those values that result in a non-negative index
956 * and return the result.
958 __isl_give isl_map
*set_index(__isl_take isl_map
*map
, int pos
,
959 __isl_take isl_pw_aff
*index
)
962 int len
= isl_map_dim(map
, isl_dim_out
);
966 domain
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(index
));
967 index
= isl_pw_aff_intersect_domain(index
, domain
);
968 index_map
= isl_map_from_range(isl_set_from_pw_aff(index
));
969 index_map
= isl_map_insert_dims(index_map
, isl_dim_out
, 0, pos
);
970 index_map
= isl_map_add_dims(index_map
, isl_dim_out
, len
- pos
- 1);
971 id
= isl_map_get_tuple_id(map
, isl_dim_out
);
972 index_map
= isl_map_set_tuple_id(index_map
, isl_dim_out
, id
);
974 map
= isl_map_intersect(map
, index_map
);
979 /* Extract an access relation from the given array subscript expression.
980 * If nesting is allowed in general, then we turn it on while
981 * examining the index expression.
983 * We first extract an access relation from the base.
984 * This will result in an access relation with a range that corresponds
985 * to the array being accessed and with earlier indices filled in already.
986 * We then extract the current index and fill that in as well.
987 * The position of the current index is based on the type of base.
988 * If base is the actual array variable, then the depth of this type
989 * will be the same as the depth of the array and we will fill in
990 * the first array index.
991 * Otherwise, the depth of the base type will be smaller and we will fill
994 __isl_give isl_map
*PetScan::extract_access(ArraySubscriptExpr
*expr
)
996 Expr
*base
= expr
->getBase();
997 Expr
*idx
= expr
->getIdx();
999 isl_map
*base_access
;
1001 int depth
= array_depth(base
->getType().getTypePtr());
1003 bool save_nesting
= nesting_enabled
;
1005 nesting_enabled
= allow_nested
;
1007 base_access
= extract_access(base
);
1008 index
= extract_affine(idx
);
1010 nesting_enabled
= save_nesting
;
1012 pos
= isl_map_dim(base_access
, isl_dim_out
) - depth
;
1013 access
= set_index(base_access
, pos
, index
);
1018 /* Check if "expr" calls function "minmax" with two arguments and if so
1019 * make lhs and rhs refer to these two arguments.
1021 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
1027 if (expr
->getStmtClass() != Stmt::CallExprClass
)
1030 call
= cast
<CallExpr
>(expr
);
1031 fd
= call
->getDirectCallee();
1035 if (call
->getNumArgs() != 2)
1038 name
= fd
->getDeclName().getAsString();
1042 lhs
= call
->getArg(0);
1043 rhs
= call
->getArg(1);
1048 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1049 * lhs and rhs refer to the two arguments.
1051 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1053 return is_minmax(expr
, "min", lhs
, rhs
);
1056 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1057 * lhs and rhs refer to the two arguments.
1059 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1061 return is_minmax(expr
, "max", lhs
, rhs
);
1064 /* Return "lhs && rhs", defined on the shared definition domain.
1066 static __isl_give isl_pw_aff
*pw_aff_and(__isl_take isl_pw_aff
*lhs
,
1067 __isl_take isl_pw_aff
*rhs
)
1072 dom
= isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs
)),
1073 isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1074 cond
= isl_set_intersect(isl_pw_aff_non_zero_set(lhs
),
1075 isl_pw_aff_non_zero_set(rhs
));
1076 return indicator_function(cond
, dom
);
1079 /* Return "lhs && rhs", with shortcut semantics.
1080 * That is, if lhs is false, then the result is defined even if rhs is not.
1081 * In practice, we compute lhs ? rhs : lhs.
1083 static __isl_give isl_pw_aff
*pw_aff_and_then(__isl_take isl_pw_aff
*lhs
,
1084 __isl_take isl_pw_aff
*rhs
)
1086 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), rhs
, lhs
);
1089 /* Return "lhs || rhs", with shortcut semantics.
1090 * That is, if lhs is true, then the result is defined even if rhs is not.
1091 * In practice, we compute lhs ? lhs : rhs.
1093 static __isl_give isl_pw_aff
*pw_aff_or_else(__isl_take isl_pw_aff
*lhs
,
1094 __isl_take isl_pw_aff
*rhs
)
1096 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), lhs
, rhs
);
1099 /* Extract an affine expressions representing the comparison "LHS op RHS"
1100 * "comp" is the original statement that "LHS op RHS" is derived from
1101 * and is used for diagnostics.
1103 * If the comparison is of the form
1107 * then the expression is constructed as the conjunction of
1112 * A similar optimization is performed for max(a,b) <= c.
1113 * We do this because that will lead to simpler representations
1114 * of the expression.
1115 * If isl is ever enhanced to explicitly deal with min and max expressions,
1116 * this optimization can be removed.
1118 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
1119 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
1128 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
1130 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
1132 if (op
== BO_LT
|| op
== BO_LE
) {
1133 Expr
*expr1
, *expr2
;
1134 if (is_min(RHS
, expr1
, expr2
)) {
1135 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
1136 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
1137 return pw_aff_and(lhs
, rhs
);
1139 if (is_max(LHS
, expr1
, expr2
)) {
1140 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
1141 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
1142 return pw_aff_and(lhs
, rhs
);
1146 lhs
= extract_affine(LHS
);
1147 rhs
= extract_affine(RHS
);
1149 dom
= isl_pw_aff_domain(isl_pw_aff_copy(lhs
));
1150 dom
= isl_set_intersect(dom
, isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1154 cond
= isl_pw_aff_lt_set(lhs
, rhs
);
1157 cond
= isl_pw_aff_le_set(lhs
, rhs
);
1160 cond
= isl_pw_aff_eq_set(lhs
, rhs
);
1163 cond
= isl_pw_aff_ne_set(lhs
, rhs
);
1166 isl_pw_aff_free(lhs
);
1167 isl_pw_aff_free(rhs
);
1173 cond
= isl_set_coalesce(cond
);
1174 res
= indicator_function(cond
, dom
);
1179 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
1181 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1182 comp
->getRHS(), comp
);
1185 /* Extract an affine expression representing the negation (logical not)
1186 * of a subexpression.
1188 __isl_give isl_pw_aff
*PetScan::extract_boolean(UnaryOperator
*op
)
1190 isl_set
*set_cond
, *dom
;
1191 isl_pw_aff
*cond
, *res
;
1193 cond
= extract_condition(op
->getSubExpr());
1195 dom
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
1197 set_cond
= isl_pw_aff_zero_set(cond
);
1199 res
= indicator_function(set_cond
, dom
);
1204 /* Extract an affine expression representing the disjunction (logical or)
1205 * or conjunction (logical and) of two subexpressions.
1207 __isl_give isl_pw_aff
*PetScan::extract_boolean(BinaryOperator
*comp
)
1209 isl_pw_aff
*lhs
, *rhs
;
1211 lhs
= extract_condition(comp
->getLHS());
1212 rhs
= extract_condition(comp
->getRHS());
1214 switch (comp
->getOpcode()) {
1216 return pw_aff_and_then(lhs
, rhs
);
1218 return pw_aff_or_else(lhs
, rhs
);
1220 isl_pw_aff_free(lhs
);
1221 isl_pw_aff_free(rhs
);
1228 __isl_give isl_pw_aff
*PetScan::extract_condition(UnaryOperator
*expr
)
1230 switch (expr
->getOpcode()) {
1232 return extract_boolean(expr
);
1239 /* Extract the affine expression "expr != 0 ? 1 : 0".
1241 __isl_give isl_pw_aff
*PetScan::extract_implicit_condition(Expr
*expr
)
1246 res
= extract_affine(expr
);
1248 dom
= isl_pw_aff_domain(isl_pw_aff_copy(res
));
1249 set
= isl_pw_aff_non_zero_set(res
);
1251 res
= indicator_function(set
, dom
);
1256 /* Extract an affine expression from a boolean expression.
1257 * In particular, return the expression "expr ? 1 : 0".
1259 * If the expression doesn't look like a condition, we assume it
1260 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1262 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
1264 BinaryOperator
*comp
;
1267 isl_set
*u
= isl_set_universe(isl_space_params_alloc(ctx
, 0));
1268 return indicator_function(u
, isl_set_copy(u
));
1271 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1272 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1274 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1275 return extract_condition(cast
<UnaryOperator
>(expr
));
1277 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1278 return extract_implicit_condition(expr
);
1280 comp
= cast
<BinaryOperator
>(expr
);
1281 switch (comp
->getOpcode()) {
1288 return extract_comparison(comp
);
1291 return extract_boolean(comp
);
1293 return extract_implicit_condition(expr
);
1297 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
1301 return pet_op_minus
;
1303 return pet_op_post_inc
;
1305 return pet_op_post_dec
;
1307 return pet_op_pre_inc
;
1309 return pet_op_pre_dec
;
1315 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
1319 return pet_op_add_assign
;
1321 return pet_op_sub_assign
;
1323 return pet_op_mul_assign
;
1325 return pet_op_div_assign
;
1327 return pet_op_assign
;
1349 /* Construct a pet_expr representing a unary operator expression.
1351 struct pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1353 struct pet_expr
*arg
;
1354 enum pet_op_type op
;
1356 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1357 if (op
== pet_op_last
) {
1362 arg
= extract_expr(expr
->getSubExpr());
1364 if (expr
->isIncrementDecrementOp() &&
1365 arg
&& arg
->type
== pet_expr_access
) {
1370 return pet_expr_new_unary(ctx
, op
, arg
);
1373 /* Mark the given access pet_expr as a write.
1374 * If a scalar is being accessed, then mark its value
1375 * as unknown in assigned_value.
1377 void PetScan::mark_write(struct pet_expr
*access
)
1382 access
->acc
.write
= 1;
1383 access
->acc
.read
= 0;
1385 if (isl_map_dim(access
->acc
.access
, isl_dim_out
) != 0)
1388 id
= isl_map_get_tuple_id(access
->acc
.access
, isl_dim_out
);
1389 decl
= (ValueDecl
*) isl_id_get_user(id
);
1390 clear_assignment(assigned_value
, decl
);
1394 /* Construct a pet_expr representing a binary operator expression.
1396 * If the top level operator is an assignment and the LHS is an access,
1397 * then we mark that access as a write. If the operator is a compound
1398 * assignment, the access is marked as both a read and a write.
1400 * If "expr" assigns something to a scalar variable, then we mark
1401 * the variable as having been assigned. If, furthermore, the expression
1402 * is affine, then keep track of this value in assigned_value
1403 * so that we can plug it in when we later come across the same variable.
1405 struct pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1407 struct pet_expr
*lhs
, *rhs
;
1408 enum pet_op_type op
;
1410 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1411 if (op
== pet_op_last
) {
1416 lhs
= extract_expr(expr
->getLHS());
1417 rhs
= extract_expr(expr
->getRHS());
1419 if (expr
->isAssignmentOp() && lhs
&& lhs
->type
== pet_expr_access
) {
1421 if (expr
->isCompoundAssignmentOp())
1425 if (expr
->getOpcode() == BO_Assign
&&
1426 lhs
&& lhs
->type
== pet_expr_access
&&
1427 isl_map_dim(lhs
->acc
.access
, isl_dim_out
) == 0) {
1428 isl_id
*id
= isl_map_get_tuple_id(lhs
->acc
.access
, isl_dim_out
);
1429 ValueDecl
*decl
= (ValueDecl
*) isl_id_get_user(id
);
1430 Expr
*rhs
= expr
->getRHS();
1431 isl_pw_aff
*pa
= try_extract_affine(rhs
);
1432 clear_assignment(assigned_value
, decl
);
1434 assigned_value
[decl
] = pa
;
1435 insert_expression(pa
);
1440 return pet_expr_new_binary(ctx
, op
, lhs
, rhs
);
1443 /* Construct a pet_expr representing a conditional operation.
1445 * We first try to extract the condition as an affine expression.
1446 * If that fails, we construct a pet_expr tree representing the condition.
1448 struct pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1450 struct pet_expr
*cond
, *lhs
, *rhs
;
1453 pa
= try_extract_affine(expr
->getCond());
1455 isl_set
*test
= isl_set_from_pw_aff(pa
);
1456 cond
= pet_expr_from_access(isl_map_from_range(test
));
1458 cond
= extract_expr(expr
->getCond());
1459 lhs
= extract_expr(expr
->getTrueExpr());
1460 rhs
= extract_expr(expr
->getFalseExpr());
1462 return pet_expr_new_ternary(ctx
, cond
, lhs
, rhs
);
1465 struct pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1467 return extract_expr(expr
->getSubExpr());
1470 /* Construct a pet_expr representing a floating point value.
1472 struct pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1474 return pet_expr_new_double(ctx
, expr
->getValueAsApproximateDouble());
1477 /* Extract an access relation from "expr" and then convert it into
1480 struct pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1483 struct pet_expr
*pe
;
1485 access
= extract_access(expr
);
1487 pe
= pet_expr_from_access(access
);
1492 struct pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1494 return extract_expr(expr
->getSubExpr());
1497 /* Construct a pet_expr representing a function call.
1499 * If we are passing along a pointer to an array element
1500 * or an entire row or even higher dimensional slice of an array,
1501 * then the function being called may write into the array.
1503 * We assume here that if the function is declared to take a pointer
1504 * to a const type, then the function will perform a read
1505 * and that otherwise, it will perform a write.
1507 struct pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1509 struct pet_expr
*res
= NULL
;
1513 fd
= expr
->getDirectCallee();
1519 name
= fd
->getDeclName().getAsString();
1520 res
= pet_expr_new_call(ctx
, name
.c_str(), expr
->getNumArgs());
1524 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
1525 Expr
*arg
= expr
->getArg(i
);
1529 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1530 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(arg
);
1531 arg
= ice
->getSubExpr();
1533 if (arg
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1534 UnaryOperator
*op
= cast
<UnaryOperator
>(arg
);
1535 if (op
->getOpcode() == UO_AddrOf
) {
1537 arg
= op
->getSubExpr();
1540 res
->args
[i
] = PetScan::extract_expr(arg
);
1541 main_arg
= res
->args
[i
];
1543 res
->args
[i
] = pet_expr_new_unary(ctx
,
1544 pet_op_address_of
, res
->args
[i
]);
1547 if (arg
->getStmtClass() == Stmt::ArraySubscriptExprClass
&&
1548 array_depth(arg
->getType().getTypePtr()) > 0)
1550 if (is_addr
&& main_arg
->type
== pet_expr_access
) {
1552 if (!fd
->hasPrototype()) {
1553 unsupported(expr
, "prototype required");
1556 parm
= fd
->getParamDecl(i
);
1557 if (!const_base(parm
->getType()))
1558 mark_write(main_arg
);
1568 /* Try and onstruct a pet_expr representing "expr".
1570 struct pet_expr
*PetScan::extract_expr(Expr
*expr
)
1572 switch (expr
->getStmtClass()) {
1573 case Stmt::UnaryOperatorClass
:
1574 return extract_expr(cast
<UnaryOperator
>(expr
));
1575 case Stmt::CompoundAssignOperatorClass
:
1576 case Stmt::BinaryOperatorClass
:
1577 return extract_expr(cast
<BinaryOperator
>(expr
));
1578 case Stmt::ImplicitCastExprClass
:
1579 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1580 case Stmt::ArraySubscriptExprClass
:
1581 case Stmt::DeclRefExprClass
:
1582 case Stmt::IntegerLiteralClass
:
1583 return extract_access_expr(expr
);
1584 case Stmt::FloatingLiteralClass
:
1585 return extract_expr(cast
<FloatingLiteral
>(expr
));
1586 case Stmt::ParenExprClass
:
1587 return extract_expr(cast
<ParenExpr
>(expr
));
1588 case Stmt::ConditionalOperatorClass
:
1589 return extract_expr(cast
<ConditionalOperator
>(expr
));
1590 case Stmt::CallExprClass
:
1591 return extract_expr(cast
<CallExpr
>(expr
));
1598 /* Check if the given initialization statement is an assignment.
1599 * If so, return that assignment. Otherwise return NULL.
1601 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1603 BinaryOperator
*ass
;
1605 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1608 ass
= cast
<BinaryOperator
>(init
);
1609 if (ass
->getOpcode() != BO_Assign
)
1615 /* Check if the given initialization statement is a declaration
1616 * of a single variable.
1617 * If so, return that declaration. Otherwise return NULL.
1619 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1623 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1626 decl
= cast
<DeclStmt
>(init
);
1628 if (!decl
->isSingleDecl())
1631 return decl
->getSingleDecl();
1634 /* Given the assignment operator in the initialization of a for loop,
1635 * extract the induction variable, i.e., the (integer)variable being
1638 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1645 lhs
= init
->getLHS();
1646 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1651 ref
= cast
<DeclRefExpr
>(lhs
);
1652 decl
= ref
->getDecl();
1653 type
= decl
->getType().getTypePtr();
1655 if (!type
->isIntegerType()) {
1663 /* Given the initialization statement of a for loop and the single
1664 * declaration in this initialization statement,
1665 * extract the induction variable, i.e., the (integer) variable being
1668 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1672 vd
= cast
<VarDecl
>(decl
);
1674 const QualType type
= vd
->getType();
1675 if (!type
->isIntegerType()) {
1680 if (!vd
->getInit()) {
1688 /* Check that op is of the form iv++ or iv--.
1689 * Return an affine expression "1" or "-1" accordingly.
1691 __isl_give isl_pw_aff
*PetScan::extract_unary_increment(
1692 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1699 if (!op
->isIncrementDecrementOp()) {
1704 sub
= op
->getSubExpr();
1705 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1710 ref
= cast
<DeclRefExpr
>(sub
);
1711 if (ref
->getDecl() != iv
) {
1716 space
= isl_space_params_alloc(ctx
, 0);
1717 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
1719 if (op
->isIncrementOp())
1720 aff
= isl_aff_add_constant_si(aff
, 1);
1722 aff
= isl_aff_add_constant_si(aff
, -1);
1724 return isl_pw_aff_from_aff(aff
);
1727 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1728 * has a single constant expression, then put this constant in *user.
1729 * The caller is assumed to have checked that this function will
1730 * be called exactly once.
1732 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
1735 isl_int
*inc
= (isl_int
*)user
;
1738 if (isl_aff_is_cst(aff
))
1739 isl_aff_get_constant(aff
, inc
);
1749 /* Check if op is of the form
1753 * and return inc as an affine expression.
1755 * We extract an affine expression from the RHS, subtract iv and return
1758 __isl_give isl_pw_aff
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1759 clang::ValueDecl
*iv
)
1768 if (op
->getOpcode() != BO_Assign
) {
1774 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1779 ref
= cast
<DeclRefExpr
>(lhs
);
1780 if (ref
->getDecl() != iv
) {
1785 val
= extract_affine(op
->getRHS());
1787 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1789 dim
= isl_space_params_alloc(ctx
, 1);
1790 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1791 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1792 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1794 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
1799 /* Check that op is of the form iv += cst or iv -= cst
1800 * and return an affine expression corresponding oto cst or -cst accordingly.
1802 __isl_give isl_pw_aff
*PetScan::extract_compound_increment(
1803 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1809 BinaryOperatorKind opcode
;
1811 opcode
= op
->getOpcode();
1812 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1816 if (opcode
== BO_SubAssign
)
1820 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1825 ref
= cast
<DeclRefExpr
>(lhs
);
1826 if (ref
->getDecl() != iv
) {
1831 val
= extract_affine(op
->getRHS());
1833 val
= isl_pw_aff_neg(val
);
1838 /* Check that the increment of the given for loop increments
1839 * (or decrements) the induction variable "iv" and return
1840 * the increment as an affine expression if successful.
1842 __isl_give isl_pw_aff
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1845 Stmt
*inc
= stmt
->getInc();
1852 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1853 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1854 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1855 return extract_compound_increment(
1856 cast
<CompoundAssignOperator
>(inc
), iv
);
1857 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1858 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1864 /* Embed the given iteration domain in an extra outer loop
1865 * with induction variable "var".
1866 * If this variable appeared as a parameter in the constraints,
1867 * it is replaced by the new outermost dimension.
1869 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1870 __isl_take isl_id
*var
)
1874 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1875 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1877 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1878 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1885 /* Return those elements in the space of "cond" that come after
1886 * (based on "sign") an element in "cond".
1888 static __isl_give isl_set
*after(__isl_take isl_set
*cond
, int sign
)
1890 isl_map
*previous_to_this
;
1893 previous_to_this
= isl_map_lex_lt(isl_set_get_space(cond
));
1895 previous_to_this
= isl_map_lex_gt(isl_set_get_space(cond
));
1897 cond
= isl_set_apply(cond
, previous_to_this
);
1902 /* Create the infinite iteration domain
1904 * { [id] : id >= 0 }
1906 * If "scop" has an affine skip of type pet_skip_later,
1907 * then remove those iterations i that have an earlier iteration
1908 * where the skip condition is satisfied, meaning that iteration i
1910 * Since we are dealing with a loop without loop iterator,
1911 * the skip condition cannot refer to the current loop iterator and
1912 * so effectively, the returned set is of the form
1914 * { [0]; [id] : id >= 1 and not skip }
1916 static __isl_give isl_set
*infinite_domain(__isl_take isl_id
*id
,
1917 struct pet_scop
*scop
)
1919 isl_ctx
*ctx
= isl_id_get_ctx(id
);
1923 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
1924 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, id
);
1926 if (!pet_scop_has_affine_skip(scop
, pet_skip_later
))
1929 skip
= pet_scop_get_skip(scop
, pet_skip_later
);
1930 skip
= isl_set_fix_si(skip
, isl_dim_set
, 0, 1);
1931 skip
= isl_set_params(skip
);
1932 skip
= embed(skip
, isl_id_copy(id
));
1933 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
1934 domain
= isl_set_subtract(domain
, after(skip
, 1));
1939 /* Create an identity mapping on the space containing "domain".
1941 static __isl_give isl_map
*identity_map(__isl_keep isl_set
*domain
)
1946 space
= isl_space_map_from_set(isl_set_get_space(domain
));
1947 id
= isl_map_identity(space
);
1952 /* Add a filter to "scop" that imposes that it is only executed
1953 * when "break_access" has a zero value for all previous iterations
1956 * The input "break_access" has a zero-dimensional domain and range.
1958 static struct pet_scop
*scop_add_break(struct pet_scop
*scop
,
1959 __isl_take isl_map
*break_access
, __isl_take isl_set
*domain
, int sign
)
1961 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
1965 id_test
= isl_map_get_tuple_id(break_access
, isl_dim_out
);
1966 break_access
= isl_map_add_dims(break_access
, isl_dim_in
, 1);
1967 break_access
= isl_map_add_dims(break_access
, isl_dim_out
, 1);
1968 break_access
= isl_map_intersect_range(break_access
, domain
);
1969 break_access
= isl_map_set_tuple_id(break_access
, isl_dim_out
, id_test
);
1971 prev
= isl_map_lex_gt_first(isl_map_get_space(break_access
), 1);
1973 prev
= isl_map_lex_lt_first(isl_map_get_space(break_access
), 1);
1974 break_access
= isl_map_intersect(break_access
, prev
);
1975 scop
= pet_scop_filter(scop
, break_access
, 0);
1976 scop
= pet_scop_merge_filters(scop
);
1981 /* Construct a pet_scop for an infinite loop around the given body.
1983 * We extract a pet_scop for the body and then embed it in a loop with
1992 * If the body contains any break, then it is taken into
1993 * account in infinite_domain (if the skip condition is affine)
1994 * or in scop_add_break (if the skip condition is not affine).
1996 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
2002 struct pet_scop
*scop
;
2005 scop
= extract(body
);
2009 id
= isl_id_alloc(ctx
, "t", NULL
);
2010 domain
= infinite_domain(isl_id_copy(id
), scop
);
2011 ident
= identity_map(domain
);
2013 has_var_break
= pet_scop_has_var_skip(scop
, pet_skip_later
);
2015 access
= pet_scop_get_skip_map(scop
, pet_skip_later
);
2017 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
2018 isl_map_copy(ident
), ident
, id
);
2020 scop
= scop_add_break(scop
, access
, domain
, 1);
2022 isl_set_free(domain
);
2027 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2033 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
2035 return extract_infinite_loop(stmt
->getBody());
2038 /* Create an access to a virtual array representing the result
2040 * Unlike other accessed data, the id of the array is NULL as
2041 * there is no ValueDecl in the program corresponding to the virtual
2043 * The array starts out as a scalar, but grows along with the
2044 * statement writing to the array in pet_scop_embed.
2046 static __isl_give isl_map
*create_test_access(isl_ctx
*ctx
, int test_nr
)
2048 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, 0);
2052 snprintf(name
, sizeof(name
), "__pet_test_%d", test_nr
);
2053 id
= isl_id_alloc(ctx
, name
, NULL
);
2054 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
2055 return isl_map_universe(dim
);
2058 /* Add an array with the given extent ("access") to the list
2059 * of arrays in "scop" and return the extended pet_scop.
2060 * The array is marked as attaining values 0 and 1 only and
2061 * as each element being assigned at most once.
2063 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2064 __isl_keep isl_map
*access
, clang::ASTContext
&ast_ctx
)
2066 isl_ctx
*ctx
= isl_map_get_ctx(access
);
2068 struct pet_array
**arrays
;
2069 struct pet_array
*array
;
2076 arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
2080 scop
->arrays
= arrays
;
2082 array
= isl_calloc_type(ctx
, struct pet_array
);
2086 array
->extent
= isl_map_range(isl_map_copy(access
));
2087 dim
= isl_space_params_alloc(ctx
, 0);
2088 array
->context
= isl_set_universe(dim
);
2089 dim
= isl_space_set_alloc(ctx
, 0, 1);
2090 array
->value_bounds
= isl_set_universe(dim
);
2091 array
->value_bounds
= isl_set_lower_bound_si(array
->value_bounds
,
2093 array
->value_bounds
= isl_set_upper_bound_si(array
->value_bounds
,
2095 array
->element_type
= strdup("int");
2096 array
->element_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
2097 array
->uniquely_defined
= 1;
2099 scop
->arrays
[scop
->n_array
] = array
;
2102 if (!array
->extent
|| !array
->context
)
2107 pet_scop_free(scop
);
2111 /* Construct a pet_scop for a while loop of the form
2116 * In particular, construct a scop for an infinite loop around body and
2117 * intersect the domain with the affine expression.
2118 * Note that this intersection may result in an empty loop.
2120 struct pet_scop
*PetScan::extract_affine_while(__isl_take isl_pw_aff
*pa
,
2123 struct pet_scop
*scop
;
2127 valid
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2128 dom
= isl_pw_aff_non_zero_set(pa
);
2129 scop
= extract_infinite_loop(body
);
2130 scop
= pet_scop_restrict(scop
, dom
);
2131 scop
= pet_scop_restrict_context(scop
, valid
);
2136 /* Construct a scop for a while, given the scops for the condition
2137 * and the body, the filter access and the iteration domain of
2140 * In particular, the scop for the condition is filtered to depend
2141 * on "test_access" evaluating to true for all previous iterations
2142 * of the loop, while the scop for the body is filtered to depend
2143 * on "test_access" evaluating to true for all iterations up to the
2144 * current iteration.
2146 * These filtered scops are then combined into a single scop.
2148 * "sign" is positive if the iterator increases and negative
2151 static struct pet_scop
*scop_add_while(struct pet_scop
*scop_cond
,
2152 struct pet_scop
*scop_body
, __isl_take isl_map
*test_access
,
2153 __isl_take isl_set
*domain
, int sign
)
2155 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
2159 id_test
= isl_map_get_tuple_id(test_access
, isl_dim_out
);
2160 test_access
= isl_map_add_dims(test_access
, isl_dim_in
, 1);
2161 test_access
= isl_map_add_dims(test_access
, isl_dim_out
, 1);
2162 test_access
= isl_map_intersect_range(test_access
, domain
);
2163 test_access
= isl_map_set_tuple_id(test_access
, isl_dim_out
, id_test
);
2165 prev
= isl_map_lex_ge_first(isl_map_get_space(test_access
), 1);
2167 prev
= isl_map_lex_le_first(isl_map_get_space(test_access
), 1);
2168 test_access
= isl_map_intersect(test_access
, prev
);
2169 scop_body
= pet_scop_filter(scop_body
, isl_map_copy(test_access
), 1);
2171 prev
= isl_map_lex_gt_first(isl_map_get_space(test_access
), 1);
2173 prev
= isl_map_lex_lt_first(isl_map_get_space(test_access
), 1);
2174 test_access
= isl_map_intersect(test_access
, prev
);
2175 scop_cond
= pet_scop_filter(scop_cond
, test_access
, 1);
2177 return pet_scop_add_seq(ctx
, scop_cond
, scop_body
);
2180 /* Check if the while loop is of the form
2182 * while (affine expression)
2185 * If so, call extract_affine_while to construct a scop.
2187 * Otherwise, construct a generic while scop, with iteration domain
2188 * { [t] : t >= 0 }. The scop consists of two parts, one for
2189 * evaluating the condition and one for the body.
2190 * The schedule is adjusted to reflect that the condition is evaluated
2191 * before the body is executed and the body is filtered to depend
2192 * on the result of the condition evaluating to true on all iterations
2193 * up to the current iteration, while the evaluation the condition itself
2194 * is filtered to depend on the result of the condition evaluating to true
2195 * on all previous iterations.
2196 * The context of the scop representing the body is dropped
2197 * because we don't know how many times the body will be executed,
2200 * If the body contains any break, then it is taken into
2201 * account in infinite_domain (if the skip condition is affine)
2202 * or in scop_add_break (if the skip condition is not affine).
2204 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
2208 isl_map
*test_access
;
2212 struct pet_scop
*scop
, *scop_body
;
2214 isl_map
*break_access
;
2216 cond
= stmt
->getCond();
2222 pa
= try_extract_affine_condition(cond
);
2224 return extract_affine_while(pa
, stmt
->getBody());
2226 if (!allow_nested
) {
2231 test_access
= create_test_access(ctx
, n_test
++);
2232 scop
= extract_non_affine_condition(cond
, isl_map_copy(test_access
));
2233 scop
= scop_add_array(scop
, test_access
, ast_context
);
2234 scop_body
= extract(stmt
->getBody());
2236 id
= isl_id_alloc(ctx
, "t", NULL
);
2237 domain
= infinite_domain(isl_id_copy(id
), scop_body
);
2238 ident
= identity_map(domain
);
2240 has_var_break
= pet_scop_has_var_skip(scop_body
, pet_skip_later
);
2242 break_access
= pet_scop_get_skip_map(scop_body
, pet_skip_later
);
2244 scop
= pet_scop_prefix(scop
, 0);
2245 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), isl_map_copy(ident
),
2246 isl_map_copy(ident
), isl_id_copy(id
));
2247 scop_body
= pet_scop_reset_context(scop_body
);
2248 scop_body
= pet_scop_prefix(scop_body
, 1);
2249 scop_body
= pet_scop_embed(scop_body
, isl_set_copy(domain
),
2250 isl_map_copy(ident
), ident
, id
);
2252 if (has_var_break
) {
2253 scop
= scop_add_break(scop
, isl_map_copy(break_access
),
2254 isl_set_copy(domain
), 1);
2255 scop_body
= scop_add_break(scop_body
, break_access
,
2256 isl_set_copy(domain
), 1);
2258 scop
= scop_add_while(scop
, scop_body
, test_access
, domain
, 1);
2263 /* Check whether "cond" expresses a simple loop bound
2264 * on the only set dimension.
2265 * In particular, if "up" is set then "cond" should contain only
2266 * upper bounds on the set dimension.
2267 * Otherwise, it should contain only lower bounds.
2269 static bool is_simple_bound(__isl_keep isl_set
*cond
, isl_int inc
)
2271 if (isl_int_is_pos(inc
))
2272 return !isl_set_dim_has_any_lower_bound(cond
, isl_dim_set
, 0);
2274 return !isl_set_dim_has_any_upper_bound(cond
, isl_dim_set
, 0);
2277 /* Extend a condition on a given iteration of a loop to one that
2278 * imposes the same condition on all previous iterations.
2279 * "domain" expresses the lower [upper] bound on the iterations
2280 * when inc is positive [negative].
2282 * In particular, we construct the condition (when inc is positive)
2284 * forall i' : (domain(i') and i' <= i) => cond(i')
2286 * which is equivalent to
2288 * not exists i' : domain(i') and i' <= i and not cond(i')
2290 * We construct this set by negating cond, applying a map
2292 * { [i'] -> [i] : domain(i') and i' <= i }
2294 * and then negating the result again.
2296 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
2297 __isl_take isl_set
*domain
, isl_int inc
)
2299 isl_map
*previous_to_this
;
2301 if (isl_int_is_pos(inc
))
2302 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
2304 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
2306 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
2308 cond
= isl_set_complement(cond
);
2309 cond
= isl_set_apply(cond
, previous_to_this
);
2310 cond
= isl_set_complement(cond
);
2315 /* Construct a domain of the form
2317 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2319 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
2320 __isl_take isl_pw_aff
*init
, isl_int inc
)
2326 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
2327 dim
= isl_pw_aff_get_domain_space(init
);
2328 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2329 aff
= isl_aff_add_coefficient(aff
, isl_dim_in
, 0, inc
);
2330 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2332 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2333 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2334 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2335 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2337 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2339 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2341 return isl_set_params(set
);
2344 /* Assuming "cond" represents a bound on a loop where the loop
2345 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2348 * Under the given assumptions, wrapping is only possible if "cond" allows
2349 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2350 * increasing iterator and 0 in case of a decreasing iterator.
2352 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
, isl_int inc
)
2358 test
= isl_set_copy(cond
);
2360 isl_int_init(limit
);
2361 if (isl_int_is_neg(inc
))
2362 isl_int_set_si(limit
, 0);
2364 isl_int_set_si(limit
, 1);
2365 isl_int_mul_2exp(limit
, limit
, get_type_size(iv
));
2366 isl_int_sub_ui(limit
, limit
, 1);
2369 test
= isl_set_fix(cond
, isl_dim_set
, 0, limit
);
2370 cw
= !isl_set_is_empty(test
);
2373 isl_int_clear(limit
);
2378 /* Given a one-dimensional space, construct the following mapping on this
2381 * { [v] -> [v mod 2^width] }
2383 * where width is the number of bits used to represent the values
2384 * of the unsigned variable "iv".
2386 static __isl_give isl_map
*compute_wrapping(__isl_take isl_space
*dim
,
2394 isl_int_set_si(mod
, 1);
2395 isl_int_mul_2exp(mod
, mod
, get_type_size(iv
));
2397 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2398 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2399 aff
= isl_aff_mod(aff
, mod
);
2403 return isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2404 map
= isl_map_reverse(map
);
2407 /* Project out the parameter "id" from "set".
2409 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2410 __isl_keep isl_id
*id
)
2414 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2416 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2421 /* Compute the set of parameters for which "set1" is a subset of "set2".
2423 * set1 is a subset of set2 if
2425 * forall i in set1 : i in set2
2429 * not exists i in set1 and i not in set2
2433 * not exists i in set1 \ set2
2435 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2436 __isl_take isl_set
*set2
)
2438 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2441 /* Compute the set of parameter values for which "cond" holds
2442 * on the next iteration for each element of "dom".
2444 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2445 * and then compute the set of parameters for which the result is a subset
2448 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2449 __isl_take isl_set
*dom
, isl_int inc
)
2455 space
= isl_set_get_space(dom
);
2456 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2457 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2458 aff
= isl_aff_add_constant(aff
, inc
);
2459 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2461 dom
= isl_set_apply(dom
, next
);
2463 return enforce_subset(dom
, cond
);
2466 /* Does "id" refer to a nested access?
2468 static bool is_nested_parameter(__isl_keep isl_id
*id
)
2470 return id
&& isl_id_get_user(id
) && !isl_id_get_name(id
);
2473 /* Does parameter "pos" of "space" refer to a nested access?
2475 static bool is_nested_parameter(__isl_keep isl_space
*space
, int pos
)
2480 id
= isl_space_get_dim_id(space
, isl_dim_param
, pos
);
2481 nested
= is_nested_parameter(id
);
2487 /* Does "space" involve any parameters that refer to nested
2488 * accesses, i.e., parameters with no name?
2490 static bool has_nested(__isl_keep isl_space
*space
)
2494 nparam
= isl_space_dim(space
, isl_dim_param
);
2495 for (int i
= 0; i
< nparam
; ++i
)
2496 if (is_nested_parameter(space
, i
))
2502 /* Does "pa" involve any parameters that refer to nested
2503 * accesses, i.e., parameters with no name?
2505 static bool has_nested(__isl_keep isl_pw_aff
*pa
)
2510 space
= isl_pw_aff_get_space(pa
);
2511 nested
= has_nested(space
);
2512 isl_space_free(space
);
2517 /* Construct a pet_scop for a for statement.
2518 * The for loop is required to be of the form
2520 * for (i = init; condition; ++i)
2524 * for (i = init; condition; --i)
2526 * The initialization of the for loop should either be an assignment
2527 * to an integer variable, or a declaration of such a variable with
2530 * The condition is allowed to contain nested accesses, provided
2531 * they are not being written to inside the body of the loop.
2532 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2533 * essentially treated as a while loop, with iteration domain
2534 * { [i] : i >= init }.
2536 * We extract a pet_scop for the body and then embed it in a loop with
2537 * iteration domain and schedule
2539 * { [i] : i >= init and condition' }
2544 * { [i] : i <= init and condition' }
2547 * Where condition' is equal to condition if the latter is
2548 * a simple upper [lower] bound and a condition that is extended
2549 * to apply to all previous iterations otherwise.
2551 * If the condition is non-affine, then we drop the condition from the
2552 * iteration domain and instead create a separate statement
2553 * for evaluating the condition. The body is then filtered to depend
2554 * on the result of the condition evaluating to true on all iterations
2555 * up to the current iteration, while the evaluation the condition itself
2556 * is filtered to depend on the result of the condition evaluating to true
2557 * on all previous iterations.
2558 * The context of the scop representing the body is dropped
2559 * because we don't know how many times the body will be executed,
2562 * If the stride of the loop is not 1, then "i >= init" is replaced by
2564 * (exists a: i = init + stride * a and a >= 0)
2566 * If the loop iterator i is unsigned, then wrapping may occur.
2567 * During the computation, we work with a virtual iterator that
2568 * does not wrap. However, the condition in the code applies
2569 * to the wrapped value, so we need to change condition(i)
2570 * into condition([i % 2^width]).
2571 * After computing the virtual domain and schedule, we apply
2572 * the function { [v] -> [v % 2^width] } to the domain and the domain
2573 * of the schedule. In order not to lose any information, we also
2574 * need to intersect the domain of the schedule with the virtual domain
2575 * first, since some iterations in the wrapped domain may be scheduled
2576 * several times, typically an infinite number of times.
2577 * Note that there may be no need to perform this final wrapping
2578 * if the loop condition (after wrapping) satisfies certain conditions.
2579 * However, the is_simple_bound condition is not enough since it doesn't
2580 * check if there even is an upper bound.
2582 * If the loop condition is non-affine, then we keep the virtual
2583 * iterator in the iteration domain and instead replace all accesses
2584 * to the original iterator by the wrapping of the virtual iterator.
2586 * Wrapping on unsigned iterators can be avoided entirely if
2587 * loop condition is simple, the loop iterator is incremented
2588 * [decremented] by one and the last value before wrapping cannot
2589 * possibly satisfy the loop condition.
2591 * Before extracting a pet_scop from the body we remove all
2592 * assignments in assigned_value to variables that are assigned
2593 * somewhere in the body of the loop.
2595 * Valid parameters for a for loop are those for which the initial
2596 * value itself, the increment on each domain iteration and
2597 * the condition on both the initial value and
2598 * the result of incrementing the iterator for each iteration of the domain
2600 * If the loop condition is non-affine, then we only consider validity
2601 * of the initial value.
2603 * If the body contains any break, then we keep track of it in "skip"
2604 * (if the skip condition is affine) or it is handled in scop_add_break
2605 * (if the skip condition is not affine).
2606 * Note that the affine break condition needs to be considered with
2607 * respect to previous iterations in the virtual domain (if any)
2608 * and that the domain needs to be kept virtual if there is a non-affine
2611 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2613 BinaryOperator
*ass
;
2621 isl_set
*cond
= NULL
;
2622 isl_set
*skip
= NULL
;
2624 struct pet_scop
*scop
, *scop_cond
= NULL
;
2625 assigned_value_cache
cache(assigned_value
);
2631 bool keep_virtual
= false;
2632 bool has_affine_break
;
2634 isl_map
*wrap
= NULL
;
2635 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2636 isl_set
*valid_init
;
2637 isl_set
*valid_cond
;
2638 isl_set
*valid_cond_init
;
2639 isl_set
*valid_cond_next
;
2641 isl_map
*test_access
= NULL
, *break_access
= NULL
;
2644 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2645 return extract_infinite_for(stmt
);
2647 init
= stmt
->getInit();
2652 if ((ass
= initialization_assignment(init
)) != NULL
) {
2653 iv
= extract_induction_variable(ass
);
2656 lhs
= ass
->getLHS();
2657 rhs
= ass
->getRHS();
2658 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2659 VarDecl
*var
= extract_induction_variable(init
, decl
);
2663 rhs
= var
->getInit();
2664 lhs
= create_DeclRefExpr(var
);
2666 unsupported(stmt
->getInit());
2670 pa_inc
= extract_increment(stmt
, iv
);
2675 if (isl_pw_aff_n_piece(pa_inc
) != 1 ||
2676 isl_pw_aff_foreach_piece(pa_inc
, &extract_cst
, &inc
) < 0) {
2677 isl_pw_aff_free(pa_inc
);
2678 unsupported(stmt
->getInc());
2682 valid_inc
= isl_pw_aff_domain(pa_inc
);
2684 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2686 assigned_value
.erase(iv
);
2687 clear_assignments
clear(assigned_value
);
2688 clear
.TraverseStmt(stmt
->getBody());
2690 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
2692 pa
= try_extract_nested_condition(stmt
->getCond());
2693 if (allow_nested
&& (!pa
|| has_nested(pa
)))
2696 scop
= extract(stmt
->getBody());
2698 has_affine_break
= scop
&&
2699 pet_scop_has_affine_skip(scop
, pet_skip_later
);
2700 if (has_affine_break
) {
2701 skip
= pet_scop_get_skip(scop
, pet_skip_later
);
2702 skip
= isl_set_fix_si(skip
, isl_dim_set
, 0, 1);
2703 skip
= isl_set_params(skip
);
2705 has_var_break
= scop
&& pet_scop_has_var_skip(scop
, pet_skip_later
);
2706 if (has_var_break
) {
2707 break_access
= pet_scop_get_skip_map(scop
, pet_skip_later
);
2708 keep_virtual
= true;
2711 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2712 isl_pw_aff_free(pa
);
2716 if (!allow_nested
&& !pa
)
2717 pa
= try_extract_affine_condition(stmt
->getCond());
2718 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2719 cond
= isl_pw_aff_non_zero_set(pa
);
2720 if (allow_nested
&& !cond
) {
2721 int save_n_stmt
= n_stmt
;
2722 test_access
= create_test_access(ctx
, n_test
++);
2724 scop_cond
= extract_non_affine_condition(stmt
->getCond(),
2725 isl_map_copy(test_access
));
2726 n_stmt
= save_n_stmt
;
2727 scop_cond
= scop_add_array(scop_cond
, test_access
, ast_context
);
2728 scop_cond
= pet_scop_prefix(scop_cond
, 0);
2729 scop
= pet_scop_reset_context(scop
);
2730 scop
= pet_scop_prefix(scop
, 1);
2731 keep_virtual
= true;
2732 cond
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2735 cond
= embed(cond
, isl_id_copy(id
));
2736 skip
= embed(skip
, isl_id_copy(id
));
2737 valid_cond
= isl_set_coalesce(valid_cond
);
2738 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
2739 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
2740 is_one
= isl_int_is_one(inc
) || isl_int_is_negone(inc
);
2741 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2743 init_val
= extract_affine(rhs
);
2744 valid_cond_init
= enforce_subset(
2745 isl_set_from_pw_aff(isl_pw_aff_copy(init_val
)),
2746 isl_set_copy(valid_cond
));
2747 if (is_one
&& !is_virtual
) {
2748 isl_pw_aff_free(init_val
);
2749 pa
= extract_comparison(isl_int_is_pos(inc
) ? BO_GE
: BO_LE
,
2751 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2752 valid_init
= set_project_out_by_id(valid_init
, id
);
2753 domain
= isl_pw_aff_non_zero_set(pa
);
2755 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
2756 domain
= strided_domain(isl_id_copy(id
), init_val
, inc
);
2759 domain
= embed(domain
, isl_id_copy(id
));
2762 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2763 rev_wrap
= isl_map_reverse(isl_map_copy(wrap
));
2764 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
2765 skip
= isl_set_apply(skip
, isl_map_copy(rev_wrap
));
2766 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
2767 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
2769 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2770 is_simple
= is_simple_bound(cond
, inc
);
2772 cond
= valid_for_each_iteration(cond
,
2773 isl_set_copy(domain
), inc
);
2774 domain
= isl_set_intersect(domain
, cond
);
2775 if (has_affine_break
) {
2776 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2777 skip
= after(skip
, isl_int_sgn(inc
));
2778 domain
= isl_set_subtract(domain
, skip
);
2780 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2781 space
= isl_space_from_domain(isl_set_get_space(domain
));
2782 space
= isl_space_add_dims(space
, isl_dim_out
, 1);
2783 sched
= isl_map_universe(space
);
2784 if (isl_int_is_pos(inc
))
2785 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2787 sched
= isl_map_oppose(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2789 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
), inc
);
2790 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
2792 if (is_virtual
&& !keep_virtual
) {
2793 wrap
= isl_map_set_dim_id(wrap
,
2794 isl_dim_out
, 0, isl_id_copy(id
));
2795 sched
= isl_map_intersect_domain(sched
, isl_set_copy(domain
));
2796 domain
= isl_set_apply(domain
, isl_map_copy(wrap
));
2797 sched
= isl_map_apply_domain(sched
, wrap
);
2799 if (!(is_virtual
&& keep_virtual
)) {
2800 space
= isl_set_get_space(domain
);
2801 wrap
= isl_map_identity(isl_space_map_from_set(space
));
2804 scop_cond
= pet_scop_embed(scop_cond
, isl_set_copy(domain
),
2805 isl_map_copy(sched
), isl_map_copy(wrap
), isl_id_copy(id
));
2806 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), sched
, wrap
, id
);
2807 scop
= resolve_nested(scop
);
2809 scop
= scop_add_break(scop
, break_access
, isl_set_copy(domain
),
2812 scop
= scop_add_while(scop_cond
, scop
, test_access
, domain
,
2814 isl_set_free(valid_inc
);
2816 scop
= pet_scop_restrict_context(scop
, valid_inc
);
2817 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
2818 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
2819 isl_set_free(domain
);
2821 clear_assignment(assigned_value
, iv
);
2825 scop
= pet_scop_restrict_context(scop
, valid_init
);
2830 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
)
2832 return extract(stmt
->children());
2835 /* Does parameter "pos" of "map" refer to a nested access?
2837 static bool is_nested_parameter(__isl_keep isl_map
*map
, int pos
)
2842 id
= isl_map_get_dim_id(map
, isl_dim_param
, pos
);
2843 nested
= is_nested_parameter(id
);
2849 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2851 static int n_nested_parameter(__isl_keep isl_space
*space
)
2856 nparam
= isl_space_dim(space
, isl_dim_param
);
2857 for (int i
= 0; i
< nparam
; ++i
)
2858 if (is_nested_parameter(space
, i
))
2864 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2866 static int n_nested_parameter(__isl_keep isl_map
*map
)
2871 space
= isl_map_get_space(map
);
2872 n
= n_nested_parameter(space
);
2873 isl_space_free(space
);
2878 /* For each nested access parameter in "space",
2879 * construct a corresponding pet_expr, place it in args and
2880 * record its position in "param2pos".
2881 * "n_arg" is the number of elements that are already in args.
2882 * The position recorded in "param2pos" takes this number into account.
2883 * If the pet_expr corresponding to a parameter is identical to
2884 * the pet_expr corresponding to an earlier parameter, then these two
2885 * parameters are made to refer to the same element in args.
2887 * Return the final number of elements in args or -1 if an error has occurred.
2889 int PetScan::extract_nested(__isl_keep isl_space
*space
,
2890 int n_arg
, struct pet_expr
**args
, std::map
<int,int> ¶m2pos
)
2894 nparam
= isl_space_dim(space
, isl_dim_param
);
2895 for (int i
= 0; i
< nparam
; ++i
) {
2897 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2900 if (!is_nested_parameter(id
)) {
2905 nested
= (Expr
*) isl_id_get_user(id
);
2906 args
[n_arg
] = extract_expr(nested
);
2910 for (j
= 0; j
< n_arg
; ++j
)
2911 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
2915 pet_expr_free(args
[n_arg
]);
2919 param2pos
[i
] = n_arg
++;
2927 /* For each nested access parameter in the access relations in "expr",
2928 * construct a corresponding pet_expr, place it in expr->args and
2929 * record its position in "param2pos".
2930 * n is the number of nested access parameters.
2932 struct pet_expr
*PetScan::extract_nested(struct pet_expr
*expr
, int n
,
2933 std::map
<int,int> ¶m2pos
)
2937 expr
->args
= isl_calloc_array(ctx
, struct pet_expr
*, n
);
2942 space
= isl_map_get_space(expr
->acc
.access
);
2943 n
= extract_nested(space
, 0, expr
->args
, param2pos
);
2944 isl_space_free(space
);
2952 pet_expr_free(expr
);
2956 /* Look for parameters in any access relation in "expr" that
2957 * refer to nested accesses. In particular, these are
2958 * parameters with no name.
2960 * If there are any such parameters, then the domain of the access
2961 * relation, which is still [] at this point, is replaced by
2962 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2963 * (after identifying identical nested accesses).
2964 * The parameters are then equated to the corresponding t dimensions
2965 * and subsequently projected out.
2966 * param2pos maps the position of the parameter to the position
2967 * of the corresponding t dimension.
2969 struct pet_expr
*PetScan::resolve_nested(struct pet_expr
*expr
)
2976 std::map
<int,int> param2pos
;
2981 for (int i
= 0; i
< expr
->n_arg
; ++i
) {
2982 expr
->args
[i
] = resolve_nested(expr
->args
[i
]);
2983 if (!expr
->args
[i
]) {
2984 pet_expr_free(expr
);
2989 if (expr
->type
!= pet_expr_access
)
2992 n
= n_nested_parameter(expr
->acc
.access
);
2996 expr
= extract_nested(expr
, n
, param2pos
);
3001 nparam
= isl_map_dim(expr
->acc
.access
, isl_dim_param
);
3002 n_in
= isl_map_dim(expr
->acc
.access
, isl_dim_in
);
3003 dim
= isl_map_get_space(expr
->acc
.access
);
3004 dim
= isl_space_domain(dim
);
3005 dim
= isl_space_from_domain(dim
);
3006 dim
= isl_space_add_dims(dim
, isl_dim_out
, n
);
3007 map
= isl_map_universe(dim
);
3008 map
= isl_map_domain_map(map
);
3009 map
= isl_map_reverse(map
);
3010 expr
->acc
.access
= isl_map_apply_domain(expr
->acc
.access
, map
);
3012 for (int i
= nparam
- 1; i
>= 0; --i
) {
3013 isl_id
*id
= isl_map_get_dim_id(expr
->acc
.access
,
3015 if (!is_nested_parameter(id
)) {
3020 expr
->acc
.access
= isl_map_equate(expr
->acc
.access
,
3021 isl_dim_param
, i
, isl_dim_in
,
3022 n_in
+ param2pos
[i
]);
3023 expr
->acc
.access
= isl_map_project_out(expr
->acc
.access
,
3024 isl_dim_param
, i
, 1);
3031 pet_expr_free(expr
);
3035 /* Convert a top-level pet_expr to a pet_scop with one statement.
3036 * This mainly involves resolving nested expression parameters
3037 * and setting the name of the iteration space.
3038 * The name is given by "label" if it is non-NULL. Otherwise,
3039 * it is of the form S_<n_stmt>.
3041 struct pet_scop
*PetScan::extract(Stmt
*stmt
, struct pet_expr
*expr
,
3042 __isl_take isl_id
*label
)
3044 struct pet_stmt
*ps
;
3045 SourceLocation loc
= stmt
->getLocStart();
3046 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3048 expr
= resolve_nested(expr
);
3049 ps
= pet_stmt_from_pet_expr(ctx
, line
, label
, n_stmt
++, expr
);
3050 return pet_scop_from_pet_stmt(ctx
, ps
);
3053 /* Check if we can extract an affine expression from "expr".
3054 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3055 * We turn on autodetection so that we won't generate any warnings
3056 * and turn off nesting, so that we won't accept any non-affine constructs.
3058 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
3061 int save_autodetect
= options
->autodetect
;
3062 bool save_nesting
= nesting_enabled
;
3064 options
->autodetect
= 1;
3065 nesting_enabled
= false;
3067 pwaff
= extract_affine(expr
);
3069 options
->autodetect
= save_autodetect
;
3070 nesting_enabled
= save_nesting
;
3075 /* Check whether "expr" is an affine expression.
3077 bool PetScan::is_affine(Expr
*expr
)
3081 pwaff
= try_extract_affine(expr
);
3082 isl_pw_aff_free(pwaff
);
3084 return pwaff
!= NULL
;
3087 /* Check if we can extract an affine constraint from "expr".
3088 * Return the constraint as an isl_set if we can and NULL otherwise.
3089 * We turn on autodetection so that we won't generate any warnings
3090 * and turn off nesting, so that we won't accept any non-affine constructs.
3092 __isl_give isl_pw_aff
*PetScan::try_extract_affine_condition(Expr
*expr
)
3095 int save_autodetect
= options
->autodetect
;
3096 bool save_nesting
= nesting_enabled
;
3098 options
->autodetect
= 1;
3099 nesting_enabled
= false;
3101 cond
= extract_condition(expr
);
3103 options
->autodetect
= save_autodetect
;
3104 nesting_enabled
= save_nesting
;
3109 /* Check whether "expr" is an affine constraint.
3111 bool PetScan::is_affine_condition(Expr
*expr
)
3115 cond
= try_extract_affine_condition(expr
);
3116 isl_pw_aff_free(cond
);
3118 return cond
!= NULL
;
3121 /* Check if we can extract a condition from "expr".
3122 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3123 * If allow_nested is set, then the condition may involve parameters
3124 * corresponding to nested accesses.
3125 * We turn on autodetection so that we won't generate any warnings.
3127 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
3130 int save_autodetect
= options
->autodetect
;
3131 bool save_nesting
= nesting_enabled
;
3133 options
->autodetect
= 1;
3134 nesting_enabled
= allow_nested
;
3135 cond
= extract_condition(expr
);
3137 options
->autodetect
= save_autodetect
;
3138 nesting_enabled
= save_nesting
;
3143 /* If the top-level expression of "stmt" is an assignment, then
3144 * return that assignment as a BinaryOperator.
3145 * Otherwise return NULL.
3147 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
3149 BinaryOperator
*ass
;
3153 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
3156 ass
= cast
<BinaryOperator
>(stmt
);
3157 if(ass
->getOpcode() != BO_Assign
)
3163 /* Check if the given if statement is a conditional assignement
3164 * with a non-affine condition. If so, construct a pet_scop
3165 * corresponding to this conditional assignment. Otherwise return NULL.
3167 * In particular we check if "stmt" is of the form
3174 * where a is some array or scalar access.
3175 * The constructed pet_scop then corresponds to the expression
3177 * a = condition ? f(...) : g(...)
3179 * All access relations in f(...) are intersected with condition
3180 * while all access relation in g(...) are intersected with the complement.
3182 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
3184 BinaryOperator
*ass_then
, *ass_else
;
3185 isl_map
*write_then
, *write_else
;
3186 isl_set
*cond
, *comp
;
3190 struct pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
3191 bool save_nesting
= nesting_enabled
;
3193 if (!options
->detect_conditional_assignment
)
3196 ass_then
= top_assignment_or_null(stmt
->getThen());
3197 ass_else
= top_assignment_or_null(stmt
->getElse());
3199 if (!ass_then
|| !ass_else
)
3202 if (is_affine_condition(stmt
->getCond()))
3205 write_then
= extract_access(ass_then
->getLHS());
3206 write_else
= extract_access(ass_else
->getLHS());
3208 equal
= isl_map_is_equal(write_then
, write_else
);
3209 isl_map_free(write_else
);
3210 if (equal
< 0 || !equal
) {
3211 isl_map_free(write_then
);
3215 nesting_enabled
= allow_nested
;
3216 pa
= extract_condition(stmt
->getCond());
3217 nesting_enabled
= save_nesting
;
3218 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
3219 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
3220 map
= isl_map_from_range(isl_set_from_pw_aff(pa
));
3222 pe_cond
= pet_expr_from_access(map
);
3224 pe_then
= extract_expr(ass_then
->getRHS());
3225 pe_then
= pet_expr_restrict(pe_then
, cond
);
3226 pe_else
= extract_expr(ass_else
->getRHS());
3227 pe_else
= pet_expr_restrict(pe_else
, comp
);
3229 pe
= pet_expr_new_ternary(ctx
, pe_cond
, pe_then
, pe_else
);
3230 pe_write
= pet_expr_from_access(write_then
);
3232 pe_write
->acc
.write
= 1;
3233 pe_write
->acc
.read
= 0;
3235 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, pe_write
, pe
);
3236 return extract(stmt
, pe
);
3239 /* Create a pet_scop with a single statement evaluating "cond"
3240 * and writing the result to a virtual scalar, as expressed by
3243 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
,
3244 __isl_take isl_map
*access
)
3246 struct pet_expr
*expr
, *write
;
3247 struct pet_stmt
*ps
;
3248 struct pet_scop
*scop
;
3249 SourceLocation loc
= cond
->getLocStart();
3250 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3252 write
= pet_expr_from_access(access
);
3254 write
->acc
.write
= 1;
3255 write
->acc
.read
= 0;
3257 expr
= extract_expr(cond
);
3258 expr
= resolve_nested(expr
);
3259 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, write
, expr
);
3260 ps
= pet_stmt_from_pet_expr(ctx
, line
, NULL
, n_stmt
++, expr
);
3261 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3262 scop
= resolve_nested(scop
);
3268 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
,
3272 /* Apply the map pointed to by "user" to the domain of the access
3273 * relation, thereby embedding it in the range of the map.
3274 * The domain of both relations is the zero-dimensional domain.
3276 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
, void *user
)
3278 isl_map
*map
= (isl_map
*) user
;
3280 return isl_map_apply_domain(access
, isl_map_copy(map
));
3283 /* Apply "map" to all access relations in "expr".
3285 static struct pet_expr
*embed(struct pet_expr
*expr
, __isl_keep isl_map
*map
)
3287 return pet_expr_foreach_access(expr
, &embed_access
, map
);
3290 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3292 static int n_nested_parameter(__isl_keep isl_set
*set
)
3297 space
= isl_set_get_space(set
);
3298 n
= n_nested_parameter(space
);
3299 isl_space_free(space
);
3304 /* Remove all parameters from "map" that refer to nested accesses.
3306 static __isl_give isl_map
*remove_nested_parameters(__isl_take isl_map
*map
)
3311 space
= isl_map_get_space(map
);
3312 nparam
= isl_space_dim(space
, isl_dim_param
);
3313 for (int i
= nparam
- 1; i
>= 0; --i
)
3314 if (is_nested_parameter(space
, i
))
3315 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3316 isl_space_free(space
);
3322 static __isl_give isl_map
*access_remove_nested_parameters(
3323 __isl_take isl_map
*access
, void *user
);
3326 static __isl_give isl_map
*access_remove_nested_parameters(
3327 __isl_take isl_map
*access
, void *user
)
3329 return remove_nested_parameters(access
);
3332 /* Remove all nested access parameters from the schedule and all
3333 * accesses of "stmt".
3334 * There is no need to remove them from the domain as these parameters
3335 * have already been removed from the domain when this function is called.
3337 static struct pet_stmt
*remove_nested_parameters(struct pet_stmt
*stmt
)
3341 stmt
->schedule
= remove_nested_parameters(stmt
->schedule
);
3342 stmt
->body
= pet_expr_foreach_access(stmt
->body
,
3343 &access_remove_nested_parameters
, NULL
);
3344 if (!stmt
->schedule
|| !stmt
->body
)
3346 for (int i
= 0; i
< stmt
->n_arg
; ++i
) {
3347 stmt
->args
[i
] = pet_expr_foreach_access(stmt
->args
[i
],
3348 &access_remove_nested_parameters
, NULL
);
3355 pet_stmt_free(stmt
);
3359 /* For each nested access parameter in the domain of "stmt",
3360 * construct a corresponding pet_expr, place it before the original
3361 * elements in stmt->args and record its position in "param2pos".
3362 * n is the number of nested access parameters.
3364 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
3365 std::map
<int,int> ¶m2pos
)
3370 struct pet_expr
**args
;
3372 n_arg
= stmt
->n_arg
;
3373 args
= isl_calloc_array(ctx
, struct pet_expr
*, n
+ n_arg
);
3377 space
= isl_set_get_space(stmt
->domain
);
3378 n_arg
= extract_nested(space
, 0, args
, param2pos
);
3379 isl_space_free(space
);
3384 for (i
= 0; i
< stmt
->n_arg
; ++i
)
3385 args
[n_arg
+ i
] = stmt
->args
[i
];
3388 stmt
->n_arg
+= n_arg
;
3393 for (i
= 0; i
< n
; ++i
)
3394 pet_expr_free(args
[i
]);
3397 pet_stmt_free(stmt
);
3401 /* Check whether any of the arguments i of "stmt" starting at position "n"
3402 * is equal to one of the first "n" arguments j.
3403 * If so, combine the constraints on arguments i and j and remove
3406 static struct pet_stmt
*remove_duplicate_arguments(struct pet_stmt
*stmt
, int n
)
3415 if (n
== stmt
->n_arg
)
3418 map
= isl_set_unwrap(stmt
->domain
);
3420 for (i
= stmt
->n_arg
- 1; i
>= n
; --i
) {
3421 for (j
= 0; j
< n
; ++j
)
3422 if (pet_expr_is_equal(stmt
->args
[i
], stmt
->args
[j
]))
3427 map
= isl_map_equate(map
, isl_dim_out
, i
, isl_dim_out
, j
);
3428 map
= isl_map_project_out(map
, isl_dim_out
, i
, 1);
3430 pet_expr_free(stmt
->args
[i
]);
3431 for (j
= i
; j
+ 1 < stmt
->n_arg
; ++j
)
3432 stmt
->args
[j
] = stmt
->args
[j
+ 1];
3436 stmt
->domain
= isl_map_wrap(map
);
3441 pet_stmt_free(stmt
);
3445 /* Look for parameters in the iteration domain of "stmt" that
3446 * refer to nested accesses. In particular, these are
3447 * parameters with no name.
3449 * If there are any such parameters, then as many extra variables
3450 * (after identifying identical nested accesses) are inserted in the
3451 * range of the map wrapped inside the domain, before the original variables.
3452 * If the original domain is not a wrapped map, then a new wrapped
3453 * map is created with zero output dimensions.
3454 * The parameters are then equated to the corresponding output dimensions
3455 * and subsequently projected out, from the iteration domain,
3456 * the schedule and the access relations.
3457 * For each of the output dimensions, a corresponding argument
3458 * expression is inserted. Initially they are created with
3459 * a zero-dimensional domain, so they have to be embedded
3460 * in the current iteration domain.
3461 * param2pos maps the position of the parameter to the position
3462 * of the corresponding output dimension in the wrapped map.
3464 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3470 std::map
<int,int> param2pos
;
3475 n
= n_nested_parameter(stmt
->domain
);
3479 n_arg
= stmt
->n_arg
;
3480 stmt
= extract_nested(stmt
, n
, param2pos
);
3484 n
= stmt
->n_arg
- n_arg
;
3485 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3486 if (isl_set_is_wrapping(stmt
->domain
))
3487 map
= isl_set_unwrap(stmt
->domain
);
3489 map
= isl_map_from_domain(stmt
->domain
);
3490 map
= isl_map_insert_dims(map
, isl_dim_out
, 0, n
);
3492 for (int i
= nparam
- 1; i
>= 0; --i
) {
3495 if (!is_nested_parameter(map
, i
))
3498 id
= isl_map_get_tuple_id(stmt
->args
[param2pos
[i
]]->acc
.access
,
3500 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3501 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3503 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3506 stmt
->domain
= isl_map_wrap(map
);
3508 map
= isl_set_unwrap(isl_set_copy(stmt
->domain
));
3509 map
= isl_map_from_range(isl_map_domain(map
));
3510 for (int pos
= 0; pos
< n
; ++pos
)
3511 stmt
->args
[pos
] = embed(stmt
->args
[pos
], map
);
3514 stmt
= remove_nested_parameters(stmt
);
3515 stmt
= remove_duplicate_arguments(stmt
, n
);
3519 pet_stmt_free(stmt
);
3523 /* For each statement in "scop", move the parameters that correspond
3524 * to nested access into the ranges of the domains and create
3525 * corresponding argument expressions.
3527 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3532 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3533 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3534 if (!scop
->stmts
[i
])
3540 pet_scop_free(scop
);
3544 /* Given an access expression "expr", is the variable accessed by
3545 * "expr" assigned anywhere inside "scop"?
3547 static bool is_assigned(pet_expr
*expr
, pet_scop
*scop
)
3549 bool assigned
= false;
3552 id
= isl_map_get_tuple_id(expr
->acc
.access
, isl_dim_out
);
3553 assigned
= pet_scop_writes(scop
, id
);
3559 /* Are all nested access parameters in "pa" allowed given "scop".
3560 * In particular, is none of them written by anywhere inside "scop".
3562 * If "scop" has any skip conditions, then no nested access parameters
3563 * are allowed. In particular, if there is any nested access in a guard
3564 * for a piece of code containing a "continue", then we want to introduce
3565 * a separate statement for evaluating this guard so that we can express
3566 * that the result is false for all previous iterations.
3568 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3575 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3576 for (int i
= 0; i
< nparam
; ++i
) {
3578 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3582 if (!is_nested_parameter(id
)) {
3587 if (pet_scop_has_skip(scop
, pet_skip_now
)) {
3592 nested
= (Expr
*) isl_id_get_user(id
);
3593 expr
= extract_expr(nested
);
3594 allowed
= expr
&& expr
->type
== pet_expr_access
&&
3595 !is_assigned(expr
, scop
);
3597 pet_expr_free(expr
);
3607 /* Do we need to construct a skip condition of the given type
3608 * on an if statement, given that the if condition is non-affine?
3610 * pet_scop_filter_skip can only handle the case where the if condition
3611 * holds (the then branch) and the skip condition is universal.
3612 * In any other case, we need to construct a new skip condition.
3614 static bool need_skip(struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3615 bool have_else
, enum pet_skip type
)
3617 if (have_else
&& scop_else
&& pet_scop_has_skip(scop_else
, type
))
3619 if (scop_then
&& pet_scop_has_skip(scop_then
, type
) &&
3620 !pet_scop_has_universal_skip(scop_then
, type
))
3625 /* Do we need to construct a skip condition of the given type
3626 * on an if statement, given that the if condition is affine?
3628 * There is no need to construct a new skip condition if all
3629 * the skip conditions are affine.
3631 static bool need_skip_aff(struct pet_scop
*scop_then
,
3632 struct pet_scop
*scop_else
, bool have_else
, enum pet_skip type
)
3634 if (scop_then
&& pet_scop_has_var_skip(scop_then
, type
))
3636 if (have_else
&& scop_else
&& pet_scop_has_var_skip(scop_else
, type
))
3641 /* Do we need to construct a skip condition of the given type
3642 * on an if statement?
3644 static bool need_skip(struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3645 bool have_else
, enum pet_skip type
, bool affine
)
3648 return need_skip_aff(scop_then
, scop_else
, have_else
, type
);
3650 return need_skip(scop_then
, scop_else
, have_else
, type
);
3653 /* Construct an affine expression pet_expr that is evaluates
3654 * to the constant "val".
3656 static struct pet_expr
*universally(isl_ctx
*ctx
, int val
)
3661 space
= isl_space_alloc(ctx
, 0, 0, 1);
3662 map
= isl_map_universe(space
);
3663 map
= isl_map_fix_si(map
, isl_dim_out
, 0, val
);
3665 return pet_expr_from_access(map
);
3668 /* Construct an affine expression pet_expr that is evaluates
3669 * to the constant 1.
3671 static struct pet_expr
*universally_true(isl_ctx
*ctx
)
3673 return universally(ctx
, 1);
3676 /* Construct an affine expression pet_expr that is evaluates
3677 * to the constant 0.
3679 static struct pet_expr
*universally_false(isl_ctx
*ctx
)
3681 return universally(ctx
, 0);
3684 /* Given an access relation "test_access" for the if condition,
3685 * an access relation "skip_access" for the skip condition and
3686 * scops for the then and else branches, construct a scop for
3687 * computing "skip_access".
3689 * The computed scop contains a single statement that essentially does
3691 * skip_cond = test_cond ? skip_cond_then : skip_cond_else
3693 * If the skip conditions of the then and/or else branch are not affine,
3694 * then they need to be filtered by test_access.
3695 * If they are missing, then this means the skip condition is false.
3697 * Since we are constructing a skip condition for the if statement,
3698 * the skip conditions on the then and else branches are removed.
3700 static struct pet_scop
*extract_skip(PetScan
*scan
,
3701 __isl_take isl_map
*test_access
, __isl_take isl_map
*skip_access
,
3702 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
, bool have_else
,
3705 struct pet_expr
*expr_then
, *expr_else
, *expr
, *expr_skip
;
3706 struct pet_stmt
*stmt
;
3707 struct pet_scop
*scop
;
3708 isl_ctx
*ctx
= scan
->ctx
;
3712 if (have_else
&& !scop_else
)
3715 if (pet_scop_has_skip(scop_then
, type
)) {
3716 expr_then
= pet_scop_get_skip_expr(scop_then
, type
);
3717 pet_scop_reset_skip(scop_then
, type
);
3718 if (!pet_expr_is_affine(expr_then
))
3719 expr_then
= pet_expr_filter(expr_then
,
3720 isl_map_copy(test_access
), 1);
3722 expr_then
= universally_false(ctx
);
3724 if (have_else
&& pet_scop_has_skip(scop_else
, type
)) {
3725 expr_else
= pet_scop_get_skip_expr(scop_else
, type
);
3726 pet_scop_reset_skip(scop_else
, type
);
3727 if (!pet_expr_is_affine(expr_else
))
3728 expr_else
= pet_expr_filter(expr_else
,
3729 isl_map_copy(test_access
), 0);
3731 expr_else
= universally_false(ctx
);
3733 expr
= pet_expr_from_access(test_access
);
3734 expr
= pet_expr_new_ternary(ctx
, expr
, expr_then
, expr_else
);
3735 expr_skip
= pet_expr_from_access(isl_map_copy(skip_access
));
3737 expr_skip
->acc
.write
= 1;
3738 expr_skip
->acc
.read
= 0;
3740 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, expr_skip
, expr
);
3741 stmt
= pet_stmt_from_pet_expr(ctx
, -1, NULL
, scan
->n_stmt
++, expr
);
3743 scop
= pet_scop_from_pet_stmt(ctx
, stmt
);
3744 scop
= scop_add_array(scop
, skip_access
, scan
->ast_context
);
3745 isl_map_free(skip_access
);
3749 isl_map_free(test_access
);
3750 isl_map_free(skip_access
);
3754 /* Is scop's skip_now condition equal to its skip_later condition?
3755 * In particular, this means that it either has no skip_now condition
3756 * or both a skip_now and a skip_later condition (that are equal to each other).
3758 static bool skip_equals_skip_later(struct pet_scop
*scop
)
3760 int has_skip_now
, has_skip_later
;
3762 isl_set
*skip_now
, *skip_later
;
3766 has_skip_now
= pet_scop_has_skip(scop
, pet_skip_now
);
3767 has_skip_later
= pet_scop_has_skip(scop
, pet_skip_later
);
3768 if (has_skip_now
!= has_skip_later
)
3773 skip_now
= pet_scop_get_skip(scop
, pet_skip_now
);
3774 skip_later
= pet_scop_get_skip(scop
, pet_skip_later
);
3775 equal
= isl_set_is_equal(skip_now
, skip_later
);
3776 isl_set_free(skip_now
);
3777 isl_set_free(skip_later
);
3782 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
3784 static void drop_skip_later(struct pet_scop
*scop1
, struct pet_scop
*scop2
)
3786 pet_scop_reset_skip(scop1
, pet_skip_later
);
3787 pet_scop_reset_skip(scop2
, pet_skip_later
);
3790 /* Structure that handles the construction of skip conditions.
3792 * scop_then and scop_else represent the then and else branches
3793 * of the if statement
3795 * skip[type] is true if we need to construct a skip condition of that type
3796 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
3797 * are equal to each other
3798 * access[type] is the virtual array representing the skip condition
3799 * scop[type] is a scop for computing the skip condition
3801 struct pet_skip_info
{
3807 struct pet_scop
*scop
[2];
3809 pet_skip_info(isl_ctx
*ctx
) : ctx(ctx
) {}
3811 operator bool() { return skip
[pet_skip_now
] || skip
[pet_skip_later
]; }
3814 /* Structure that handles the construction of skip conditions on if statements.
3816 * scop_then and scop_else represent the then and else branches
3817 * of the if statement
3819 struct pet_skip_info_if
: public pet_skip_info
{
3820 struct pet_scop
*scop_then
, *scop_else
;
3823 pet_skip_info_if(isl_ctx
*ctx
, struct pet_scop
*scop_then
,
3824 struct pet_scop
*scop_else
, bool have_else
, bool affine
);
3825 void extract(PetScan
*scan
, __isl_keep isl_map
*access
,
3826 enum pet_skip type
);
3827 void extract(PetScan
*scan
, __isl_keep isl_map
*access
);
3828 void extract(PetScan
*scan
, __isl_keep isl_pw_aff
*cond
);
3829 struct pet_scop
*add(struct pet_scop
*scop
, enum pet_skip type
,
3831 struct pet_scop
*add(struct pet_scop
*scop
, int offset
);
3834 /* Initialize a pet_skip_info_if structure based on the then and else branches
3835 * and based on whether the if condition is affine or not.
3837 pet_skip_info_if::pet_skip_info_if(isl_ctx
*ctx
, struct pet_scop
*scop_then
,
3838 struct pet_scop
*scop_else
, bool have_else
, bool affine
) :
3839 pet_skip_info(ctx
), scop_then(scop_then
), scop_else(scop_else
),
3840 have_else(have_else
)
3842 skip
[pet_skip_now
] =
3843 need_skip(scop_then
, scop_else
, have_else
, pet_skip_now
, affine
);
3844 equal
= skip
[pet_skip_now
] && skip_equals_skip_later(scop_then
) &&
3845 (!have_else
|| skip_equals_skip_later(scop_else
));
3846 skip
[pet_skip_later
] = skip
[pet_skip_now
] && !equal
&&
3847 need_skip(scop_then
, scop_else
, have_else
, pet_skip_later
, affine
);
3850 /* If we need to construct a skip condition of the given type,
3853 * "map" represents the if condition.
3855 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_map
*map
,
3861 access
[type
] = create_test_access(isl_map_get_ctx(map
), scan
->n_test
++);
3862 scop
[type
] = extract_skip(scan
, isl_map_copy(map
),
3863 isl_map_copy(access
[type
]),
3864 scop_then
, scop_else
, have_else
, type
);
3867 /* Construct the required skip conditions, given the if condition "map".
3869 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_map
*map
)
3871 extract(scan
, map
, pet_skip_now
);
3872 extract(scan
, map
, pet_skip_later
);
3874 drop_skip_later(scop_then
, scop_else
);
3877 /* Construct the required skip conditions, given the if condition "cond".
3879 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_pw_aff
*cond
)
3884 if (!skip
[pet_skip_now
] && !skip
[pet_skip_later
])
3887 test_set
= isl_set_from_pw_aff(isl_pw_aff_copy(cond
));
3888 test
= isl_map_from_range(test_set
);
3889 extract(scan
, test
);
3893 /* Add the computed skip condition of the give type to "main" and
3894 * add the scop for computing the condition at the given offset.
3896 * If equal is set, then we only computed a skip condition for pet_skip_now,
3897 * but we also need to set it as main's pet_skip_later.
3899 struct pet_scop
*pet_skip_info_if::add(struct pet_scop
*main
,
3900 enum pet_skip type
, int offset
)
3907 skip_set
= isl_map_range(access
[type
]);
3908 access
[type
] = NULL
;
3909 scop
[type
] = pet_scop_prefix(scop
[type
], offset
);
3910 main
= pet_scop_add_par(ctx
, main
, scop
[type
]);
3914 main
= pet_scop_set_skip(main
, pet_skip_later
,
3915 isl_set_copy(skip_set
));
3917 main
= pet_scop_set_skip(main
, type
, skip_set
);
3922 /* Add the computed skip conditions to "main" and
3923 * add the scops for computing the conditions at the given offset.
3925 struct pet_scop
*pet_skip_info_if::add(struct pet_scop
*scop
, int offset
)
3927 scop
= add(scop
, pet_skip_now
, offset
);
3928 scop
= add(scop
, pet_skip_later
, offset
);
3933 /* Construct a pet_scop for a non-affine if statement.
3935 * We create a separate statement that writes the result
3936 * of the non-affine condition to a virtual scalar.
3937 * A constraint requiring the value of this virtual scalar to be one
3938 * is added to the iteration domains of the then branch.
3939 * Similarly, a constraint requiring the value of this virtual scalar
3940 * to be zero is added to the iteration domains of the else branch, if any.
3941 * We adjust the schedules to ensure that the virtual scalar is written
3942 * before it is read.
3944 * If there are any breaks or continues in the then and/or else
3945 * branches, then we may have to compute a new skip condition.
3946 * This is handled using a pet_skip_info_if object.
3947 * On initialization, the object checks if skip conditions need
3948 * to be computed. If so, it does so in "extract" and adds them in "add".
3950 struct pet_scop
*PetScan::extract_non_affine_if(Expr
*cond
,
3951 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3952 bool have_else
, int stmt_id
)
3954 struct pet_scop
*scop
;
3955 isl_map
*test_access
;
3956 int save_n_stmt
= n_stmt
;
3958 test_access
= create_test_access(ctx
, n_test
++);
3960 scop
= extract_non_affine_condition(cond
, isl_map_copy(test_access
));
3961 n_stmt
= save_n_stmt
;
3962 scop
= scop_add_array(scop
, test_access
, ast_context
);
3964 pet_skip_info_if
skip(ctx
, scop_then
, scop_else
, have_else
, false);
3965 skip
.extract(this, test_access
);
3967 scop
= pet_scop_prefix(scop
, 0);
3968 scop_then
= pet_scop_prefix(scop_then
, 1);
3969 scop_then
= pet_scop_filter(scop_then
, isl_map_copy(test_access
), 1);
3971 scop_else
= pet_scop_prefix(scop_else
, 1);
3972 scop_else
= pet_scop_filter(scop_else
, test_access
, 0);
3973 scop_then
= pet_scop_add_par(ctx
, scop_then
, scop_else
);
3975 isl_map_free(test_access
);
3977 scop
= pet_scop_add_seq(ctx
, scop
, scop_then
);
3979 scop
= skip
.add(scop
, 2);
3984 /* Construct a pet_scop for an if statement.
3986 * If the condition fits the pattern of a conditional assignment,
3987 * then it is handled by extract_conditional_assignment.
3988 * Otherwise, we do the following.
3990 * If the condition is affine, then the condition is added
3991 * to the iteration domains of the then branch, while the
3992 * opposite of the condition in added to the iteration domains
3993 * of the else branch, if any.
3994 * We allow the condition to be dynamic, i.e., to refer to
3995 * scalars or array elements that may be written to outside
3996 * of the given if statement. These nested accesses are then represented
3997 * as output dimensions in the wrapping iteration domain.
3998 * If it also written _inside_ the then or else branch, then
3999 * we treat the condition as non-affine.
4000 * As explained in extract_non_affine_if, this will introduce
4001 * an extra statement.
4002 * For aesthetic reasons, we want this statement to have a statement
4003 * number that is lower than those of the then and else branches.
4004 * In order to evaluate if will need such a statement, however, we
4005 * first construct scops for the then and else branches.
4006 * We therefore reserve a statement number if we might have to
4007 * introduce such an extra statement.
4009 * If the condition is not affine, then the scop is created in
4010 * extract_non_affine_if.
4012 * If there are any breaks or continues in the then and/or else
4013 * branches, then we may have to compute a new skip condition.
4014 * This is handled using a pet_skip_info_if object.
4015 * On initialization, the object checks if skip conditions need
4016 * to be computed. If so, it does so in "extract" and adds them in "add".
4018 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
4020 struct pet_scop
*scop_then
, *scop_else
= NULL
, *scop
;
4026 scop
= extract_conditional_assignment(stmt
);
4030 cond
= try_extract_nested_condition(stmt
->getCond());
4031 if (allow_nested
&& (!cond
|| has_nested(cond
)))
4035 assigned_value_cache
cache(assigned_value
);
4036 scop_then
= extract(stmt
->getThen());
4039 if (stmt
->getElse()) {
4040 assigned_value_cache
cache(assigned_value
);
4041 scop_else
= extract(stmt
->getElse());
4042 if (options
->autodetect
) {
4043 if (scop_then
&& !scop_else
) {
4045 isl_pw_aff_free(cond
);
4048 if (!scop_then
&& scop_else
) {
4050 isl_pw_aff_free(cond
);
4057 (!is_nested_allowed(cond
, scop_then
) ||
4058 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
4059 isl_pw_aff_free(cond
);
4062 if (allow_nested
&& !cond
)
4063 return extract_non_affine_if(stmt
->getCond(), scop_then
,
4064 scop_else
, stmt
->getElse(), stmt_id
);
4067 cond
= extract_condition(stmt
->getCond());
4069 pet_skip_info_if
skip(ctx
, scop_then
, scop_else
, stmt
->getElse(), true);
4070 skip
.extract(this, cond
);
4072 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
4073 set
= isl_pw_aff_non_zero_set(cond
);
4074 scop
= pet_scop_restrict(scop_then
, isl_set_copy(set
));
4076 if (stmt
->getElse()) {
4077 set
= isl_set_subtract(isl_set_copy(valid
), set
);
4078 scop_else
= pet_scop_restrict(scop_else
, set
);
4079 scop
= pet_scop_add_par(ctx
, scop
, scop_else
);
4082 scop
= resolve_nested(scop
);
4083 scop
= pet_scop_restrict_context(scop
, valid
);
4086 scop
= pet_scop_prefix(scop
, 0);
4087 scop
= skip
.add(scop
, 1);
4092 /* Try and construct a pet_scop for a label statement.
4093 * We currently only allow labels on expression statements.
4095 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
4100 sub
= stmt
->getSubStmt();
4101 if (!isa
<Expr
>(sub
)) {
4106 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
4108 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
4111 /* Construct a pet_scop for a continue statement.
4113 * We simply create an empty scop with a universal pet_skip_now
4114 * skip condition. This skip condition will then be taken into
4115 * account by the enclosing loop construct, possibly after
4116 * being incorporated into outer skip conditions.
4118 struct pet_scop
*PetScan::extract(ContinueStmt
*stmt
)
4124 scop
= pet_scop_empty(ctx
);
4128 space
= isl_space_set_alloc(ctx
, 0, 1);
4129 set
= isl_set_universe(space
);
4130 set
= isl_set_fix_si(set
, isl_dim_set
, 0, 1);
4131 scop
= pet_scop_set_skip(scop
, pet_skip_now
, set
);
4136 /* Construct a pet_scop for a break statement.
4138 * We simply create an empty scop with both a universal pet_skip_now
4139 * skip condition and a universal pet_skip_later skip condition.
4140 * These skip conditions will then be taken into
4141 * account by the enclosing loop construct, possibly after
4142 * being incorporated into outer skip conditions.
4144 struct pet_scop
*PetScan::extract(BreakStmt
*stmt
)
4150 scop
= pet_scop_empty(ctx
);
4154 space
= isl_space_set_alloc(ctx
, 0, 1);
4155 set
= isl_set_universe(space
);
4156 set
= isl_set_fix_si(set
, isl_dim_set
, 0, 1);
4157 scop
= pet_scop_set_skip(scop
, pet_skip_now
, isl_set_copy(set
));
4158 scop
= pet_scop_set_skip(scop
, pet_skip_later
, set
);
4163 /* Try and construct a pet_scop corresponding to "stmt".
4165 struct pet_scop
*PetScan::extract(Stmt
*stmt
)
4167 if (isa
<Expr
>(stmt
))
4168 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
4170 switch (stmt
->getStmtClass()) {
4171 case Stmt::WhileStmtClass
:
4172 return extract(cast
<WhileStmt
>(stmt
));
4173 case Stmt::ForStmtClass
:
4174 return extract_for(cast
<ForStmt
>(stmt
));
4175 case Stmt::IfStmtClass
:
4176 return extract(cast
<IfStmt
>(stmt
));
4177 case Stmt::CompoundStmtClass
:
4178 return extract(cast
<CompoundStmt
>(stmt
));
4179 case Stmt::LabelStmtClass
:
4180 return extract(cast
<LabelStmt
>(stmt
));
4181 case Stmt::ContinueStmtClass
:
4182 return extract(cast
<ContinueStmt
>(stmt
));
4183 case Stmt::BreakStmtClass
:
4184 return extract(cast
<BreakStmt
>(stmt
));
4192 /* Do we need to construct a skip condition of the given type
4193 * on a sequence of statements?
4195 * There is no need to construct a new skip condition if only
4196 * only of the two statements has a skip condition or if both
4197 * of their skip conditions are affine.
4199 * In principle we also don't need a new continuation variable if
4200 * the continuation of scop2 is affine, but then we would need
4201 * to allow more complicated forms of continuations.
4203 static bool need_skip_seq(struct pet_scop
*scop1
, struct pet_scop
*scop2
,
4206 if (!scop1
|| !pet_scop_has_skip(scop1
, type
))
4208 if (!scop2
|| !pet_scop_has_skip(scop2
, type
))
4210 if (pet_scop_has_affine_skip(scop1
, type
) &&
4211 pet_scop_has_affine_skip(scop2
, type
))
4216 /* Construct a scop for computing the skip condition of the given type and
4217 * with access relation "skip_access" for a sequence of two scops "scop1"
4220 * The computed scop contains a single statement that essentially does
4222 * skip_cond = skip_cond_1 ? 1 : skip_cond_2
4224 * or, in other words, skip_cond1 || skip_cond2.
4225 * In this expression, skip_cond_2 is filtered to reflect that it is
4226 * only evaluated when skip_cond_1 is false.
4228 * The skip condition on scop1 is not removed because it still needs
4229 * to be applied to scop2 when these two scops are combined.
4231 static struct pet_scop
*extract_skip_seq(PetScan
*ps
,
4232 __isl_take isl_map
*skip_access
,
4233 struct pet_scop
*scop1
, struct pet_scop
*scop2
, enum pet_skip type
)
4236 struct pet_expr
*expr1
, *expr2
, *expr
, *expr_skip
;
4237 struct pet_stmt
*stmt
;
4238 struct pet_scop
*scop
;
4239 isl_ctx
*ctx
= ps
->ctx
;
4241 if (!scop1
|| !scop2
)
4244 expr1
= pet_scop_get_skip_expr(scop1
, type
);
4245 expr2
= pet_scop_get_skip_expr(scop2
, type
);
4246 pet_scop_reset_skip(scop2
, type
);
4248 expr2
= pet_expr_filter(expr2
, isl_map_copy(expr1
->acc
.access
), 0);
4250 expr
= universally_true(ctx
);
4251 expr
= pet_expr_new_ternary(ctx
, expr1
, expr
, expr2
);
4252 expr_skip
= pet_expr_from_access(isl_map_copy(skip_access
));
4254 expr_skip
->acc
.write
= 1;
4255 expr_skip
->acc
.read
= 0;
4257 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, expr_skip
, expr
);
4258 stmt
= pet_stmt_from_pet_expr(ctx
, -1, NULL
, ps
->n_stmt
++, expr
);
4260 scop
= pet_scop_from_pet_stmt(ctx
, stmt
);
4261 scop
= scop_add_array(scop
, skip_access
, ps
->ast_context
);
4262 isl_map_free(skip_access
);
4266 isl_map_free(skip_access
);
4270 /* Structure that handles the construction of skip conditions
4271 * on sequences of statements.
4273 * scop1 and scop2 represent the two statements that are combined
4275 struct pet_skip_info_seq
: public pet_skip_info
{
4276 struct pet_scop
*scop1
, *scop2
;
4278 pet_skip_info_seq(isl_ctx
*ctx
, struct pet_scop
*scop1
,
4279 struct pet_scop
*scop2
);
4280 void extract(PetScan
*scan
, enum pet_skip type
);
4281 void extract(PetScan
*scan
);
4282 struct pet_scop
*add(struct pet_scop
*scop
, enum pet_skip type
,
4284 struct pet_scop
*add(struct pet_scop
*scop
, int offset
);
4287 /* Initialize a pet_skip_info_seq structure based on
4288 * on the two statements that are going to be combined.
4290 pet_skip_info_seq::pet_skip_info_seq(isl_ctx
*ctx
, struct pet_scop
*scop1
,
4291 struct pet_scop
*scop2
) : pet_skip_info(ctx
), scop1(scop1
), scop2(scop2
)
4293 skip
[pet_skip_now
] = need_skip_seq(scop1
, scop2
, pet_skip_now
);
4294 equal
= skip
[pet_skip_now
] && skip_equals_skip_later(scop1
) &&
4295 skip_equals_skip_later(scop2
);
4296 skip
[pet_skip_later
] = skip
[pet_skip_now
] && !equal
&&
4297 need_skip_seq(scop1
, scop2
, pet_skip_later
);
4300 /* If we need to construct a skip condition of the given type,
4303 void pet_skip_info_seq::extract(PetScan
*scan
, enum pet_skip type
)
4308 access
[type
] = create_test_access(ctx
, scan
->n_test
++);
4309 scop
[type
] = extract_skip_seq(scan
, isl_map_copy(access
[type
]),
4310 scop1
, scop2
, type
);
4313 /* Construct the required skip conditions.
4315 void pet_skip_info_seq::extract(PetScan
*scan
)
4317 extract(scan
, pet_skip_now
);
4318 extract(scan
, pet_skip_later
);
4320 drop_skip_later(scop1
, scop2
);
4323 /* Add the computed skip condition of the give type to "main" and
4324 * add the scop for computing the condition at the given offset (the statement
4325 * number). Within this offset, the condition is computed at position 1
4326 * to ensure that it is computed after the corresponding statement.
4328 * If equal is set, then we only computed a skip condition for pet_skip_now,
4329 * but we also need to set it as main's pet_skip_later.
4331 struct pet_scop
*pet_skip_info_seq::add(struct pet_scop
*main
,
4332 enum pet_skip type
, int offset
)
4339 skip_set
= isl_map_range(access
[type
]);
4340 access
[type
] = NULL
;
4341 scop
[type
] = pet_scop_prefix(scop
[type
], 1);
4342 scop
[type
] = pet_scop_prefix(scop
[type
], offset
);
4343 main
= pet_scop_add_par(ctx
, main
, scop
[type
]);
4347 main
= pet_scop_set_skip(main
, pet_skip_later
,
4348 isl_set_copy(skip_set
));
4350 main
= pet_scop_set_skip(main
, type
, skip_set
);
4355 /* Add the computed skip conditions to "main" and
4356 * add the scops for computing the conditions at the given offset.
4358 struct pet_scop
*pet_skip_info_seq::add(struct pet_scop
*scop
, int offset
)
4360 scop
= add(scop
, pet_skip_now
, offset
);
4361 scop
= add(scop
, pet_skip_later
, offset
);
4366 /* Try and construct a pet_scop corresponding to (part of)
4367 * a sequence of statements.
4369 * If there are any breaks or continues in the individual statements,
4370 * then we may have to compute a new skip condition.
4371 * This is handled using a pet_skip_info_seq object.
4372 * On initialization, the object checks if skip conditions need
4373 * to be computed. If so, it does so in "extract" and adds them in "add".
4375 struct pet_scop
*PetScan::extract(StmtRange stmt_range
)
4380 bool partial_range
= false;
4382 scop
= pet_scop_empty(ctx
);
4383 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
4385 struct pet_scop
*scop_i
;
4387 scop_i
= extract(child
);
4388 if (scop
&& partial
) {
4389 pet_scop_free(scop_i
);
4392 pet_skip_info_seq
skip(ctx
, scop
, scop_i
);
4395 scop_i
= pet_scop_prefix(scop_i
, 0);
4396 scop_i
= pet_scop_prefix(scop_i
, j
);
4397 if (options
->autodetect
) {
4399 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4401 partial_range
= true;
4402 if (scop
->n_stmt
!= 0 && !scop_i
)
4405 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4408 scop
= skip
.add(scop
, j
);
4414 if (scop
&& partial_range
)
4420 /* Check if the scop marked by the user is exactly this Stmt
4421 * or part of this Stmt.
4422 * If so, return a pet_scop corresponding to the marked region.
4423 * Otherwise, return NULL.
4425 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
4427 SourceManager
&SM
= PP
.getSourceManager();
4428 unsigned start_off
, end_off
;
4430 start_off
= SM
.getFileOffset(stmt
->getLocStart());
4431 end_off
= SM
.getFileOffset(stmt
->getLocEnd());
4433 if (start_off
> loc
.end
)
4435 if (end_off
< loc
.start
)
4437 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
4438 return extract(stmt
);
4442 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
4443 Stmt
*child
= *start
;
4446 start_off
= SM
.getFileOffset(child
->getLocStart());
4447 end_off
= SM
.getFileOffset(child
->getLocEnd());
4448 if (start_off
< loc
.start
&& end_off
> loc
.end
)
4450 if (start_off
>= loc
.start
)
4455 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
4457 start_off
= SM
.getFileOffset(child
->getLocStart());
4458 if (start_off
>= loc
.end
)
4462 return extract(StmtRange(start
, end
));
4465 /* Set the size of index "pos" of "array" to "size".
4466 * In particular, add a constraint of the form
4470 * to array->extent and a constraint of the form
4474 * to array->context.
4476 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
4477 __isl_take isl_pw_aff
*size
)
4487 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
4488 array
->context
= isl_set_intersect(array
->context
, valid
);
4490 dim
= isl_set_get_space(array
->extent
);
4491 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
4492 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
4493 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
4494 index
= isl_pw_aff_alloc(univ
, aff
);
4496 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
4497 isl_set_dim(array
->extent
, isl_dim_set
));
4498 id
= isl_set_get_tuple_id(array
->extent
);
4499 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
4500 bound
= isl_pw_aff_lt_set(index
, size
);
4502 array
->extent
= isl_set_intersect(array
->extent
, bound
);
4504 if (!array
->context
|| !array
->extent
)
4509 pet_array_free(array
);
4513 /* Figure out the size of the array at position "pos" and all
4514 * subsequent positions from "type" and update "array" accordingly.
4516 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
4517 const Type
*type
, int pos
)
4519 const ArrayType
*atype
;
4525 if (type
->isPointerType()) {
4526 type
= type
->getPointeeType().getTypePtr();
4527 return set_upper_bounds(array
, type
, pos
+ 1);
4529 if (!type
->isArrayType())
4532 type
= type
->getCanonicalTypeInternal().getTypePtr();
4533 atype
= cast
<ArrayType
>(type
);
4535 if (type
->isConstantArrayType()) {
4536 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
4537 size
= extract_affine(ca
->getSize());
4538 array
= update_size(array
, pos
, size
);
4539 } else if (type
->isVariableArrayType()) {
4540 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
4541 size
= extract_affine(vla
->getSizeExpr());
4542 array
= update_size(array
, pos
, size
);
4545 type
= atype
->getElementType().getTypePtr();
4547 return set_upper_bounds(array
, type
, pos
+ 1);
4550 /* Construct and return a pet_array corresponding to the variable "decl".
4551 * In particular, initialize array->extent to
4553 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4555 * and then call set_upper_bounds to set the upper bounds on the indices
4556 * based on the type of the variable.
4558 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
)
4560 struct pet_array
*array
;
4561 QualType qt
= decl
->getType();
4562 const Type
*type
= qt
.getTypePtr();
4563 int depth
= array_depth(type
);
4564 QualType base
= base_type(qt
);
4569 array
= isl_calloc_type(ctx
, struct pet_array
);
4573 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
4574 dim
= isl_space_set_alloc(ctx
, 0, depth
);
4575 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
4577 array
->extent
= isl_set_nat_universe(dim
);
4579 dim
= isl_space_params_alloc(ctx
, 0);
4580 array
->context
= isl_set_universe(dim
);
4582 array
= set_upper_bounds(array
, type
, 0);
4586 name
= base
.getAsString();
4587 array
->element_type
= strdup(name
.c_str());
4588 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
4593 /* Construct a list of pet_arrays, one for each array (or scalar)
4594 * accessed inside "scop", add this list to "scop" and return the result.
4596 * The context of "scop" is updated with the intersection of
4597 * the contexts of all arrays, i.e., constraints on the parameters
4598 * that ensure that the arrays have a valid (non-negative) size.
4600 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
4603 set
<ValueDecl
*> arrays
;
4604 set
<ValueDecl
*>::iterator it
;
4606 struct pet_array
**scop_arrays
;
4611 pet_scop_collect_arrays(scop
, arrays
);
4612 if (arrays
.size() == 0)
4615 n_array
= scop
->n_array
;
4617 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
4618 n_array
+ arrays
.size());
4621 scop
->arrays
= scop_arrays
;
4623 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
4624 struct pet_array
*array
;
4625 scop
->arrays
[n_array
+ i
] = array
= extract_array(ctx
, *it
);
4626 if (!scop
->arrays
[n_array
+ i
])
4629 scop
->context
= isl_set_intersect(scop
->context
,
4630 isl_set_copy(array
->context
));
4637 pet_scop_free(scop
);
4641 /* Bound all parameters in scop->context to the possible values
4642 * of the corresponding C variable.
4644 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
4651 n
= isl_set_dim(scop
->context
, isl_dim_param
);
4652 for (int i
= 0; i
< n
; ++i
) {
4656 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
4657 if (is_nested_parameter(id
)) {
4659 isl_die(isl_set_get_ctx(scop
->context
),
4661 "unresolved nested parameter", goto error
);
4663 decl
= (ValueDecl
*) isl_id_get_user(id
);
4666 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
4674 pet_scop_free(scop
);
4678 /* Construct a pet_scop from the given function.
4680 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
4685 stmt
= fd
->getBody();
4687 if (options
->autodetect
)
4688 scop
= extract(stmt
);
4691 scop
= pet_scop_detect_parameter_accesses(scop
);
4692 scop
= scan_arrays(scop
);
4693 scop
= add_parameter_bounds(scop
);
4694 scop
= pet_scop_gist(scop
, value_bounds
);