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
39 #include <llvm/Support/raw_ostream.h>
40 #include <clang/AST/ASTContext.h>
41 #include <clang/AST/ASTDiagnostic.h>
42 #include <clang/AST/Expr.h>
43 #include <clang/AST/RecursiveASTVisitor.h>
46 #include <isl/space.h>
53 #include "scop_plus.h"
58 using namespace clang
;
60 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
61 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
63 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
64 SourceLocation(), var
, false, var
->getInnerLocStart(),
65 var
->getType(), VK_LValue
);
67 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
68 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
70 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
71 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
75 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
77 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
78 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
82 /* Check if the element type corresponding to the given array type
83 * has a const qualifier.
85 static bool const_base(QualType qt
)
87 const Type
*type
= qt
.getTypePtr();
89 if (type
->isPointerType())
90 return const_base(type
->getPointeeType());
91 if (type
->isArrayType()) {
92 const ArrayType
*atype
;
93 type
= type
->getCanonicalTypeInternal().getTypePtr();
94 atype
= cast
<ArrayType
>(type
);
95 return const_base(atype
->getElementType());
98 return qt
.isConstQualified();
101 /* Mark "decl" as having an unknown value in "assigned_value".
103 * If no (known or unknown) value was assigned to "decl" before,
104 * then it may have been treated as a parameter before and may
105 * therefore appear in a value assigned to another variable.
106 * If so, this assignment needs to be turned into an unknown value too.
108 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
111 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
113 it
= assigned_value
.find(decl
);
115 assigned_value
[decl
] = NULL
;
117 if (it
== assigned_value
.end())
120 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
121 isl_pw_aff
*pa
= it
->second
;
122 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
124 for (int i
= 0; i
< nparam
; ++i
) {
127 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
129 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
130 if (isl_id_get_user(id
) == decl
)
137 /* Look for any assignments to scalar variables in part of the parse
138 * tree and set assigned_value to NULL for each of them.
139 * Also reset assigned_value if the address of a scalar variable
140 * is being taken. As an exception, if the address is passed to a function
141 * that is declared to receive a const pointer, then assigned_value is
144 * This ensures that we won't use any previously stored value
145 * in the current subtree and its parents.
147 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
148 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
149 set
<UnaryOperator
*> skip
;
151 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
152 assigned_value(assigned_value
) {}
154 /* Check for "address of" operators whose value is passed
155 * to a const pointer argument and add them to "skip", so that
156 * we can skip them in VisitUnaryOperator.
158 bool VisitCallExpr(CallExpr
*expr
) {
160 fd
= expr
->getDirectCallee();
163 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
164 Expr
*arg
= expr
->getArg(i
);
166 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
167 ImplicitCastExpr
*ice
;
168 ice
= cast
<ImplicitCastExpr
>(arg
);
169 arg
= ice
->getSubExpr();
171 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
173 op
= cast
<UnaryOperator
>(arg
);
174 if (op
->getOpcode() != UO_AddrOf
)
176 if (const_base(fd
->getParamDecl(i
)->getType()))
182 bool VisitUnaryOperator(UnaryOperator
*expr
) {
187 switch (expr
->getOpcode()) {
197 if (skip
.find(expr
) != skip
.end())
200 arg
= expr
->getSubExpr();
201 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
203 ref
= cast
<DeclRefExpr
>(arg
);
204 decl
= ref
->getDecl();
205 clear_assignment(assigned_value
, decl
);
209 bool VisitBinaryOperator(BinaryOperator
*expr
) {
214 if (!expr
->isAssignmentOp())
216 lhs
= expr
->getLHS();
217 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
219 ref
= cast
<DeclRefExpr
>(lhs
);
220 decl
= ref
->getDecl();
221 clear_assignment(assigned_value
, decl
);
226 /* Keep a copy of the currently assigned values.
228 * Any variable that is assigned a value inside the current scope
229 * is removed again when we leave the scope (either because it wasn't
230 * stored in the cache or because it has a different value in the cache).
232 struct assigned_value_cache
{
233 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
234 map
<ValueDecl
*, isl_pw_aff
*> cache
;
236 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
237 assigned_value(assigned_value
), cache(assigned_value
) {}
238 ~assigned_value_cache() {
239 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
240 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
243 (cache
.find(it
->first
) != cache
.end() &&
244 cache
[it
->first
] != it
->second
))
245 cache
[it
->first
] = NULL
;
247 assigned_value
= cache
;
251 /* Insert an expression into the collection of expressions,
252 * provided it is not already in there.
253 * The isl_pw_affs are freed in the destructor.
255 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
257 std::set
<isl_pw_aff
*>::iterator it
;
259 if (expressions
.find(expr
) == expressions
.end())
260 expressions
.insert(expr
);
262 isl_pw_aff_free(expr
);
267 std::set
<isl_pw_aff
*>::iterator it
;
269 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
270 isl_pw_aff_free(*it
);
272 isl_union_map_free(value_bounds
);
275 /* Called if we found something we (currently) cannot handle.
276 * We'll provide more informative warnings later.
278 * We only actually complain if autodetect is false.
280 void PetScan::unsupported(Stmt
*stmt
, const char *msg
)
282 if (options
->autodetect
)
285 SourceLocation loc
= stmt
->getLocStart();
286 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
287 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
288 msg
? msg
: "unsupported");
289 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
292 /* Extract an integer from "expr".
294 __isl_give isl_val
*PetScan::extract_int(isl_ctx
*ctx
, IntegerLiteral
*expr
)
296 const Type
*type
= expr
->getType().getTypePtr();
297 int is_signed
= type
->hasSignedIntegerRepresentation();
300 int64_t i
= expr
->getValue().getSExtValue();
301 return isl_val_int_from_si(ctx
, i
);
303 uint64_t i
= expr
->getValue().getZExtValue();
304 return isl_val_int_from_ui(ctx
, i
);
308 /* Extract an integer from "expr".
309 * Return NULL if "expr" does not (obviously) represent an integer.
311 __isl_give isl_val
*PetScan::extract_int(clang::ParenExpr
*expr
)
313 return extract_int(expr
->getSubExpr());
316 /* Extract an integer from "expr".
317 * Return NULL if "expr" does not (obviously) represent an integer.
319 __isl_give isl_val
*PetScan::extract_int(clang::Expr
*expr
)
321 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
322 return extract_int(ctx
, cast
<IntegerLiteral
>(expr
));
323 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
324 return extract_int(cast
<ParenExpr
>(expr
));
330 /* Extract an affine expression from the IntegerLiteral "expr".
332 __isl_give isl_pw_aff
*PetScan::extract_affine(IntegerLiteral
*expr
)
334 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
335 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
336 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
337 isl_set
*dom
= isl_set_universe(dim
);
340 v
= extract_int(expr
);
341 aff
= isl_aff_add_constant_val(aff
, v
);
343 return isl_pw_aff_alloc(dom
, aff
);
346 /* Extract an affine expression from the APInt "val".
348 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
350 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
351 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
352 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
353 isl_set
*dom
= isl_set_universe(dim
);
357 isl_int_set_ui(v
, val
.getZExtValue());
358 aff
= isl_aff_add_constant(aff
, v
);
361 return isl_pw_aff_alloc(dom
, aff
);
364 __isl_give isl_pw_aff
*PetScan::extract_affine(ImplicitCastExpr
*expr
)
366 return extract_affine(expr
->getSubExpr());
369 static unsigned get_type_size(ValueDecl
*decl
)
371 return decl
->getASTContext().getIntWidth(decl
->getType());
374 /* Bound parameter "pos" of "set" to the possible values of "decl".
376 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
377 unsigned pos
, ValueDecl
*decl
)
384 width
= get_type_size(decl
);
385 if (decl
->getType()->isUnsignedIntegerType()) {
386 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
387 isl_int_set_si(v
, 1);
388 isl_int_mul_2exp(v
, v
, width
);
389 isl_int_sub_ui(v
, v
, 1);
390 set
= isl_set_upper_bound(set
, isl_dim_param
, pos
, v
);
392 isl_int_set_si(v
, 1);
393 isl_int_mul_2exp(v
, v
, width
- 1);
394 isl_int_sub_ui(v
, v
, 1);
395 set
= isl_set_upper_bound(set
, isl_dim_param
, pos
, v
);
397 isl_int_sub_ui(v
, v
, 1);
398 set
= isl_set_lower_bound(set
, isl_dim_param
, pos
, v
);
406 /* Extract an affine expression from the DeclRefExpr "expr".
408 * If the variable has been assigned a value, then we check whether
409 * we know what (affine) value was assigned.
410 * If so, we return this value. Otherwise we convert "expr"
411 * to an extra parameter (provided nesting_enabled is set).
413 * Otherwise, we simply return an expression that is equal
414 * to a parameter corresponding to the referenced variable.
416 __isl_give isl_pw_aff
*PetScan::extract_affine(DeclRefExpr
*expr
)
418 ValueDecl
*decl
= expr
->getDecl();
419 const Type
*type
= decl
->getType().getTypePtr();
425 if (!type
->isIntegerType()) {
430 if (assigned_value
.find(decl
) != assigned_value
.end()) {
431 if (assigned_value
[decl
])
432 return isl_pw_aff_copy(assigned_value
[decl
]);
434 return nested_access(expr
);
437 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
438 dim
= isl_space_params_alloc(ctx
, 1);
440 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
442 dom
= isl_set_universe(isl_space_copy(dim
));
443 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
444 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
446 return isl_pw_aff_alloc(dom
, aff
);
449 /* Extract an affine expression from an integer division operation.
450 * In particular, if "expr" is lhs/rhs, then return
452 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
454 * The second argument (rhs) is required to be a (positive) integer constant.
456 __isl_give isl_pw_aff
*PetScan::extract_affine_div(BinaryOperator
*expr
)
459 isl_pw_aff
*rhs
, *lhs
;
461 rhs
= extract_affine(expr
->getRHS());
462 is_cst
= isl_pw_aff_is_cst(rhs
);
463 if (is_cst
< 0 || !is_cst
) {
464 isl_pw_aff_free(rhs
);
470 lhs
= extract_affine(expr
->getLHS());
472 return isl_pw_aff_tdiv_q(lhs
, rhs
);
475 /* Extract an affine expression from a modulo operation.
476 * In particular, if "expr" is lhs/rhs, then return
478 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
480 * The second argument (rhs) is required to be a (positive) integer constant.
482 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
485 isl_pw_aff
*rhs
, *lhs
;
487 rhs
= extract_affine(expr
->getRHS());
488 is_cst
= isl_pw_aff_is_cst(rhs
);
489 if (is_cst
< 0 || !is_cst
) {
490 isl_pw_aff_free(rhs
);
496 lhs
= extract_affine(expr
->getLHS());
498 return isl_pw_aff_tdiv_r(lhs
, rhs
);
501 /* Extract an affine expression from a multiplication operation.
502 * This is only allowed if at least one of the two arguments
503 * is a (piecewise) constant.
505 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
510 lhs
= extract_affine(expr
->getLHS());
511 rhs
= extract_affine(expr
->getRHS());
513 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
514 isl_pw_aff_free(lhs
);
515 isl_pw_aff_free(rhs
);
520 return isl_pw_aff_mul(lhs
, rhs
);
523 /* Extract an affine expression from an addition or subtraction operation.
525 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
530 lhs
= extract_affine(expr
->getLHS());
531 rhs
= extract_affine(expr
->getRHS());
533 switch (expr
->getOpcode()) {
535 return isl_pw_aff_add(lhs
, rhs
);
537 return isl_pw_aff_sub(lhs
, rhs
);
539 isl_pw_aff_free(lhs
);
540 isl_pw_aff_free(rhs
);
550 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
556 isl_int_set_si(mod
, 1);
557 isl_int_mul_2exp(mod
, mod
, width
);
559 pwaff
= isl_pw_aff_mod(pwaff
, mod
);
566 /* Limit the domain of "pwaff" to those elements where the function
569 * 2^{width-1} <= pwaff < 2^{width-1}
571 static __isl_give isl_pw_aff
*avoid_overflow(__isl_take isl_pw_aff
*pwaff
,
575 isl_space
*space
= isl_pw_aff_get_domain_space(pwaff
);
576 isl_local_space
*ls
= isl_local_space_from_space(space
);
582 isl_int_set_si(v
, 1);
583 isl_int_mul_2exp(v
, v
, width
- 1);
585 bound
= isl_aff_zero_on_domain(ls
);
586 bound
= isl_aff_add_constant(bound
, v
);
587 b
= isl_pw_aff_from_aff(bound
);
589 dom
= isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff
), isl_pw_aff_copy(b
));
590 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
592 b
= isl_pw_aff_neg(b
);
593 dom
= isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff
), b
);
594 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
601 /* Handle potential overflows on signed computations.
603 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
604 * the we adjust the domain of "pa" to avoid overflows.
606 __isl_give isl_pw_aff
*PetScan::signed_overflow(__isl_take isl_pw_aff
*pa
,
609 if (options
->signed_overflow
== PET_OVERFLOW_AVOID
)
610 pa
= avoid_overflow(pa
, width
);
615 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
617 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
618 __isl_take isl_set
*dom
)
621 pa
= isl_set_indicator_function(set
);
622 pa
= isl_pw_aff_intersect_domain(pa
, dom
);
626 /* Extract an affine expression from some binary operations.
627 * If the result of the expression is unsigned, then we wrap it
628 * based on the size of the type. Otherwise, we ensure that
629 * no overflow occurs.
631 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
636 switch (expr
->getOpcode()) {
639 res
= extract_affine_add(expr
);
642 res
= extract_affine_div(expr
);
645 res
= extract_affine_mod(expr
);
648 res
= extract_affine_mul(expr
);
658 return extract_condition(expr
);
664 width
= ast_context
.getIntWidth(expr
->getType());
665 if (expr
->getType()->isUnsignedIntegerType())
666 res
= wrap(res
, width
);
668 res
= signed_overflow(res
, width
);
673 /* Extract an affine expression from a negation operation.
675 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
677 if (expr
->getOpcode() == UO_Minus
)
678 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
679 if (expr
->getOpcode() == UO_LNot
)
680 return extract_condition(expr
);
686 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
688 return extract_affine(expr
->getSubExpr());
691 /* Extract an affine expression from some special function calls.
692 * In particular, we handle "min", "max", "ceild" and "floord".
693 * In case of the latter two, the second argument needs to be
694 * a (positive) integer constant.
696 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
700 isl_pw_aff
*aff1
, *aff2
;
702 fd
= expr
->getDirectCallee();
708 name
= fd
->getDeclName().getAsString();
709 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
710 !(expr
->getNumArgs() == 2 && name
== "max") &&
711 !(expr
->getNumArgs() == 2 && name
== "floord") &&
712 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
717 if (name
== "min" || name
== "max") {
718 aff1
= extract_affine(expr
->getArg(0));
719 aff2
= extract_affine(expr
->getArg(1));
722 aff1
= isl_pw_aff_min(aff1
, aff2
);
724 aff1
= isl_pw_aff_max(aff1
, aff2
);
725 } else if (name
== "floord" || name
== "ceild") {
727 Expr
*arg2
= expr
->getArg(1);
729 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
733 aff1
= extract_affine(expr
->getArg(0));
734 v
= extract_int(cast
<IntegerLiteral
>(arg2
));
735 aff1
= isl_pw_aff_scale_down_val(aff1
, v
);
736 if (name
== "floord")
737 aff1
= isl_pw_aff_floor(aff1
);
739 aff1
= isl_pw_aff_ceil(aff1
);
748 /* This method is called when we come across an access that is
749 * nested in what is supposed to be an affine expression.
750 * If nesting is allowed, we return a new parameter that corresponds
751 * to this nested access. Otherwise, we simply complain.
753 * Note that we currently don't allow nested accesses themselves
754 * to contain any nested accesses, so we check if we can extract
755 * the access without any nesting and complain if we can't.
757 * The new parameter is resolved in resolve_nested.
759 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
767 if (!nesting_enabled
) {
772 allow_nested
= false;
773 access
= extract_access(expr
);
779 isl_map_free(access
);
781 id
= isl_id_alloc(ctx
, NULL
, expr
);
782 dim
= isl_space_params_alloc(ctx
, 1);
784 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
786 dom
= isl_set_universe(isl_space_copy(dim
));
787 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
788 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
790 return isl_pw_aff_alloc(dom
, aff
);
793 /* Affine expressions are not supposed to contain array accesses,
794 * but if nesting is allowed, we return a parameter corresponding
795 * to the array access.
797 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
799 return nested_access(expr
);
802 /* Extract an affine expression from a conditional operation.
804 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
806 isl_pw_aff
*cond
, *lhs
, *rhs
, *res
;
808 cond
= extract_condition(expr
->getCond());
809 lhs
= extract_affine(expr
->getTrueExpr());
810 rhs
= extract_affine(expr
->getFalseExpr());
812 return isl_pw_aff_cond(cond
, lhs
, rhs
);
815 /* Extract an affine expression, if possible, from "expr".
816 * Otherwise return NULL.
818 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
820 switch (expr
->getStmtClass()) {
821 case Stmt::ImplicitCastExprClass
:
822 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
823 case Stmt::IntegerLiteralClass
:
824 return extract_affine(cast
<IntegerLiteral
>(expr
));
825 case Stmt::DeclRefExprClass
:
826 return extract_affine(cast
<DeclRefExpr
>(expr
));
827 case Stmt::BinaryOperatorClass
:
828 return extract_affine(cast
<BinaryOperator
>(expr
));
829 case Stmt::UnaryOperatorClass
:
830 return extract_affine(cast
<UnaryOperator
>(expr
));
831 case Stmt::ParenExprClass
:
832 return extract_affine(cast
<ParenExpr
>(expr
));
833 case Stmt::CallExprClass
:
834 return extract_affine(cast
<CallExpr
>(expr
));
835 case Stmt::ArraySubscriptExprClass
:
836 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
837 case Stmt::ConditionalOperatorClass
:
838 return extract_affine(cast
<ConditionalOperator
>(expr
));
845 __isl_give isl_map
*PetScan::extract_access(ImplicitCastExpr
*expr
)
847 return extract_access(expr
->getSubExpr());
850 /* Return the depth of an array of the given type.
852 static int array_depth(const Type
*type
)
854 if (type
->isPointerType())
855 return 1 + array_depth(type
->getPointeeType().getTypePtr());
856 if (type
->isArrayType()) {
857 const ArrayType
*atype
;
858 type
= type
->getCanonicalTypeInternal().getTypePtr();
859 atype
= cast
<ArrayType
>(type
);
860 return 1 + array_depth(atype
->getElementType().getTypePtr());
865 /* Return the element type of the given array type.
867 static QualType
base_type(QualType qt
)
869 const Type
*type
= qt
.getTypePtr();
871 if (type
->isPointerType())
872 return base_type(type
->getPointeeType());
873 if (type
->isArrayType()) {
874 const ArrayType
*atype
;
875 type
= type
->getCanonicalTypeInternal().getTypePtr();
876 atype
= cast
<ArrayType
>(type
);
877 return base_type(atype
->getElementType());
882 /* Extract an access relation from a reference to a variable.
883 * If the variable has name "A" and its type corresponds to an
884 * array of depth d, then the returned access relation is of the
887 * { [] -> A[i_1,...,i_d] }
889 __isl_give isl_map
*PetScan::extract_access(DeclRefExpr
*expr
)
891 return extract_access(expr
->getDecl());
894 /* Extract an access relation from a variable.
895 * If the variable has name "A" and its type corresponds to an
896 * array of depth d, then the returned access relation is of the
899 * { [] -> A[i_1,...,i_d] }
901 __isl_give isl_map
*PetScan::extract_access(ValueDecl
*decl
)
903 int depth
= array_depth(decl
->getType().getTypePtr());
904 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
905 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, depth
);
908 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
910 access_rel
= isl_map_universe(dim
);
915 /* Extract an access relation from an integer contant.
916 * If the value of the constant is "v", then the returned access relation
921 __isl_give isl_map
*PetScan::extract_access(IntegerLiteral
*expr
)
923 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr
)));
926 /* Try and extract an access relation from the given Expr.
927 * Return NULL if it doesn't work out.
929 __isl_give isl_map
*PetScan::extract_access(Expr
*expr
)
931 switch (expr
->getStmtClass()) {
932 case Stmt::ImplicitCastExprClass
:
933 return extract_access(cast
<ImplicitCastExpr
>(expr
));
934 case Stmt::DeclRefExprClass
:
935 return extract_access(cast
<DeclRefExpr
>(expr
));
936 case Stmt::ArraySubscriptExprClass
:
937 return extract_access(cast
<ArraySubscriptExpr
>(expr
));
938 case Stmt::IntegerLiteralClass
:
939 return extract_access(cast
<IntegerLiteral
>(expr
));
946 /* Assign the affine expression "index" to the output dimension "pos" of "map",
947 * restrict the domain to those values that result in a non-negative index
948 * and return the result.
950 __isl_give isl_map
*set_index(__isl_take isl_map
*map
, int pos
,
951 __isl_take isl_pw_aff
*index
)
954 int len
= isl_map_dim(map
, isl_dim_out
);
958 domain
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(index
));
959 index
= isl_pw_aff_intersect_domain(index
, domain
);
960 index_map
= isl_map_from_range(isl_set_from_pw_aff(index
));
961 index_map
= isl_map_insert_dims(index_map
, isl_dim_out
, 0, pos
);
962 index_map
= isl_map_add_dims(index_map
, isl_dim_out
, len
- pos
- 1);
963 id
= isl_map_get_tuple_id(map
, isl_dim_out
);
964 index_map
= isl_map_set_tuple_id(index_map
, isl_dim_out
, id
);
966 map
= isl_map_intersect(map
, index_map
);
971 /* Extract an access relation from the given array subscript expression.
972 * If nesting is allowed in general, then we turn it on while
973 * examining the index expression.
975 * We first extract an access relation from the base.
976 * This will result in an access relation with a range that corresponds
977 * to the array being accessed and with earlier indices filled in already.
978 * We then extract the current index and fill that in as well.
979 * The position of the current index is based on the type of base.
980 * If base is the actual array variable, then the depth of this type
981 * will be the same as the depth of the array and we will fill in
982 * the first array index.
983 * Otherwise, the depth of the base type will be smaller and we will fill
986 __isl_give isl_map
*PetScan::extract_access(ArraySubscriptExpr
*expr
)
988 Expr
*base
= expr
->getBase();
989 Expr
*idx
= expr
->getIdx();
991 isl_map
*base_access
;
993 int depth
= array_depth(base
->getType().getTypePtr());
995 bool save_nesting
= nesting_enabled
;
997 nesting_enabled
= allow_nested
;
999 base_access
= extract_access(base
);
1000 index
= extract_affine(idx
);
1002 nesting_enabled
= save_nesting
;
1004 pos
= isl_map_dim(base_access
, isl_dim_out
) - depth
;
1005 access
= set_index(base_access
, pos
, index
);
1010 /* Check if "expr" calls function "minmax" with two arguments and if so
1011 * make lhs and rhs refer to these two arguments.
1013 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
1019 if (expr
->getStmtClass() != Stmt::CallExprClass
)
1022 call
= cast
<CallExpr
>(expr
);
1023 fd
= call
->getDirectCallee();
1027 if (call
->getNumArgs() != 2)
1030 name
= fd
->getDeclName().getAsString();
1034 lhs
= call
->getArg(0);
1035 rhs
= call
->getArg(1);
1040 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1041 * lhs and rhs refer to the two arguments.
1043 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1045 return is_minmax(expr
, "min", lhs
, rhs
);
1048 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1049 * lhs and rhs refer to the two arguments.
1051 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1053 return is_minmax(expr
, "max", lhs
, rhs
);
1056 /* Return "lhs && rhs", defined on the shared definition domain.
1058 static __isl_give isl_pw_aff
*pw_aff_and(__isl_take isl_pw_aff
*lhs
,
1059 __isl_take isl_pw_aff
*rhs
)
1064 dom
= isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs
)),
1065 isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1066 cond
= isl_set_intersect(isl_pw_aff_non_zero_set(lhs
),
1067 isl_pw_aff_non_zero_set(rhs
));
1068 return indicator_function(cond
, dom
);
1071 /* Return "lhs && rhs", with shortcut semantics.
1072 * That is, if lhs is false, then the result is defined even if rhs is not.
1073 * In practice, we compute lhs ? rhs : lhs.
1075 static __isl_give isl_pw_aff
*pw_aff_and_then(__isl_take isl_pw_aff
*lhs
,
1076 __isl_take isl_pw_aff
*rhs
)
1078 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), rhs
, lhs
);
1081 /* Return "lhs || rhs", with shortcut semantics.
1082 * That is, if lhs is true, then the result is defined even if rhs is not.
1083 * In practice, we compute lhs ? lhs : rhs.
1085 static __isl_give isl_pw_aff
*pw_aff_or_else(__isl_take isl_pw_aff
*lhs
,
1086 __isl_take isl_pw_aff
*rhs
)
1088 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), lhs
, rhs
);
1091 /* Extract an affine expressions representing the comparison "LHS op RHS"
1092 * "comp" is the original statement that "LHS op RHS" is derived from
1093 * and is used for diagnostics.
1095 * If the comparison is of the form
1099 * then the expression is constructed as the conjunction of
1104 * A similar optimization is performed for max(a,b) <= c.
1105 * We do this because that will lead to simpler representations
1106 * of the expression.
1107 * If isl is ever enhanced to explicitly deal with min and max expressions,
1108 * this optimization can be removed.
1110 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
1111 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
1120 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
1122 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
1124 if (op
== BO_LT
|| op
== BO_LE
) {
1125 Expr
*expr1
, *expr2
;
1126 if (is_min(RHS
, expr1
, expr2
)) {
1127 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
1128 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
1129 return pw_aff_and(lhs
, rhs
);
1131 if (is_max(LHS
, expr1
, expr2
)) {
1132 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
1133 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
1134 return pw_aff_and(lhs
, rhs
);
1138 lhs
= extract_affine(LHS
);
1139 rhs
= extract_affine(RHS
);
1141 dom
= isl_pw_aff_domain(isl_pw_aff_copy(lhs
));
1142 dom
= isl_set_intersect(dom
, isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1146 cond
= isl_pw_aff_lt_set(lhs
, rhs
);
1149 cond
= isl_pw_aff_le_set(lhs
, rhs
);
1152 cond
= isl_pw_aff_eq_set(lhs
, rhs
);
1155 cond
= isl_pw_aff_ne_set(lhs
, rhs
);
1158 isl_pw_aff_free(lhs
);
1159 isl_pw_aff_free(rhs
);
1165 cond
= isl_set_coalesce(cond
);
1166 res
= indicator_function(cond
, dom
);
1171 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
1173 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1174 comp
->getRHS(), comp
);
1177 /* Extract an affine expression representing the negation (logical not)
1178 * of a subexpression.
1180 __isl_give isl_pw_aff
*PetScan::extract_boolean(UnaryOperator
*op
)
1182 isl_set
*set_cond
, *dom
;
1183 isl_pw_aff
*cond
, *res
;
1185 cond
= extract_condition(op
->getSubExpr());
1187 dom
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
1189 set_cond
= isl_pw_aff_zero_set(cond
);
1191 res
= indicator_function(set_cond
, dom
);
1196 /* Extract an affine expression representing the disjunction (logical or)
1197 * or conjunction (logical and) of two subexpressions.
1199 __isl_give isl_pw_aff
*PetScan::extract_boolean(BinaryOperator
*comp
)
1201 isl_pw_aff
*lhs
, *rhs
;
1203 lhs
= extract_condition(comp
->getLHS());
1204 rhs
= extract_condition(comp
->getRHS());
1206 switch (comp
->getOpcode()) {
1208 return pw_aff_and_then(lhs
, rhs
);
1210 return pw_aff_or_else(lhs
, rhs
);
1212 isl_pw_aff_free(lhs
);
1213 isl_pw_aff_free(rhs
);
1220 __isl_give isl_pw_aff
*PetScan::extract_condition(UnaryOperator
*expr
)
1222 switch (expr
->getOpcode()) {
1224 return extract_boolean(expr
);
1231 /* Extract the affine expression "expr != 0 ? 1 : 0".
1233 __isl_give isl_pw_aff
*PetScan::extract_implicit_condition(Expr
*expr
)
1238 res
= extract_affine(expr
);
1240 dom
= isl_pw_aff_domain(isl_pw_aff_copy(res
));
1241 set
= isl_pw_aff_non_zero_set(res
);
1243 res
= indicator_function(set
, dom
);
1248 /* Extract an affine expression from a boolean expression.
1249 * In particular, return the expression "expr ? 1 : 0".
1251 * If the expression doesn't look like a condition, we assume it
1252 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1254 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
1256 BinaryOperator
*comp
;
1259 isl_set
*u
= isl_set_universe(isl_space_params_alloc(ctx
, 0));
1260 return indicator_function(u
, isl_set_copy(u
));
1263 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1264 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1266 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1267 return extract_condition(cast
<UnaryOperator
>(expr
));
1269 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1270 return extract_implicit_condition(expr
);
1272 comp
= cast
<BinaryOperator
>(expr
);
1273 switch (comp
->getOpcode()) {
1280 return extract_comparison(comp
);
1283 return extract_boolean(comp
);
1285 return extract_implicit_condition(expr
);
1289 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
1293 return pet_op_minus
;
1295 return pet_op_post_inc
;
1297 return pet_op_post_dec
;
1299 return pet_op_pre_inc
;
1301 return pet_op_pre_dec
;
1307 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
1311 return pet_op_add_assign
;
1313 return pet_op_sub_assign
;
1315 return pet_op_mul_assign
;
1317 return pet_op_div_assign
;
1319 return pet_op_assign
;
1343 /* Construct a pet_expr representing a unary operator expression.
1345 struct pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1347 struct pet_expr
*arg
;
1348 enum pet_op_type op
;
1350 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1351 if (op
== pet_op_last
) {
1356 arg
= extract_expr(expr
->getSubExpr());
1358 if (expr
->isIncrementDecrementOp() &&
1359 arg
&& arg
->type
== pet_expr_access
) {
1364 return pet_expr_new_unary(ctx
, op
, arg
);
1367 /* Mark the given access pet_expr as a write.
1368 * If a scalar is being accessed, then mark its value
1369 * as unknown in assigned_value.
1371 void PetScan::mark_write(struct pet_expr
*access
)
1379 access
->acc
.write
= 1;
1380 access
->acc
.read
= 0;
1382 if (isl_map_dim(access
->acc
.access
, isl_dim_out
) != 0)
1385 id
= isl_map_get_tuple_id(access
->acc
.access
, isl_dim_out
);
1386 decl
= (ValueDecl
*) isl_id_get_user(id
);
1387 clear_assignment(assigned_value
, decl
);
1391 /* Assign "rhs" to "lhs".
1393 * In particular, if "lhs" is a scalar variable, then mark
1394 * the variable as having been assigned. If, furthermore, "rhs"
1395 * is an affine expression, then keep track of this value in assigned_value
1396 * so that we can plug it in when we later come across the same variable.
1398 void PetScan::assign(struct pet_expr
*lhs
, Expr
*rhs
)
1406 if (lhs
->type
!= pet_expr_access
)
1408 if (isl_map_dim(lhs
->acc
.access
, isl_dim_out
) != 0)
1411 id
= isl_map_get_tuple_id(lhs
->acc
.access
, isl_dim_out
);
1412 decl
= (ValueDecl
*) isl_id_get_user(id
);
1415 pa
= try_extract_affine(rhs
);
1416 clear_assignment(assigned_value
, decl
);
1419 assigned_value
[decl
] = pa
;
1420 insert_expression(pa
);
1423 /* Construct a pet_expr representing a binary operator expression.
1425 * If the top level operator is an assignment and the LHS is an access,
1426 * then we mark that access as a write. If the operator is a compound
1427 * assignment, the access is marked as both a read and a write.
1429 * If "expr" assigns something to a scalar variable, then we mark
1430 * the variable as having been assigned. If, furthermore, the expression
1431 * is affine, then keep track of this value in assigned_value
1432 * so that we can plug it in when we later come across the same variable.
1434 struct pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1436 struct pet_expr
*lhs
, *rhs
;
1437 enum pet_op_type op
;
1439 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1440 if (op
== pet_op_last
) {
1445 lhs
= extract_expr(expr
->getLHS());
1446 rhs
= extract_expr(expr
->getRHS());
1448 if (expr
->isAssignmentOp() && lhs
&& lhs
->type
== pet_expr_access
) {
1450 if (expr
->isCompoundAssignmentOp())
1454 if (expr
->getOpcode() == BO_Assign
)
1455 assign(lhs
, expr
->getRHS());
1457 return pet_expr_new_binary(ctx
, op
, lhs
, rhs
);
1460 /* Construct a pet_scop with a single statement killing the entire
1463 struct pet_scop
*PetScan::kill(Stmt
*stmt
, struct pet_array
*array
)
1466 struct pet_expr
*expr
;
1470 access
= isl_map_from_range(isl_set_copy(array
->extent
));
1471 expr
= pet_expr_kill_from_access(access
);
1472 return extract(stmt
, expr
);
1475 /* Construct a pet_scop for a (single) variable declaration.
1477 * The scop contains the variable being declared (as an array)
1478 * and a statement killing the array.
1480 * If the variable is initialized in the AST, then the scop
1481 * also contains an assignment to the variable.
1483 struct pet_scop
*PetScan::extract(DeclStmt
*stmt
)
1487 struct pet_expr
*lhs
, *rhs
, *pe
;
1488 struct pet_scop
*scop_decl
, *scop
;
1489 struct pet_array
*array
;
1491 if (!stmt
->isSingleDecl()) {
1496 decl
= stmt
->getSingleDecl();
1497 vd
= cast
<VarDecl
>(decl
);
1499 array
= extract_array(ctx
, vd
);
1501 array
->declared
= 1;
1502 scop_decl
= kill(stmt
, array
);
1503 scop_decl
= pet_scop_add_array(scop_decl
, array
);
1508 lhs
= pet_expr_from_access(extract_access(vd
));
1509 rhs
= extract_expr(vd
->getInit());
1512 assign(lhs
, vd
->getInit());
1514 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, lhs
, rhs
);
1515 scop
= extract(stmt
, pe
);
1517 scop_decl
= pet_scop_prefix(scop_decl
, 0);
1518 scop
= pet_scop_prefix(scop
, 1);
1520 scop
= pet_scop_add_seq(ctx
, scop_decl
, scop
);
1525 /* Construct a pet_expr representing a conditional operation.
1527 * We first try to extract the condition as an affine expression.
1528 * If that fails, we construct a pet_expr tree representing the condition.
1530 struct pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1532 struct pet_expr
*cond
, *lhs
, *rhs
;
1535 pa
= try_extract_affine(expr
->getCond());
1537 isl_set
*test
= isl_set_from_pw_aff(pa
);
1538 cond
= pet_expr_from_access(isl_map_from_range(test
));
1540 cond
= extract_expr(expr
->getCond());
1541 lhs
= extract_expr(expr
->getTrueExpr());
1542 rhs
= extract_expr(expr
->getFalseExpr());
1544 return pet_expr_new_ternary(ctx
, cond
, lhs
, rhs
);
1547 struct pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1549 return extract_expr(expr
->getSubExpr());
1552 /* Construct a pet_expr representing a floating point value.
1554 * If the floating point literal does not appear in a macro,
1555 * then we use the original representation in the source code
1556 * as the string representation. Otherwise, we use the pretty
1557 * printer to produce a string representation.
1559 struct pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1563 const LangOptions
&LO
= PP
.getLangOpts();
1564 SourceLocation loc
= expr
->getLocation();
1566 if (!loc
.isMacroID()) {
1567 SourceManager
&SM
= PP
.getSourceManager();
1568 unsigned len
= Lexer::MeasureTokenLength(loc
, SM
, LO
);
1569 s
= string(SM
.getCharacterData(loc
), len
);
1571 llvm::raw_string_ostream
S(s
);
1572 expr
->printPretty(S
, 0, PrintingPolicy(LO
));
1575 d
= expr
->getValueAsApproximateDouble();
1576 return pet_expr_new_double(ctx
, d
, s
.c_str());
1579 /* Extract an access relation from "expr" and then convert it into
1582 struct pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1585 struct pet_expr
*pe
;
1587 access
= extract_access(expr
);
1589 pe
= pet_expr_from_access(access
);
1594 struct pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1596 return extract_expr(expr
->getSubExpr());
1599 /* Construct a pet_expr representing a function call.
1601 * If we are passing along a pointer to an array element
1602 * or an entire row or even higher dimensional slice of an array,
1603 * then the function being called may write into the array.
1605 * We assume here that if the function is declared to take a pointer
1606 * to a const type, then the function will perform a read
1607 * and that otherwise, it will perform a write.
1609 struct pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1611 struct pet_expr
*res
= NULL
;
1615 fd
= expr
->getDirectCallee();
1621 name
= fd
->getDeclName().getAsString();
1622 res
= pet_expr_new_call(ctx
, name
.c_str(), expr
->getNumArgs());
1626 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
1627 Expr
*arg
= expr
->getArg(i
);
1631 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1632 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(arg
);
1633 arg
= ice
->getSubExpr();
1635 if (arg
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1636 UnaryOperator
*op
= cast
<UnaryOperator
>(arg
);
1637 if (op
->getOpcode() == UO_AddrOf
) {
1639 arg
= op
->getSubExpr();
1642 res
->args
[i
] = PetScan::extract_expr(arg
);
1643 main_arg
= res
->args
[i
];
1645 res
->args
[i
] = pet_expr_new_unary(ctx
,
1646 pet_op_address_of
, res
->args
[i
]);
1649 if (arg
->getStmtClass() == Stmt::ArraySubscriptExprClass
&&
1650 array_depth(arg
->getType().getTypePtr()) > 0)
1652 if (is_addr
&& main_arg
->type
== pet_expr_access
) {
1654 if (!fd
->hasPrototype()) {
1655 unsupported(expr
, "prototype required");
1658 parm
= fd
->getParamDecl(i
);
1659 if (!const_base(parm
->getType()))
1660 mark_write(main_arg
);
1670 /* Construct a pet_expr representing a (C style) cast.
1672 struct pet_expr
*PetScan::extract_expr(CStyleCastExpr
*expr
)
1674 struct pet_expr
*arg
;
1677 arg
= extract_expr(expr
->getSubExpr());
1681 type
= expr
->getTypeAsWritten();
1682 return pet_expr_new_cast(ctx
, type
.getAsString().c_str(), arg
);
1685 /* Try and onstruct a pet_expr representing "expr".
1687 struct pet_expr
*PetScan::extract_expr(Expr
*expr
)
1689 switch (expr
->getStmtClass()) {
1690 case Stmt::UnaryOperatorClass
:
1691 return extract_expr(cast
<UnaryOperator
>(expr
));
1692 case Stmt::CompoundAssignOperatorClass
:
1693 case Stmt::BinaryOperatorClass
:
1694 return extract_expr(cast
<BinaryOperator
>(expr
));
1695 case Stmt::ImplicitCastExprClass
:
1696 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1697 case Stmt::ArraySubscriptExprClass
:
1698 case Stmt::DeclRefExprClass
:
1699 case Stmt::IntegerLiteralClass
:
1700 return extract_access_expr(expr
);
1701 case Stmt::FloatingLiteralClass
:
1702 return extract_expr(cast
<FloatingLiteral
>(expr
));
1703 case Stmt::ParenExprClass
:
1704 return extract_expr(cast
<ParenExpr
>(expr
));
1705 case Stmt::ConditionalOperatorClass
:
1706 return extract_expr(cast
<ConditionalOperator
>(expr
));
1707 case Stmt::CallExprClass
:
1708 return extract_expr(cast
<CallExpr
>(expr
));
1709 case Stmt::CStyleCastExprClass
:
1710 return extract_expr(cast
<CStyleCastExpr
>(expr
));
1717 /* Check if the given initialization statement is an assignment.
1718 * If so, return that assignment. Otherwise return NULL.
1720 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1722 BinaryOperator
*ass
;
1724 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1727 ass
= cast
<BinaryOperator
>(init
);
1728 if (ass
->getOpcode() != BO_Assign
)
1734 /* Check if the given initialization statement is a declaration
1735 * of a single variable.
1736 * If so, return that declaration. Otherwise return NULL.
1738 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1742 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1745 decl
= cast
<DeclStmt
>(init
);
1747 if (!decl
->isSingleDecl())
1750 return decl
->getSingleDecl();
1753 /* Given the assignment operator in the initialization of a for loop,
1754 * extract the induction variable, i.e., the (integer)variable being
1757 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1764 lhs
= init
->getLHS();
1765 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1770 ref
= cast
<DeclRefExpr
>(lhs
);
1771 decl
= ref
->getDecl();
1772 type
= decl
->getType().getTypePtr();
1774 if (!type
->isIntegerType()) {
1782 /* Given the initialization statement of a for loop and the single
1783 * declaration in this initialization statement,
1784 * extract the induction variable, i.e., the (integer) variable being
1787 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1791 vd
= cast
<VarDecl
>(decl
);
1793 const QualType type
= vd
->getType();
1794 if (!type
->isIntegerType()) {
1799 if (!vd
->getInit()) {
1807 /* Check that op is of the form iv++ or iv--.
1808 * Return an affine expression "1" or "-1" accordingly.
1810 __isl_give isl_pw_aff
*PetScan::extract_unary_increment(
1811 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1818 if (!op
->isIncrementDecrementOp()) {
1823 sub
= op
->getSubExpr();
1824 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1829 ref
= cast
<DeclRefExpr
>(sub
);
1830 if (ref
->getDecl() != iv
) {
1835 space
= isl_space_params_alloc(ctx
, 0);
1836 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
1838 if (op
->isIncrementOp())
1839 aff
= isl_aff_add_constant_si(aff
, 1);
1841 aff
= isl_aff_add_constant_si(aff
, -1);
1843 return isl_pw_aff_from_aff(aff
);
1846 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1847 * has a single constant expression, then put this constant in *user.
1848 * The caller is assumed to have checked that this function will
1849 * be called exactly once.
1851 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
1854 isl_int
*inc
= (isl_int
*)user
;
1857 if (isl_aff_is_cst(aff
))
1858 isl_aff_get_constant(aff
, inc
);
1868 /* Check if op is of the form
1872 * and return inc as an affine expression.
1874 * We extract an affine expression from the RHS, subtract iv and return
1877 __isl_give isl_pw_aff
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1878 clang::ValueDecl
*iv
)
1887 if (op
->getOpcode() != BO_Assign
) {
1893 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1898 ref
= cast
<DeclRefExpr
>(lhs
);
1899 if (ref
->getDecl() != iv
) {
1904 val
= extract_affine(op
->getRHS());
1906 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1908 dim
= isl_space_params_alloc(ctx
, 1);
1909 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1910 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1911 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1913 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
1918 /* Check that op is of the form iv += cst or iv -= cst
1919 * and return an affine expression corresponding oto cst or -cst accordingly.
1921 __isl_give isl_pw_aff
*PetScan::extract_compound_increment(
1922 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1928 BinaryOperatorKind opcode
;
1930 opcode
= op
->getOpcode();
1931 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1935 if (opcode
== BO_SubAssign
)
1939 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1944 ref
= cast
<DeclRefExpr
>(lhs
);
1945 if (ref
->getDecl() != iv
) {
1950 val
= extract_affine(op
->getRHS());
1952 val
= isl_pw_aff_neg(val
);
1957 /* Check that the increment of the given for loop increments
1958 * (or decrements) the induction variable "iv" and return
1959 * the increment as an affine expression if successful.
1961 __isl_give isl_pw_aff
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1964 Stmt
*inc
= stmt
->getInc();
1971 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1972 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1973 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1974 return extract_compound_increment(
1975 cast
<CompoundAssignOperator
>(inc
), iv
);
1976 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1977 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1983 /* Embed the given iteration domain in an extra outer loop
1984 * with induction variable "var".
1985 * If this variable appeared as a parameter in the constraints,
1986 * it is replaced by the new outermost dimension.
1988 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1989 __isl_take isl_id
*var
)
1993 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1994 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1996 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1997 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2004 /* Return those elements in the space of "cond" that come after
2005 * (based on "sign") an element in "cond".
2007 static __isl_give isl_set
*after(__isl_take isl_set
*cond
, int sign
)
2009 isl_map
*previous_to_this
;
2012 previous_to_this
= isl_map_lex_lt(isl_set_get_space(cond
));
2014 previous_to_this
= isl_map_lex_gt(isl_set_get_space(cond
));
2016 cond
= isl_set_apply(cond
, previous_to_this
);
2021 /* Create the infinite iteration domain
2023 * { [id] : id >= 0 }
2025 * If "scop" has an affine skip of type pet_skip_later,
2026 * then remove those iterations i that have an earlier iteration
2027 * where the skip condition is satisfied, meaning that iteration i
2029 * Since we are dealing with a loop without loop iterator,
2030 * the skip condition cannot refer to the current loop iterator and
2031 * so effectively, the returned set is of the form
2033 * { [0]; [id] : id >= 1 and not skip }
2035 static __isl_give isl_set
*infinite_domain(__isl_take isl_id
*id
,
2036 struct pet_scop
*scop
)
2038 isl_ctx
*ctx
= isl_id_get_ctx(id
);
2042 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
2043 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, id
);
2045 if (!pet_scop_has_affine_skip(scop
, pet_skip_later
))
2048 skip
= pet_scop_get_skip(scop
, pet_skip_later
);
2049 skip
= isl_set_fix_si(skip
, isl_dim_set
, 0, 1);
2050 skip
= isl_set_params(skip
);
2051 skip
= embed(skip
, isl_id_copy(id
));
2052 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2053 domain
= isl_set_subtract(domain
, after(skip
, 1));
2058 /* Create an identity mapping on the space containing "domain".
2060 static __isl_give isl_map
*identity_map(__isl_keep isl_set
*domain
)
2065 space
= isl_space_map_from_set(isl_set_get_space(domain
));
2066 id
= isl_map_identity(space
);
2071 /* Add a filter to "scop" that imposes that it is only executed
2072 * when "break_access" has a zero value for all previous iterations
2075 * The input "break_access" has a zero-dimensional domain and range.
2077 static struct pet_scop
*scop_add_break(struct pet_scop
*scop
,
2078 __isl_take isl_map
*break_access
, __isl_take isl_set
*domain
, int sign
)
2080 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
2084 id_test
= isl_map_get_tuple_id(break_access
, isl_dim_out
);
2085 break_access
= isl_map_add_dims(break_access
, isl_dim_in
, 1);
2086 break_access
= isl_map_add_dims(break_access
, isl_dim_out
, 1);
2087 break_access
= isl_map_intersect_range(break_access
, domain
);
2088 break_access
= isl_map_set_tuple_id(break_access
, isl_dim_out
, id_test
);
2090 prev
= isl_map_lex_gt_first(isl_map_get_space(break_access
), 1);
2092 prev
= isl_map_lex_lt_first(isl_map_get_space(break_access
), 1);
2093 break_access
= isl_map_intersect(break_access
, prev
);
2094 scop
= pet_scop_filter(scop
, break_access
, 0);
2095 scop
= pet_scop_merge_filters(scop
);
2100 /* Construct a pet_scop for an infinite loop around the given body.
2102 * We extract a pet_scop for the body and then embed it in a loop with
2111 * If the body contains any break, then it is taken into
2112 * account in infinite_domain (if the skip condition is affine)
2113 * or in scop_add_break (if the skip condition is not affine).
2115 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
2121 struct pet_scop
*scop
;
2124 scop
= extract(body
);
2128 id
= isl_id_alloc(ctx
, "t", NULL
);
2129 domain
= infinite_domain(isl_id_copy(id
), scop
);
2130 ident
= identity_map(domain
);
2132 has_var_break
= pet_scop_has_var_skip(scop
, pet_skip_later
);
2134 access
= pet_scop_get_skip_map(scop
, pet_skip_later
);
2136 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
2137 isl_map_copy(ident
), ident
, id
);
2139 scop
= scop_add_break(scop
, access
, domain
, 1);
2141 isl_set_free(domain
);
2146 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2152 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
2154 return extract_infinite_loop(stmt
->getBody());
2157 /* Create an access to a virtual array representing the result
2159 * Unlike other accessed data, the id of the array is NULL as
2160 * there is no ValueDecl in the program corresponding to the virtual
2162 * The array starts out as a scalar, but grows along with the
2163 * statement writing to the array in pet_scop_embed.
2165 static __isl_give isl_map
*create_test_access(isl_ctx
*ctx
, int test_nr
)
2167 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, 0);
2171 snprintf(name
, sizeof(name
), "__pet_test_%d", test_nr
);
2172 id
= isl_id_alloc(ctx
, name
, NULL
);
2173 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
2174 return isl_map_universe(dim
);
2177 /* Add an array with the given extent ("access") to the list
2178 * of arrays in "scop" and return the extended pet_scop.
2179 * The array is marked as attaining values 0 and 1 only and
2180 * as each element being assigned at most once.
2182 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2183 __isl_keep isl_map
*access
, clang::ASTContext
&ast_ctx
)
2185 isl_ctx
*ctx
= isl_map_get_ctx(access
);
2187 struct pet_array
*array
;
2194 array
= isl_calloc_type(ctx
, struct pet_array
);
2198 array
->extent
= isl_map_range(isl_map_copy(access
));
2199 dim
= isl_space_params_alloc(ctx
, 0);
2200 array
->context
= isl_set_universe(dim
);
2201 dim
= isl_space_set_alloc(ctx
, 0, 1);
2202 array
->value_bounds
= isl_set_universe(dim
);
2203 array
->value_bounds
= isl_set_lower_bound_si(array
->value_bounds
,
2205 array
->value_bounds
= isl_set_upper_bound_si(array
->value_bounds
,
2207 array
->element_type
= strdup("int");
2208 array
->element_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
2209 array
->uniquely_defined
= 1;
2211 if (!array
->extent
|| !array
->context
)
2212 array
= pet_array_free(array
);
2214 scop
= pet_scop_add_array(scop
, array
);
2218 pet_scop_free(scop
);
2222 /* Construct a pet_scop for a while loop of the form
2227 * In particular, construct a scop for an infinite loop around body and
2228 * intersect the domain with the affine expression.
2229 * Note that this intersection may result in an empty loop.
2231 struct pet_scop
*PetScan::extract_affine_while(__isl_take isl_pw_aff
*pa
,
2234 struct pet_scop
*scop
;
2238 valid
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2239 dom
= isl_pw_aff_non_zero_set(pa
);
2240 scop
= extract_infinite_loop(body
);
2241 scop
= pet_scop_restrict(scop
, dom
);
2242 scop
= pet_scop_restrict_context(scop
, valid
);
2247 /* Construct a scop for a while, given the scops for the condition
2248 * and the body, the filter access and the iteration domain of
2251 * In particular, the scop for the condition is filtered to depend
2252 * on "test_access" evaluating to true for all previous iterations
2253 * of the loop, while the scop for the body is filtered to depend
2254 * on "test_access" evaluating to true for all iterations up to the
2255 * current iteration.
2257 * These filtered scops are then combined into a single scop.
2259 * "sign" is positive if the iterator increases and negative
2262 static struct pet_scop
*scop_add_while(struct pet_scop
*scop_cond
,
2263 struct pet_scop
*scop_body
, __isl_take isl_map
*test_access
,
2264 __isl_take isl_set
*domain
, int sign
)
2266 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
2270 id_test
= isl_map_get_tuple_id(test_access
, isl_dim_out
);
2271 test_access
= isl_map_add_dims(test_access
, isl_dim_in
, 1);
2272 test_access
= isl_map_add_dims(test_access
, isl_dim_out
, 1);
2273 test_access
= isl_map_intersect_range(test_access
, domain
);
2274 test_access
= isl_map_set_tuple_id(test_access
, isl_dim_out
, id_test
);
2276 prev
= isl_map_lex_ge_first(isl_map_get_space(test_access
), 1);
2278 prev
= isl_map_lex_le_first(isl_map_get_space(test_access
), 1);
2279 test_access
= isl_map_intersect(test_access
, prev
);
2280 scop_body
= pet_scop_filter(scop_body
, isl_map_copy(test_access
), 1);
2282 prev
= isl_map_lex_gt_first(isl_map_get_space(test_access
), 1);
2284 prev
= isl_map_lex_lt_first(isl_map_get_space(test_access
), 1);
2285 test_access
= isl_map_intersect(test_access
, prev
);
2286 scop_cond
= pet_scop_filter(scop_cond
, test_access
, 1);
2288 return pet_scop_add_seq(ctx
, scop_cond
, scop_body
);
2291 /* Check if the while loop is of the form
2293 * while (affine expression)
2296 * If so, call extract_affine_while to construct a scop.
2298 * Otherwise, construct a generic while scop, with iteration domain
2299 * { [t] : t >= 0 }. The scop consists of two parts, one for
2300 * evaluating the condition and one for the body.
2301 * The schedule is adjusted to reflect that the condition is evaluated
2302 * before the body is executed and the body is filtered to depend
2303 * on the result of the condition evaluating to true on all iterations
2304 * up to the current iteration, while the evaluation the condition itself
2305 * is filtered to depend on the result of the condition evaluating to true
2306 * on all previous iterations.
2307 * The context of the scop representing the body is dropped
2308 * because we don't know how many times the body will be executed,
2311 * If the body contains any break, then it is taken into
2312 * account in infinite_domain (if the skip condition is affine)
2313 * or in scop_add_break (if the skip condition is not affine).
2315 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
2319 isl_map
*test_access
;
2323 struct pet_scop
*scop
, *scop_body
;
2325 isl_map
*break_access
;
2327 cond
= stmt
->getCond();
2333 clear_assignments
clear(assigned_value
);
2334 clear
.TraverseStmt(stmt
->getBody());
2336 pa
= try_extract_affine_condition(cond
);
2338 return extract_affine_while(pa
, stmt
->getBody());
2340 if (!allow_nested
) {
2345 test_access
= create_test_access(ctx
, n_test
++);
2346 scop
= extract_non_affine_condition(cond
, isl_map_copy(test_access
));
2347 scop
= scop_add_array(scop
, test_access
, ast_context
);
2348 scop_body
= extract(stmt
->getBody());
2350 id
= isl_id_alloc(ctx
, "t", NULL
);
2351 domain
= infinite_domain(isl_id_copy(id
), scop_body
);
2352 ident
= identity_map(domain
);
2354 has_var_break
= pet_scop_has_var_skip(scop_body
, pet_skip_later
);
2356 break_access
= pet_scop_get_skip_map(scop_body
, pet_skip_later
);
2358 scop
= pet_scop_prefix(scop
, 0);
2359 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), isl_map_copy(ident
),
2360 isl_map_copy(ident
), isl_id_copy(id
));
2361 scop_body
= pet_scop_reset_context(scop_body
);
2362 scop_body
= pet_scop_prefix(scop_body
, 1);
2363 scop_body
= pet_scop_embed(scop_body
, isl_set_copy(domain
),
2364 isl_map_copy(ident
), ident
, id
);
2366 if (has_var_break
) {
2367 scop
= scop_add_break(scop
, isl_map_copy(break_access
),
2368 isl_set_copy(domain
), 1);
2369 scop_body
= scop_add_break(scop_body
, break_access
,
2370 isl_set_copy(domain
), 1);
2372 scop
= scop_add_while(scop
, scop_body
, test_access
, domain
, 1);
2377 /* Check whether "cond" expresses a simple loop bound
2378 * on the only set dimension.
2379 * In particular, if "up" is set then "cond" should contain only
2380 * upper bounds on the set dimension.
2381 * Otherwise, it should contain only lower bounds.
2383 static bool is_simple_bound(__isl_keep isl_set
*cond
, isl_int inc
)
2385 if (isl_int_is_pos(inc
))
2386 return !isl_set_dim_has_any_lower_bound(cond
, isl_dim_set
, 0);
2388 return !isl_set_dim_has_any_upper_bound(cond
, isl_dim_set
, 0);
2391 /* Extend a condition on a given iteration of a loop to one that
2392 * imposes the same condition on all previous iterations.
2393 * "domain" expresses the lower [upper] bound on the iterations
2394 * when inc is positive [negative].
2396 * In particular, we construct the condition (when inc is positive)
2398 * forall i' : (domain(i') and i' <= i) => cond(i')
2400 * which is equivalent to
2402 * not exists i' : domain(i') and i' <= i and not cond(i')
2404 * We construct this set by negating cond, applying a map
2406 * { [i'] -> [i] : domain(i') and i' <= i }
2408 * and then negating the result again.
2410 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
2411 __isl_take isl_set
*domain
, isl_int inc
)
2413 isl_map
*previous_to_this
;
2415 if (isl_int_is_pos(inc
))
2416 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
2418 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
2420 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
2422 cond
= isl_set_complement(cond
);
2423 cond
= isl_set_apply(cond
, previous_to_this
);
2424 cond
= isl_set_complement(cond
);
2429 /* Construct a domain of the form
2431 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2433 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
2434 __isl_take isl_pw_aff
*init
, isl_int inc
)
2440 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
2441 dim
= isl_pw_aff_get_domain_space(init
);
2442 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2443 aff
= isl_aff_add_coefficient(aff
, isl_dim_in
, 0, inc
);
2444 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2446 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2447 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2448 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2449 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2451 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2453 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2455 return isl_set_params(set
);
2458 /* Assuming "cond" represents a bound on a loop where the loop
2459 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2462 * Under the given assumptions, wrapping is only possible if "cond" allows
2463 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2464 * increasing iterator and 0 in case of a decreasing iterator.
2466 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
, isl_int inc
)
2472 test
= isl_set_copy(cond
);
2474 isl_int_init(limit
);
2475 if (isl_int_is_neg(inc
))
2476 isl_int_set_si(limit
, 0);
2478 isl_int_set_si(limit
, 1);
2479 isl_int_mul_2exp(limit
, limit
, get_type_size(iv
));
2480 isl_int_sub_ui(limit
, limit
, 1);
2483 test
= isl_set_fix(cond
, isl_dim_set
, 0, limit
);
2484 cw
= !isl_set_is_empty(test
);
2487 isl_int_clear(limit
);
2492 /* Given a one-dimensional space, construct the following mapping on this
2495 * { [v] -> [v mod 2^width] }
2497 * where width is the number of bits used to represent the values
2498 * of the unsigned variable "iv".
2500 static __isl_give isl_map
*compute_wrapping(__isl_take isl_space
*dim
,
2508 isl_int_set_si(mod
, 1);
2509 isl_int_mul_2exp(mod
, mod
, get_type_size(iv
));
2511 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2512 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2513 aff
= isl_aff_mod(aff
, mod
);
2517 return isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2518 map
= isl_map_reverse(map
);
2521 /* Project out the parameter "id" from "set".
2523 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2524 __isl_keep isl_id
*id
)
2528 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2530 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2535 /* Compute the set of parameters for which "set1" is a subset of "set2".
2537 * set1 is a subset of set2 if
2539 * forall i in set1 : i in set2
2543 * not exists i in set1 and i not in set2
2547 * not exists i in set1 \ set2
2549 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2550 __isl_take isl_set
*set2
)
2552 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2555 /* Compute the set of parameter values for which "cond" holds
2556 * on the next iteration for each element of "dom".
2558 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2559 * and then compute the set of parameters for which the result is a subset
2562 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2563 __isl_take isl_set
*dom
, isl_int inc
)
2569 space
= isl_set_get_space(dom
);
2570 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2571 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2572 aff
= isl_aff_add_constant(aff
, inc
);
2573 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2575 dom
= isl_set_apply(dom
, next
);
2577 return enforce_subset(dom
, cond
);
2580 /* Does "id" refer to a nested access?
2582 static bool is_nested_parameter(__isl_keep isl_id
*id
)
2584 return id
&& isl_id_get_user(id
) && !isl_id_get_name(id
);
2587 /* Does parameter "pos" of "space" refer to a nested access?
2589 static bool is_nested_parameter(__isl_keep isl_space
*space
, int pos
)
2594 id
= isl_space_get_dim_id(space
, isl_dim_param
, pos
);
2595 nested
= is_nested_parameter(id
);
2601 /* Does "space" involve any parameters that refer to nested
2602 * accesses, i.e., parameters with no name?
2604 static bool has_nested(__isl_keep isl_space
*space
)
2608 nparam
= isl_space_dim(space
, isl_dim_param
);
2609 for (int i
= 0; i
< nparam
; ++i
)
2610 if (is_nested_parameter(space
, i
))
2616 /* Does "pa" involve any parameters that refer to nested
2617 * accesses, i.e., parameters with no name?
2619 static bool has_nested(__isl_keep isl_pw_aff
*pa
)
2624 space
= isl_pw_aff_get_space(pa
);
2625 nested
= has_nested(space
);
2626 isl_space_free(space
);
2631 /* Construct a pet_scop for a for statement.
2632 * The for loop is required to be of the form
2634 * for (i = init; condition; ++i)
2638 * for (i = init; condition; --i)
2640 * The initialization of the for loop should either be an assignment
2641 * to an integer variable, or a declaration of such a variable with
2644 * The condition is allowed to contain nested accesses, provided
2645 * they are not being written to inside the body of the loop.
2646 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2647 * essentially treated as a while loop, with iteration domain
2648 * { [i] : i >= init }.
2650 * We extract a pet_scop for the body and then embed it in a loop with
2651 * iteration domain and schedule
2653 * { [i] : i >= init and condition' }
2658 * { [i] : i <= init and condition' }
2661 * Where condition' is equal to condition if the latter is
2662 * a simple upper [lower] bound and a condition that is extended
2663 * to apply to all previous iterations otherwise.
2665 * If the condition is non-affine, then we drop the condition from the
2666 * iteration domain and instead create a separate statement
2667 * for evaluating the condition. The body is then filtered to depend
2668 * on the result of the condition evaluating to true on all iterations
2669 * up to the current iteration, while the evaluation the condition itself
2670 * is filtered to depend on the result of the condition evaluating to true
2671 * on all previous iterations.
2672 * The context of the scop representing the body is dropped
2673 * because we don't know how many times the body will be executed,
2676 * If the stride of the loop is not 1, then "i >= init" is replaced by
2678 * (exists a: i = init + stride * a and a >= 0)
2680 * If the loop iterator i is unsigned, then wrapping may occur.
2681 * During the computation, we work with a virtual iterator that
2682 * does not wrap. However, the condition in the code applies
2683 * to the wrapped value, so we need to change condition(i)
2684 * into condition([i % 2^width]).
2685 * After computing the virtual domain and schedule, we apply
2686 * the function { [v] -> [v % 2^width] } to the domain and the domain
2687 * of the schedule. In order not to lose any information, we also
2688 * need to intersect the domain of the schedule with the virtual domain
2689 * first, since some iterations in the wrapped domain may be scheduled
2690 * several times, typically an infinite number of times.
2691 * Note that there may be no need to perform this final wrapping
2692 * if the loop condition (after wrapping) satisfies certain conditions.
2693 * However, the is_simple_bound condition is not enough since it doesn't
2694 * check if there even is an upper bound.
2696 * If the loop condition is non-affine, then we keep the virtual
2697 * iterator in the iteration domain and instead replace all accesses
2698 * to the original iterator by the wrapping of the virtual iterator.
2700 * Wrapping on unsigned iterators can be avoided entirely if
2701 * loop condition is simple, the loop iterator is incremented
2702 * [decremented] by one and the last value before wrapping cannot
2703 * possibly satisfy the loop condition.
2705 * Before extracting a pet_scop from the body we remove all
2706 * assignments in assigned_value to variables that are assigned
2707 * somewhere in the body of the loop.
2709 * Valid parameters for a for loop are those for which the initial
2710 * value itself, the increment on each domain iteration and
2711 * the condition on both the initial value and
2712 * the result of incrementing the iterator for each iteration of the domain
2714 * If the loop condition is non-affine, then we only consider validity
2715 * of the initial value.
2717 * If the body contains any break, then we keep track of it in "skip"
2718 * (if the skip condition is affine) or it is handled in scop_add_break
2719 * (if the skip condition is not affine).
2720 * Note that the affine break condition needs to be considered with
2721 * respect to previous iterations in the virtual domain (if any)
2722 * and that the domain needs to be kept virtual if there is a non-affine
2725 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2727 BinaryOperator
*ass
;
2735 isl_set
*cond
= NULL
;
2736 isl_set
*skip
= NULL
;
2738 struct pet_scop
*scop
, *scop_cond
= NULL
;
2739 assigned_value_cache
cache(assigned_value
);
2745 bool keep_virtual
= false;
2746 bool has_affine_break
;
2748 isl_map
*wrap
= NULL
;
2749 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2750 isl_set
*valid_init
;
2751 isl_set
*valid_cond
;
2752 isl_set
*valid_cond_init
;
2753 isl_set
*valid_cond_next
;
2755 isl_map
*test_access
= NULL
, *break_access
= NULL
;
2758 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2759 return extract_infinite_for(stmt
);
2761 init
= stmt
->getInit();
2766 if ((ass
= initialization_assignment(init
)) != NULL
) {
2767 iv
= extract_induction_variable(ass
);
2770 lhs
= ass
->getLHS();
2771 rhs
= ass
->getRHS();
2772 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2773 VarDecl
*var
= extract_induction_variable(init
, decl
);
2777 rhs
= var
->getInit();
2778 lhs
= create_DeclRefExpr(var
);
2780 unsupported(stmt
->getInit());
2784 pa_inc
= extract_increment(stmt
, iv
);
2789 if (isl_pw_aff_n_piece(pa_inc
) != 1 ||
2790 isl_pw_aff_foreach_piece(pa_inc
, &extract_cst
, &inc
) < 0) {
2791 isl_pw_aff_free(pa_inc
);
2792 unsupported(stmt
->getInc());
2796 valid_inc
= isl_pw_aff_domain(pa_inc
);
2798 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2800 assigned_value
.erase(iv
);
2801 clear_assignments
clear(assigned_value
);
2802 clear
.TraverseStmt(stmt
->getBody());
2804 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
2806 pa
= try_extract_nested_condition(stmt
->getCond());
2807 if (allow_nested
&& (!pa
|| has_nested(pa
)))
2810 scop
= extract(stmt
->getBody());
2812 has_affine_break
= scop
&&
2813 pet_scop_has_affine_skip(scop
, pet_skip_later
);
2814 if (has_affine_break
) {
2815 skip
= pet_scop_get_skip(scop
, pet_skip_later
);
2816 skip
= isl_set_fix_si(skip
, isl_dim_set
, 0, 1);
2817 skip
= isl_set_params(skip
);
2819 has_var_break
= scop
&& pet_scop_has_var_skip(scop
, pet_skip_later
);
2820 if (has_var_break
) {
2821 break_access
= pet_scop_get_skip_map(scop
, pet_skip_later
);
2822 keep_virtual
= true;
2825 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2826 isl_pw_aff_free(pa
);
2830 if (!allow_nested
&& !pa
)
2831 pa
= try_extract_affine_condition(stmt
->getCond());
2832 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2833 cond
= isl_pw_aff_non_zero_set(pa
);
2834 if (allow_nested
&& !cond
) {
2835 int save_n_stmt
= n_stmt
;
2836 test_access
= create_test_access(ctx
, n_test
++);
2838 scop_cond
= extract_non_affine_condition(stmt
->getCond(),
2839 isl_map_copy(test_access
));
2840 n_stmt
= save_n_stmt
;
2841 scop_cond
= scop_add_array(scop_cond
, test_access
, ast_context
);
2842 scop_cond
= pet_scop_prefix(scop_cond
, 0);
2843 scop
= pet_scop_reset_context(scop
);
2844 scop
= pet_scop_prefix(scop
, 1);
2845 keep_virtual
= true;
2846 cond
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2849 cond
= embed(cond
, isl_id_copy(id
));
2850 skip
= embed(skip
, isl_id_copy(id
));
2851 valid_cond
= isl_set_coalesce(valid_cond
);
2852 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
2853 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
2854 is_one
= isl_int_is_one(inc
) || isl_int_is_negone(inc
);
2855 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2857 init_val
= extract_affine(rhs
);
2858 valid_cond_init
= enforce_subset(
2859 isl_set_from_pw_aff(isl_pw_aff_copy(init_val
)),
2860 isl_set_copy(valid_cond
));
2861 if (is_one
&& !is_virtual
) {
2862 isl_pw_aff_free(init_val
);
2863 pa
= extract_comparison(isl_int_is_pos(inc
) ? BO_GE
: BO_LE
,
2865 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2866 valid_init
= set_project_out_by_id(valid_init
, id
);
2867 domain
= isl_pw_aff_non_zero_set(pa
);
2869 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
2870 domain
= strided_domain(isl_id_copy(id
), init_val
, inc
);
2873 domain
= embed(domain
, isl_id_copy(id
));
2876 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2877 rev_wrap
= isl_map_reverse(isl_map_copy(wrap
));
2878 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
2879 skip
= isl_set_apply(skip
, isl_map_copy(rev_wrap
));
2880 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
2881 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
2883 is_simple
= is_simple_bound(cond
, inc
);
2885 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2886 is_simple
= is_simple_bound(cond
, inc
);
2889 cond
= valid_for_each_iteration(cond
,
2890 isl_set_copy(domain
), inc
);
2891 domain
= isl_set_intersect(domain
, cond
);
2892 if (has_affine_break
) {
2893 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2894 skip
= after(skip
, isl_int_sgn(inc
));
2895 domain
= isl_set_subtract(domain
, skip
);
2897 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2898 space
= isl_space_from_domain(isl_set_get_space(domain
));
2899 space
= isl_space_add_dims(space
, isl_dim_out
, 1);
2900 sched
= isl_map_universe(space
);
2901 if (isl_int_is_pos(inc
))
2902 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2904 sched
= isl_map_oppose(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2906 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
), inc
);
2907 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
2909 if (is_virtual
&& !keep_virtual
) {
2910 wrap
= isl_map_set_dim_id(wrap
,
2911 isl_dim_out
, 0, isl_id_copy(id
));
2912 sched
= isl_map_intersect_domain(sched
, isl_set_copy(domain
));
2913 domain
= isl_set_apply(domain
, isl_map_copy(wrap
));
2914 sched
= isl_map_apply_domain(sched
, wrap
);
2916 if (!(is_virtual
&& keep_virtual
)) {
2917 space
= isl_set_get_space(domain
);
2918 wrap
= isl_map_identity(isl_space_map_from_set(space
));
2921 scop_cond
= pet_scop_embed(scop_cond
, isl_set_copy(domain
),
2922 isl_map_copy(sched
), isl_map_copy(wrap
), isl_id_copy(id
));
2923 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), sched
, wrap
, id
);
2924 scop
= resolve_nested(scop
);
2926 scop
= scop_add_break(scop
, break_access
, isl_set_copy(domain
),
2929 scop
= scop_add_while(scop_cond
, scop
, test_access
, domain
,
2931 isl_set_free(valid_inc
);
2933 scop
= pet_scop_restrict_context(scop
, valid_inc
);
2934 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
2935 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
2936 isl_set_free(domain
);
2938 clear_assignment(assigned_value
, iv
);
2942 scop
= pet_scop_restrict_context(scop
, valid_init
);
2947 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
, bool skip_declarations
)
2949 return extract(stmt
->children(), true, skip_declarations
);
2952 /* Does parameter "pos" of "map" refer to a nested access?
2954 static bool is_nested_parameter(__isl_keep isl_map
*map
, int pos
)
2959 id
= isl_map_get_dim_id(map
, isl_dim_param
, pos
);
2960 nested
= is_nested_parameter(id
);
2966 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2968 static int n_nested_parameter(__isl_keep isl_space
*space
)
2973 nparam
= isl_space_dim(space
, isl_dim_param
);
2974 for (int i
= 0; i
< nparam
; ++i
)
2975 if (is_nested_parameter(space
, i
))
2981 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2983 static int n_nested_parameter(__isl_keep isl_map
*map
)
2988 space
= isl_map_get_space(map
);
2989 n
= n_nested_parameter(space
);
2990 isl_space_free(space
);
2995 /* For each nested access parameter in "space",
2996 * construct a corresponding pet_expr, place it in args and
2997 * record its position in "param2pos".
2998 * "n_arg" is the number of elements that are already in args.
2999 * The position recorded in "param2pos" takes this number into account.
3000 * If the pet_expr corresponding to a parameter is identical to
3001 * the pet_expr corresponding to an earlier parameter, then these two
3002 * parameters are made to refer to the same element in args.
3004 * Return the final number of elements in args or -1 if an error has occurred.
3006 int PetScan::extract_nested(__isl_keep isl_space
*space
,
3007 int n_arg
, struct pet_expr
**args
, std::map
<int,int> ¶m2pos
)
3011 nparam
= isl_space_dim(space
, isl_dim_param
);
3012 for (int i
= 0; i
< nparam
; ++i
) {
3014 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
3017 if (!is_nested_parameter(id
)) {
3022 nested
= (Expr
*) isl_id_get_user(id
);
3023 args
[n_arg
] = extract_expr(nested
);
3027 for (j
= 0; j
< n_arg
; ++j
)
3028 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
3032 pet_expr_free(args
[n_arg
]);
3036 param2pos
[i
] = n_arg
++;
3044 /* For each nested access parameter in the access relations in "expr",
3045 * construct a corresponding pet_expr, place it in expr->args and
3046 * record its position in "param2pos".
3047 * n is the number of nested access parameters.
3049 struct pet_expr
*PetScan::extract_nested(struct pet_expr
*expr
, int n
,
3050 std::map
<int,int> ¶m2pos
)
3054 expr
->args
= isl_calloc_array(ctx
, struct pet_expr
*, n
);
3059 space
= isl_map_get_space(expr
->acc
.access
);
3060 n
= extract_nested(space
, 0, expr
->args
, param2pos
);
3061 isl_space_free(space
);
3069 pet_expr_free(expr
);
3073 /* Look for parameters in any access relation in "expr" that
3074 * refer to nested accesses. In particular, these are
3075 * parameters with no name.
3077 * If there are any such parameters, then the domain of the access
3078 * relation, which is still [] at this point, is replaced by
3079 * [[] -> [t_1,...,t_n]], with n the number of these parameters
3080 * (after identifying identical nested accesses).
3081 * The parameters are then equated to the corresponding t dimensions
3082 * and subsequently projected out.
3083 * param2pos maps the position of the parameter to the position
3084 * of the corresponding t dimension.
3086 struct pet_expr
*PetScan::resolve_nested(struct pet_expr
*expr
)
3093 std::map
<int,int> param2pos
;
3098 for (int i
= 0; i
< expr
->n_arg
; ++i
) {
3099 expr
->args
[i
] = resolve_nested(expr
->args
[i
]);
3100 if (!expr
->args
[i
]) {
3101 pet_expr_free(expr
);
3106 if (expr
->type
!= pet_expr_access
)
3109 n
= n_nested_parameter(expr
->acc
.access
);
3113 expr
= extract_nested(expr
, n
, param2pos
);
3118 nparam
= isl_map_dim(expr
->acc
.access
, isl_dim_param
);
3119 n_in
= isl_map_dim(expr
->acc
.access
, isl_dim_in
);
3120 dim
= isl_map_get_space(expr
->acc
.access
);
3121 dim
= isl_space_domain(dim
);
3122 dim
= isl_space_from_domain(dim
);
3123 dim
= isl_space_add_dims(dim
, isl_dim_out
, n
);
3124 map
= isl_map_universe(dim
);
3125 map
= isl_map_domain_map(map
);
3126 map
= isl_map_reverse(map
);
3127 expr
->acc
.access
= isl_map_apply_domain(expr
->acc
.access
, map
);
3129 for (int i
= nparam
- 1; i
>= 0; --i
) {
3130 isl_id
*id
= isl_map_get_dim_id(expr
->acc
.access
,
3132 if (!is_nested_parameter(id
)) {
3137 expr
->acc
.access
= isl_map_equate(expr
->acc
.access
,
3138 isl_dim_param
, i
, isl_dim_in
,
3139 n_in
+ param2pos
[i
]);
3140 expr
->acc
.access
= isl_map_project_out(expr
->acc
.access
,
3141 isl_dim_param
, i
, 1);
3148 pet_expr_free(expr
);
3152 /* Return the file offset of the expansion location of "Loc".
3154 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
3156 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
3159 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3161 /* Return a SourceLocation for the location after the first semicolon
3162 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3163 * call it and also skip trailing spaces and newline.
3165 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3166 const LangOptions
&LO
)
3168 return Lexer::findLocationAfterToken(loc
, tok::semi
, SM
, LO
, true);
3173 /* Return a SourceLocation for the location after the first semicolon
3174 * after "loc". If Lexer::findLocationAfterToken is not available,
3175 * we look in the underlying character data for the first semicolon.
3177 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3178 const LangOptions
&LO
)
3181 const char *s
= SM
.getCharacterData(loc
);
3183 semi
= strchr(s
, ';');
3185 return SourceLocation();
3186 return loc
.getFileLocWithOffset(semi
+ 1 - s
);
3191 /* Convert a top-level pet_expr to a pet_scop with one statement.
3192 * This mainly involves resolving nested expression parameters
3193 * and setting the name of the iteration space.
3194 * The name is given by "label" if it is non-NULL. Otherwise,
3195 * it is of the form S_<n_stmt>.
3196 * start and end of the pet_scop are derived from those of "stmt".
3198 struct pet_scop
*PetScan::extract(Stmt
*stmt
, struct pet_expr
*expr
,
3199 __isl_take isl_id
*label
)
3201 struct pet_stmt
*ps
;
3202 struct pet_scop
*scop
;
3203 SourceLocation loc
= stmt
->getLocStart();
3204 SourceManager
&SM
= PP
.getSourceManager();
3205 const LangOptions
&LO
= PP
.getLangOpts();
3206 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3207 unsigned start
, end
;
3209 expr
= resolve_nested(expr
);
3210 ps
= pet_stmt_from_pet_expr(ctx
, line
, label
, n_stmt
++, expr
);
3211 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3213 start
= getExpansionOffset(SM
, loc
);
3214 loc
= stmt
->getLocEnd();
3215 loc
= location_after_semi(loc
, SM
, LO
);
3216 end
= getExpansionOffset(SM
, loc
);
3218 scop
= pet_scop_update_start_end(scop
, start
, end
);
3222 /* Check if we can extract an affine expression from "expr".
3223 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3224 * We turn on autodetection so that we won't generate any warnings
3225 * and turn off nesting, so that we won't accept any non-affine constructs.
3227 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
3230 int save_autodetect
= options
->autodetect
;
3231 bool save_nesting
= nesting_enabled
;
3233 options
->autodetect
= 1;
3234 nesting_enabled
= false;
3236 pwaff
= extract_affine(expr
);
3238 options
->autodetect
= save_autodetect
;
3239 nesting_enabled
= save_nesting
;
3244 /* Check whether "expr" is an affine expression.
3246 bool PetScan::is_affine(Expr
*expr
)
3250 pwaff
= try_extract_affine(expr
);
3251 isl_pw_aff_free(pwaff
);
3253 return pwaff
!= NULL
;
3256 /* Check if we can extract an affine constraint from "expr".
3257 * Return the constraint as an isl_set if we can and NULL otherwise.
3258 * We turn on autodetection so that we won't generate any warnings
3259 * and turn off nesting, so that we won't accept any non-affine constructs.
3261 __isl_give isl_pw_aff
*PetScan::try_extract_affine_condition(Expr
*expr
)
3264 int save_autodetect
= options
->autodetect
;
3265 bool save_nesting
= nesting_enabled
;
3267 options
->autodetect
= 1;
3268 nesting_enabled
= false;
3270 cond
= extract_condition(expr
);
3272 options
->autodetect
= save_autodetect
;
3273 nesting_enabled
= save_nesting
;
3278 /* Check whether "expr" is an affine constraint.
3280 bool PetScan::is_affine_condition(Expr
*expr
)
3284 cond
= try_extract_affine_condition(expr
);
3285 isl_pw_aff_free(cond
);
3287 return cond
!= NULL
;
3290 /* Check if we can extract a condition from "expr".
3291 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3292 * If allow_nested is set, then the condition may involve parameters
3293 * corresponding to nested accesses.
3294 * We turn on autodetection so that we won't generate any warnings.
3296 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
3299 int save_autodetect
= options
->autodetect
;
3300 bool save_nesting
= nesting_enabled
;
3302 options
->autodetect
= 1;
3303 nesting_enabled
= allow_nested
;
3304 cond
= extract_condition(expr
);
3306 options
->autodetect
= save_autodetect
;
3307 nesting_enabled
= save_nesting
;
3312 /* If the top-level expression of "stmt" is an assignment, then
3313 * return that assignment as a BinaryOperator.
3314 * Otherwise return NULL.
3316 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
3318 BinaryOperator
*ass
;
3322 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
3325 ass
= cast
<BinaryOperator
>(stmt
);
3326 if(ass
->getOpcode() != BO_Assign
)
3332 /* Check if the given if statement is a conditional assignement
3333 * with a non-affine condition. If so, construct a pet_scop
3334 * corresponding to this conditional assignment. Otherwise return NULL.
3336 * In particular we check if "stmt" is of the form
3343 * where a is some array or scalar access.
3344 * The constructed pet_scop then corresponds to the expression
3346 * a = condition ? f(...) : g(...)
3348 * All access relations in f(...) are intersected with condition
3349 * while all access relation in g(...) are intersected with the complement.
3351 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
3353 BinaryOperator
*ass_then
, *ass_else
;
3354 isl_map
*write_then
, *write_else
;
3355 isl_set
*cond
, *comp
;
3359 struct pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
3360 bool save_nesting
= nesting_enabled
;
3362 if (!options
->detect_conditional_assignment
)
3365 ass_then
= top_assignment_or_null(stmt
->getThen());
3366 ass_else
= top_assignment_or_null(stmt
->getElse());
3368 if (!ass_then
|| !ass_else
)
3371 if (is_affine_condition(stmt
->getCond()))
3374 write_then
= extract_access(ass_then
->getLHS());
3375 write_else
= extract_access(ass_else
->getLHS());
3377 equal
= isl_map_is_equal(write_then
, write_else
);
3378 isl_map_free(write_else
);
3379 if (equal
< 0 || !equal
) {
3380 isl_map_free(write_then
);
3384 nesting_enabled
= allow_nested
;
3385 pa
= extract_condition(stmt
->getCond());
3386 nesting_enabled
= save_nesting
;
3387 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
3388 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
3389 map
= isl_map_from_range(isl_set_from_pw_aff(pa
));
3391 pe_cond
= pet_expr_from_access(map
);
3393 pe_then
= extract_expr(ass_then
->getRHS());
3394 pe_then
= pet_expr_restrict(pe_then
, cond
);
3395 pe_else
= extract_expr(ass_else
->getRHS());
3396 pe_else
= pet_expr_restrict(pe_else
, comp
);
3398 pe
= pet_expr_new_ternary(ctx
, pe_cond
, pe_then
, pe_else
);
3399 pe_write
= pet_expr_from_access(write_then
);
3401 pe_write
->acc
.write
= 1;
3402 pe_write
->acc
.read
= 0;
3404 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, pe_write
, pe
);
3405 return extract(stmt
, pe
);
3408 /* Create a pet_scop with a single statement evaluating "cond"
3409 * and writing the result to a virtual scalar, as expressed by
3412 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
,
3413 __isl_take isl_map
*access
)
3415 struct pet_expr
*expr
, *write
;
3416 struct pet_stmt
*ps
;
3417 struct pet_scop
*scop
;
3418 SourceLocation loc
= cond
->getLocStart();
3419 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3421 write
= pet_expr_from_access(access
);
3423 write
->acc
.write
= 1;
3424 write
->acc
.read
= 0;
3426 expr
= extract_expr(cond
);
3427 expr
= resolve_nested(expr
);
3428 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, write
, expr
);
3429 ps
= pet_stmt_from_pet_expr(ctx
, line
, NULL
, n_stmt
++, expr
);
3430 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3431 scop
= resolve_nested(scop
);
3437 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
,
3441 /* Apply the map pointed to by "user" to the domain of the access
3442 * relation, thereby embedding it in the range of the map.
3443 * The domain of both relations is the zero-dimensional domain.
3445 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
, void *user
)
3447 isl_map
*map
= (isl_map
*) user
;
3449 return isl_map_apply_domain(access
, isl_map_copy(map
));
3452 /* Apply "map" to all access relations in "expr".
3454 static struct pet_expr
*embed(struct pet_expr
*expr
, __isl_keep isl_map
*map
)
3456 return pet_expr_foreach_access(expr
, &embed_access
, map
);
3459 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3461 static int n_nested_parameter(__isl_keep isl_set
*set
)
3466 space
= isl_set_get_space(set
);
3467 n
= n_nested_parameter(space
);
3468 isl_space_free(space
);
3473 /* Remove all parameters from "map" that refer to nested accesses.
3475 static __isl_give isl_map
*remove_nested_parameters(__isl_take isl_map
*map
)
3480 space
= isl_map_get_space(map
);
3481 nparam
= isl_space_dim(space
, isl_dim_param
);
3482 for (int i
= nparam
- 1; i
>= 0; --i
)
3483 if (is_nested_parameter(space
, i
))
3484 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3485 isl_space_free(space
);
3491 static __isl_give isl_map
*access_remove_nested_parameters(
3492 __isl_take isl_map
*access
, void *user
);
3495 static __isl_give isl_map
*access_remove_nested_parameters(
3496 __isl_take isl_map
*access
, void *user
)
3498 return remove_nested_parameters(access
);
3501 /* Remove all nested access parameters from the schedule and all
3502 * accesses of "stmt".
3503 * There is no need to remove them from the domain as these parameters
3504 * have already been removed from the domain when this function is called.
3506 static struct pet_stmt
*remove_nested_parameters(struct pet_stmt
*stmt
)
3510 stmt
->schedule
= remove_nested_parameters(stmt
->schedule
);
3511 stmt
->body
= pet_expr_foreach_access(stmt
->body
,
3512 &access_remove_nested_parameters
, NULL
);
3513 if (!stmt
->schedule
|| !stmt
->body
)
3515 for (int i
= 0; i
< stmt
->n_arg
; ++i
) {
3516 stmt
->args
[i
] = pet_expr_foreach_access(stmt
->args
[i
],
3517 &access_remove_nested_parameters
, NULL
);
3524 pet_stmt_free(stmt
);
3528 /* For each nested access parameter in the domain of "stmt",
3529 * construct a corresponding pet_expr, place it before the original
3530 * elements in stmt->args and record its position in "param2pos".
3531 * n is the number of nested access parameters.
3533 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
3534 std::map
<int,int> ¶m2pos
)
3539 struct pet_expr
**args
;
3541 n_arg
= stmt
->n_arg
;
3542 args
= isl_calloc_array(ctx
, struct pet_expr
*, n
+ n_arg
);
3546 space
= isl_set_get_space(stmt
->domain
);
3547 n_arg
= extract_nested(space
, 0, args
, param2pos
);
3548 isl_space_free(space
);
3553 for (i
= 0; i
< stmt
->n_arg
; ++i
)
3554 args
[n_arg
+ i
] = stmt
->args
[i
];
3557 stmt
->n_arg
+= n_arg
;
3562 for (i
= 0; i
< n
; ++i
)
3563 pet_expr_free(args
[i
]);
3566 pet_stmt_free(stmt
);
3570 /* Check whether any of the arguments i of "stmt" starting at position "n"
3571 * is equal to one of the first "n" arguments j.
3572 * If so, combine the constraints on arguments i and j and remove
3575 static struct pet_stmt
*remove_duplicate_arguments(struct pet_stmt
*stmt
, int n
)
3584 if (n
== stmt
->n_arg
)
3587 map
= isl_set_unwrap(stmt
->domain
);
3589 for (i
= stmt
->n_arg
- 1; i
>= n
; --i
) {
3590 for (j
= 0; j
< n
; ++j
)
3591 if (pet_expr_is_equal(stmt
->args
[i
], stmt
->args
[j
]))
3596 map
= isl_map_equate(map
, isl_dim_out
, i
, isl_dim_out
, j
);
3597 map
= isl_map_project_out(map
, isl_dim_out
, i
, 1);
3599 pet_expr_free(stmt
->args
[i
]);
3600 for (j
= i
; j
+ 1 < stmt
->n_arg
; ++j
)
3601 stmt
->args
[j
] = stmt
->args
[j
+ 1];
3605 stmt
->domain
= isl_map_wrap(map
);
3610 pet_stmt_free(stmt
);
3614 /* Look for parameters in the iteration domain of "stmt" that
3615 * refer to nested accesses. In particular, these are
3616 * parameters with no name.
3618 * If there are any such parameters, then as many extra variables
3619 * (after identifying identical nested accesses) are inserted in the
3620 * range of the map wrapped inside the domain, before the original variables.
3621 * If the original domain is not a wrapped map, then a new wrapped
3622 * map is created with zero output dimensions.
3623 * The parameters are then equated to the corresponding output dimensions
3624 * and subsequently projected out, from the iteration domain,
3625 * the schedule and the access relations.
3626 * For each of the output dimensions, a corresponding argument
3627 * expression is inserted. Initially they are created with
3628 * a zero-dimensional domain, so they have to be embedded
3629 * in the current iteration domain.
3630 * param2pos maps the position of the parameter to the position
3631 * of the corresponding output dimension in the wrapped map.
3633 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3639 std::map
<int,int> param2pos
;
3644 n
= n_nested_parameter(stmt
->domain
);
3648 n_arg
= stmt
->n_arg
;
3649 stmt
= extract_nested(stmt
, n
, param2pos
);
3653 n
= stmt
->n_arg
- n_arg
;
3654 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3655 if (isl_set_is_wrapping(stmt
->domain
))
3656 map
= isl_set_unwrap(stmt
->domain
);
3658 map
= isl_map_from_domain(stmt
->domain
);
3659 map
= isl_map_insert_dims(map
, isl_dim_out
, 0, n
);
3661 for (int i
= nparam
- 1; i
>= 0; --i
) {
3664 if (!is_nested_parameter(map
, i
))
3667 id
= isl_map_get_tuple_id(stmt
->args
[param2pos
[i
]]->acc
.access
,
3669 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3670 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3672 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3675 stmt
->domain
= isl_map_wrap(map
);
3677 map
= isl_set_unwrap(isl_set_copy(stmt
->domain
));
3678 map
= isl_map_from_range(isl_map_domain(map
));
3679 for (int pos
= 0; pos
< n
; ++pos
)
3680 stmt
->args
[pos
] = embed(stmt
->args
[pos
], map
);
3683 stmt
= remove_nested_parameters(stmt
);
3684 stmt
= remove_duplicate_arguments(stmt
, n
);
3688 pet_stmt_free(stmt
);
3692 /* For each statement in "scop", move the parameters that correspond
3693 * to nested access into the ranges of the domains and create
3694 * corresponding argument expressions.
3696 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3701 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3702 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3703 if (!scop
->stmts
[i
])
3709 pet_scop_free(scop
);
3713 /* Given an access expression "expr", is the variable accessed by
3714 * "expr" assigned anywhere inside "scop"?
3716 static bool is_assigned(pet_expr
*expr
, pet_scop
*scop
)
3718 bool assigned
= false;
3721 id
= isl_map_get_tuple_id(expr
->acc
.access
, isl_dim_out
);
3722 assigned
= pet_scop_writes(scop
, id
);
3728 /* Are all nested access parameters in "pa" allowed given "scop".
3729 * In particular, is none of them written by anywhere inside "scop".
3731 * If "scop" has any skip conditions, then no nested access parameters
3732 * are allowed. In particular, if there is any nested access in a guard
3733 * for a piece of code containing a "continue", then we want to introduce
3734 * a separate statement for evaluating this guard so that we can express
3735 * that the result is false for all previous iterations.
3737 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3744 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3745 for (int i
= 0; i
< nparam
; ++i
) {
3747 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3751 if (!is_nested_parameter(id
)) {
3756 if (pet_scop_has_skip(scop
, pet_skip_now
)) {
3761 nested
= (Expr
*) isl_id_get_user(id
);
3762 expr
= extract_expr(nested
);
3763 allowed
= expr
&& expr
->type
== pet_expr_access
&&
3764 !is_assigned(expr
, scop
);
3766 pet_expr_free(expr
);
3776 /* Do we need to construct a skip condition of the given type
3777 * on an if statement, given that the if condition is non-affine?
3779 * pet_scop_filter_skip can only handle the case where the if condition
3780 * holds (the then branch) and the skip condition is universal.
3781 * In any other case, we need to construct a new skip condition.
3783 static bool need_skip(struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3784 bool have_else
, enum pet_skip type
)
3786 if (have_else
&& scop_else
&& pet_scop_has_skip(scop_else
, type
))
3788 if (scop_then
&& pet_scop_has_skip(scop_then
, type
) &&
3789 !pet_scop_has_universal_skip(scop_then
, type
))
3794 /* Do we need to construct a skip condition of the given type
3795 * on an if statement, given that the if condition is affine?
3797 * There is no need to construct a new skip condition if all
3798 * the skip conditions are affine.
3800 static bool need_skip_aff(struct pet_scop
*scop_then
,
3801 struct pet_scop
*scop_else
, bool have_else
, enum pet_skip type
)
3803 if (scop_then
&& pet_scop_has_var_skip(scop_then
, type
))
3805 if (have_else
&& scop_else
&& pet_scop_has_var_skip(scop_else
, type
))
3810 /* Do we need to construct a skip condition of the given type
3811 * on an if statement?
3813 static bool need_skip(struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3814 bool have_else
, enum pet_skip type
, bool affine
)
3817 return need_skip_aff(scop_then
, scop_else
, have_else
, type
);
3819 return need_skip(scop_then
, scop_else
, have_else
, type
);
3822 /* Construct an affine expression pet_expr that is evaluates
3823 * to the constant "val".
3825 static struct pet_expr
*universally(isl_ctx
*ctx
, int val
)
3830 space
= isl_space_alloc(ctx
, 0, 0, 1);
3831 map
= isl_map_universe(space
);
3832 map
= isl_map_fix_si(map
, isl_dim_out
, 0, val
);
3834 return pet_expr_from_access(map
);
3837 /* Construct an affine expression pet_expr that is evaluates
3838 * to the constant 1.
3840 static struct pet_expr
*universally_true(isl_ctx
*ctx
)
3842 return universally(ctx
, 1);
3845 /* Construct an affine expression pet_expr that is evaluates
3846 * to the constant 0.
3848 static struct pet_expr
*universally_false(isl_ctx
*ctx
)
3850 return universally(ctx
, 0);
3853 /* Given an access relation "test_access" for the if condition,
3854 * an access relation "skip_access" for the skip condition and
3855 * scops for the then and else branches, construct a scop for
3856 * computing "skip_access".
3858 * The computed scop contains a single statement that essentially does
3860 * skip_cond = test_cond ? skip_cond_then : skip_cond_else
3862 * If the skip conditions of the then and/or else branch are not affine,
3863 * then they need to be filtered by test_access.
3864 * If they are missing, then this means the skip condition is false.
3866 * Since we are constructing a skip condition for the if statement,
3867 * the skip conditions on the then and else branches are removed.
3869 static struct pet_scop
*extract_skip(PetScan
*scan
,
3870 __isl_take isl_map
*test_access
, __isl_take isl_map
*skip_access
,
3871 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
, bool have_else
,
3874 struct pet_expr
*expr_then
, *expr_else
, *expr
, *expr_skip
;
3875 struct pet_stmt
*stmt
;
3876 struct pet_scop
*scop
;
3877 isl_ctx
*ctx
= scan
->ctx
;
3881 if (have_else
&& !scop_else
)
3884 if (pet_scop_has_skip(scop_then
, type
)) {
3885 expr_then
= pet_scop_get_skip_expr(scop_then
, type
);
3886 pet_scop_reset_skip(scop_then
, type
);
3887 if (!pet_expr_is_affine(expr_then
))
3888 expr_then
= pet_expr_filter(expr_then
,
3889 isl_map_copy(test_access
), 1);
3891 expr_then
= universally_false(ctx
);
3893 if (have_else
&& pet_scop_has_skip(scop_else
, type
)) {
3894 expr_else
= pet_scop_get_skip_expr(scop_else
, type
);
3895 pet_scop_reset_skip(scop_else
, type
);
3896 if (!pet_expr_is_affine(expr_else
))
3897 expr_else
= pet_expr_filter(expr_else
,
3898 isl_map_copy(test_access
), 0);
3900 expr_else
= universally_false(ctx
);
3902 expr
= pet_expr_from_access(test_access
);
3903 expr
= pet_expr_new_ternary(ctx
, expr
, expr_then
, expr_else
);
3904 expr_skip
= pet_expr_from_access(isl_map_copy(skip_access
));
3906 expr_skip
->acc
.write
= 1;
3907 expr_skip
->acc
.read
= 0;
3909 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, expr_skip
, expr
);
3910 stmt
= pet_stmt_from_pet_expr(ctx
, -1, NULL
, scan
->n_stmt
++, expr
);
3912 scop
= pet_scop_from_pet_stmt(ctx
, stmt
);
3913 scop
= scop_add_array(scop
, skip_access
, scan
->ast_context
);
3914 isl_map_free(skip_access
);
3918 isl_map_free(test_access
);
3919 isl_map_free(skip_access
);
3923 /* Is scop's skip_now condition equal to its skip_later condition?
3924 * In particular, this means that it either has no skip_now condition
3925 * or both a skip_now and a skip_later condition (that are equal to each other).
3927 static bool skip_equals_skip_later(struct pet_scop
*scop
)
3929 int has_skip_now
, has_skip_later
;
3931 isl_set
*skip_now
, *skip_later
;
3935 has_skip_now
= pet_scop_has_skip(scop
, pet_skip_now
);
3936 has_skip_later
= pet_scop_has_skip(scop
, pet_skip_later
);
3937 if (has_skip_now
!= has_skip_later
)
3942 skip_now
= pet_scop_get_skip(scop
, pet_skip_now
);
3943 skip_later
= pet_scop_get_skip(scop
, pet_skip_later
);
3944 equal
= isl_set_is_equal(skip_now
, skip_later
);
3945 isl_set_free(skip_now
);
3946 isl_set_free(skip_later
);
3951 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
3953 static void drop_skip_later(struct pet_scop
*scop1
, struct pet_scop
*scop2
)
3955 pet_scop_reset_skip(scop1
, pet_skip_later
);
3956 pet_scop_reset_skip(scop2
, pet_skip_later
);
3959 /* Structure that handles the construction of skip conditions.
3961 * scop_then and scop_else represent the then and else branches
3962 * of the if statement
3964 * skip[type] is true if we need to construct a skip condition of that type
3965 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
3966 * are equal to each other
3967 * access[type] is the virtual array representing the skip condition
3968 * scop[type] is a scop for computing the skip condition
3970 struct pet_skip_info
{
3976 struct pet_scop
*scop
[2];
3978 pet_skip_info(isl_ctx
*ctx
) : ctx(ctx
) {}
3980 operator bool() { return skip
[pet_skip_now
] || skip
[pet_skip_later
]; }
3983 /* Structure that handles the construction of skip conditions on if statements.
3985 * scop_then and scop_else represent the then and else branches
3986 * of the if statement
3988 struct pet_skip_info_if
: public pet_skip_info
{
3989 struct pet_scop
*scop_then
, *scop_else
;
3992 pet_skip_info_if(isl_ctx
*ctx
, struct pet_scop
*scop_then
,
3993 struct pet_scop
*scop_else
, bool have_else
, bool affine
);
3994 void extract(PetScan
*scan
, __isl_keep isl_map
*access
,
3995 enum pet_skip type
);
3996 void extract(PetScan
*scan
, __isl_keep isl_map
*access
);
3997 void extract(PetScan
*scan
, __isl_keep isl_pw_aff
*cond
);
3998 struct pet_scop
*add(struct pet_scop
*scop
, enum pet_skip type
,
4000 struct pet_scop
*add(struct pet_scop
*scop
, int offset
);
4003 /* Initialize a pet_skip_info_if structure based on the then and else branches
4004 * and based on whether the if condition is affine or not.
4006 pet_skip_info_if::pet_skip_info_if(isl_ctx
*ctx
, struct pet_scop
*scop_then
,
4007 struct pet_scop
*scop_else
, bool have_else
, bool affine
) :
4008 pet_skip_info(ctx
), scop_then(scop_then
), scop_else(scop_else
),
4009 have_else(have_else
)
4011 skip
[pet_skip_now
] =
4012 need_skip(scop_then
, scop_else
, have_else
, pet_skip_now
, affine
);
4013 equal
= skip
[pet_skip_now
] && skip_equals_skip_later(scop_then
) &&
4014 (!have_else
|| skip_equals_skip_later(scop_else
));
4015 skip
[pet_skip_later
] = skip
[pet_skip_now
] && !equal
&&
4016 need_skip(scop_then
, scop_else
, have_else
, pet_skip_later
, affine
);
4019 /* If we need to construct a skip condition of the given type,
4022 * "map" represents the if condition.
4024 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_map
*map
,
4030 access
[type
] = create_test_access(isl_map_get_ctx(map
), scan
->n_test
++);
4031 scop
[type
] = extract_skip(scan
, isl_map_copy(map
),
4032 isl_map_copy(access
[type
]),
4033 scop_then
, scop_else
, have_else
, type
);
4036 /* Construct the required skip conditions, given the if condition "map".
4038 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_map
*map
)
4040 extract(scan
, map
, pet_skip_now
);
4041 extract(scan
, map
, pet_skip_later
);
4043 drop_skip_later(scop_then
, scop_else
);
4046 /* Construct the required skip conditions, given the if condition "cond".
4048 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_pw_aff
*cond
)
4053 if (!skip
[pet_skip_now
] && !skip
[pet_skip_later
])
4056 test_set
= isl_set_from_pw_aff(isl_pw_aff_copy(cond
));
4057 test
= isl_map_from_range(test_set
);
4058 extract(scan
, test
);
4062 /* Add the computed skip condition of the give type to "main" and
4063 * add the scop for computing the condition at the given offset.
4065 * If equal is set, then we only computed a skip condition for pet_skip_now,
4066 * but we also need to set it as main's pet_skip_later.
4068 struct pet_scop
*pet_skip_info_if::add(struct pet_scop
*main
,
4069 enum pet_skip type
, int offset
)
4076 skip_set
= isl_map_range(access
[type
]);
4077 access
[type
] = NULL
;
4078 scop
[type
] = pet_scop_prefix(scop
[type
], offset
);
4079 main
= pet_scop_add_par(ctx
, main
, scop
[type
]);
4083 main
= pet_scop_set_skip(main
, pet_skip_later
,
4084 isl_set_copy(skip_set
));
4086 main
= pet_scop_set_skip(main
, type
, skip_set
);
4091 /* Add the computed skip conditions to "main" and
4092 * add the scops for computing the conditions at the given offset.
4094 struct pet_scop
*pet_skip_info_if::add(struct pet_scop
*scop
, int offset
)
4096 scop
= add(scop
, pet_skip_now
, offset
);
4097 scop
= add(scop
, pet_skip_later
, offset
);
4102 /* Construct a pet_scop for a non-affine if statement.
4104 * We create a separate statement that writes the result
4105 * of the non-affine condition to a virtual scalar.
4106 * A constraint requiring the value of this virtual scalar to be one
4107 * is added to the iteration domains of the then branch.
4108 * Similarly, a constraint requiring the value of this virtual scalar
4109 * to be zero is added to the iteration domains of the else branch, if any.
4110 * We adjust the schedules to ensure that the virtual scalar is written
4111 * before it is read.
4113 * If there are any breaks or continues in the then and/or else
4114 * branches, then we may have to compute a new skip condition.
4115 * This is handled using a pet_skip_info_if object.
4116 * On initialization, the object checks if skip conditions need
4117 * to be computed. If so, it does so in "extract" and adds them in "add".
4119 struct pet_scop
*PetScan::extract_non_affine_if(Expr
*cond
,
4120 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
4121 bool have_else
, int stmt_id
)
4123 struct pet_scop
*scop
;
4124 isl_map
*test_access
;
4125 int save_n_stmt
= n_stmt
;
4127 test_access
= create_test_access(ctx
, n_test
++);
4129 scop
= extract_non_affine_condition(cond
, isl_map_copy(test_access
));
4130 n_stmt
= save_n_stmt
;
4131 scop
= scop_add_array(scop
, test_access
, ast_context
);
4133 pet_skip_info_if
skip(ctx
, scop_then
, scop_else
, have_else
, false);
4134 skip
.extract(this, test_access
);
4136 scop
= pet_scop_prefix(scop
, 0);
4137 scop_then
= pet_scop_prefix(scop_then
, 1);
4138 scop_then
= pet_scop_filter(scop_then
, isl_map_copy(test_access
), 1);
4140 scop_else
= pet_scop_prefix(scop_else
, 1);
4141 scop_else
= pet_scop_filter(scop_else
, test_access
, 0);
4142 scop_then
= pet_scop_add_par(ctx
, scop_then
, scop_else
);
4144 isl_map_free(test_access
);
4146 scop
= pet_scop_add_seq(ctx
, scop
, scop_then
);
4148 scop
= skip
.add(scop
, 2);
4153 /* Construct a pet_scop for an if statement.
4155 * If the condition fits the pattern of a conditional assignment,
4156 * then it is handled by extract_conditional_assignment.
4157 * Otherwise, we do the following.
4159 * If the condition is affine, then the condition is added
4160 * to the iteration domains of the then branch, while the
4161 * opposite of the condition in added to the iteration domains
4162 * of the else branch, if any.
4163 * We allow the condition to be dynamic, i.e., to refer to
4164 * scalars or array elements that may be written to outside
4165 * of the given if statement. These nested accesses are then represented
4166 * as output dimensions in the wrapping iteration domain.
4167 * If it also written _inside_ the then or else branch, then
4168 * we treat the condition as non-affine.
4169 * As explained in extract_non_affine_if, this will introduce
4170 * an extra statement.
4171 * For aesthetic reasons, we want this statement to have a statement
4172 * number that is lower than those of the then and else branches.
4173 * In order to evaluate if will need such a statement, however, we
4174 * first construct scops for the then and else branches.
4175 * We therefore reserve a statement number if we might have to
4176 * introduce such an extra statement.
4178 * If the condition is not affine, then the scop is created in
4179 * extract_non_affine_if.
4181 * If there are any breaks or continues in the then and/or else
4182 * branches, then we may have to compute a new skip condition.
4183 * This is handled using a pet_skip_info_if object.
4184 * On initialization, the object checks if skip conditions need
4185 * to be computed. If so, it does so in "extract" and adds them in "add".
4187 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
4189 struct pet_scop
*scop_then
, *scop_else
= NULL
, *scop
;
4195 scop
= extract_conditional_assignment(stmt
);
4199 cond
= try_extract_nested_condition(stmt
->getCond());
4200 if (allow_nested
&& (!cond
|| has_nested(cond
)))
4204 assigned_value_cache
cache(assigned_value
);
4205 scop_then
= extract(stmt
->getThen());
4208 if (stmt
->getElse()) {
4209 assigned_value_cache
cache(assigned_value
);
4210 scop_else
= extract(stmt
->getElse());
4211 if (options
->autodetect
) {
4212 if (scop_then
&& !scop_else
) {
4214 isl_pw_aff_free(cond
);
4217 if (!scop_then
&& scop_else
) {
4219 isl_pw_aff_free(cond
);
4226 (!is_nested_allowed(cond
, scop_then
) ||
4227 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
4228 isl_pw_aff_free(cond
);
4231 if (allow_nested
&& !cond
)
4232 return extract_non_affine_if(stmt
->getCond(), scop_then
,
4233 scop_else
, stmt
->getElse(), stmt_id
);
4236 cond
= extract_condition(stmt
->getCond());
4238 pet_skip_info_if
skip(ctx
, scop_then
, scop_else
, stmt
->getElse(), true);
4239 skip
.extract(this, cond
);
4241 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
4242 set
= isl_pw_aff_non_zero_set(cond
);
4243 scop
= pet_scop_restrict(scop_then
, isl_set_copy(set
));
4245 if (stmt
->getElse()) {
4246 set
= isl_set_subtract(isl_set_copy(valid
), set
);
4247 scop_else
= pet_scop_restrict(scop_else
, set
);
4248 scop
= pet_scop_add_par(ctx
, scop
, scop_else
);
4251 scop
= resolve_nested(scop
);
4252 scop
= pet_scop_restrict_context(scop
, valid
);
4255 scop
= pet_scop_prefix(scop
, 0);
4256 scop
= skip
.add(scop
, 1);
4261 /* Try and construct a pet_scop for a label statement.
4262 * We currently only allow labels on expression statements.
4264 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
4269 sub
= stmt
->getSubStmt();
4270 if (!isa
<Expr
>(sub
)) {
4275 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
4277 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
4280 /* Construct a pet_scop for a continue statement.
4282 * We simply create an empty scop with a universal pet_skip_now
4283 * skip condition. This skip condition will then be taken into
4284 * account by the enclosing loop construct, possibly after
4285 * being incorporated into outer skip conditions.
4287 struct pet_scop
*PetScan::extract(ContinueStmt
*stmt
)
4293 scop
= pet_scop_empty(ctx
);
4297 space
= isl_space_set_alloc(ctx
, 0, 1);
4298 set
= isl_set_universe(space
);
4299 set
= isl_set_fix_si(set
, isl_dim_set
, 0, 1);
4300 scop
= pet_scop_set_skip(scop
, pet_skip_now
, set
);
4305 /* Construct a pet_scop for a break statement.
4307 * We simply create an empty scop with both a universal pet_skip_now
4308 * skip condition and a universal pet_skip_later skip condition.
4309 * These skip conditions will then be taken into
4310 * account by the enclosing loop construct, possibly after
4311 * being incorporated into outer skip conditions.
4313 struct pet_scop
*PetScan::extract(BreakStmt
*stmt
)
4319 scop
= pet_scop_empty(ctx
);
4323 space
= isl_space_set_alloc(ctx
, 0, 1);
4324 set
= isl_set_universe(space
);
4325 set
= isl_set_fix_si(set
, isl_dim_set
, 0, 1);
4326 scop
= pet_scop_set_skip(scop
, pet_skip_now
, isl_set_copy(set
));
4327 scop
= pet_scop_set_skip(scop
, pet_skip_later
, set
);
4332 /* Try and construct a pet_scop corresponding to "stmt".
4334 * If "stmt" is a compound statement, then "skip_declarations"
4335 * indicates whether we should skip initial declarations in the
4336 * compound statement.
4338 * If the constructed pet_scop is not a (possibly) partial representation
4339 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4340 * In particular, if skip_declarations, then we may have skipped declarations
4341 * inside "stmt" and so the pet_scop may not represent the entire "stmt".
4342 * Note that this function may be called with "stmt" referring to the entire
4343 * body of the function, including the outer braces. In such cases,
4344 * skip_declarations will be set and the braces will not be taken into
4345 * account in scop->start and scop->end.
4347 struct pet_scop
*PetScan::extract(Stmt
*stmt
, bool skip_declarations
)
4349 struct pet_scop
*scop
;
4350 unsigned start
, end
;
4352 SourceManager
&SM
= PP
.getSourceManager();
4354 if (isa
<Expr
>(stmt
))
4355 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
4357 switch (stmt
->getStmtClass()) {
4358 case Stmt::WhileStmtClass
:
4359 scop
= extract(cast
<WhileStmt
>(stmt
));
4361 case Stmt::ForStmtClass
:
4362 scop
= extract_for(cast
<ForStmt
>(stmt
));
4364 case Stmt::IfStmtClass
:
4365 scop
= extract(cast
<IfStmt
>(stmt
));
4367 case Stmt::CompoundStmtClass
:
4368 scop
= extract(cast
<CompoundStmt
>(stmt
), skip_declarations
);
4370 case Stmt::LabelStmtClass
:
4371 scop
= extract(cast
<LabelStmt
>(stmt
));
4373 case Stmt::ContinueStmtClass
:
4374 scop
= extract(cast
<ContinueStmt
>(stmt
));
4376 case Stmt::BreakStmtClass
:
4377 scop
= extract(cast
<BreakStmt
>(stmt
));
4379 case Stmt::DeclStmtClass
:
4380 scop
= extract(cast
<DeclStmt
>(stmt
));
4387 if (partial
|| skip_declarations
)
4390 start
= getExpansionOffset(SM
, stmt
->getLocStart());
4391 loc
= PP
.getLocForEndOfToken(stmt
->getLocEnd());
4392 end
= getExpansionOffset(SM
, loc
);
4393 scop
= pet_scop_update_start_end(scop
, start
, end
);
4398 /* Do we need to construct a skip condition of the given type
4399 * on a sequence of statements?
4401 * There is no need to construct a new skip condition if only
4402 * only of the two statements has a skip condition or if both
4403 * of their skip conditions are affine.
4405 * In principle we also don't need a new continuation variable if
4406 * the continuation of scop2 is affine, but then we would need
4407 * to allow more complicated forms of continuations.
4409 static bool need_skip_seq(struct pet_scop
*scop1
, struct pet_scop
*scop2
,
4412 if (!scop1
|| !pet_scop_has_skip(scop1
, type
))
4414 if (!scop2
|| !pet_scop_has_skip(scop2
, type
))
4416 if (pet_scop_has_affine_skip(scop1
, type
) &&
4417 pet_scop_has_affine_skip(scop2
, type
))
4422 /* Construct a scop for computing the skip condition of the given type and
4423 * with access relation "skip_access" for a sequence of two scops "scop1"
4426 * The computed scop contains a single statement that essentially does
4428 * skip_cond = skip_cond_1 ? 1 : skip_cond_2
4430 * or, in other words, skip_cond1 || skip_cond2.
4431 * In this expression, skip_cond_2 is filtered to reflect that it is
4432 * only evaluated when skip_cond_1 is false.
4434 * The skip condition on scop1 is not removed because it still needs
4435 * to be applied to scop2 when these two scops are combined.
4437 static struct pet_scop
*extract_skip_seq(PetScan
*ps
,
4438 __isl_take isl_map
*skip_access
,
4439 struct pet_scop
*scop1
, struct pet_scop
*scop2
, enum pet_skip type
)
4442 struct pet_expr
*expr1
, *expr2
, *expr
, *expr_skip
;
4443 struct pet_stmt
*stmt
;
4444 struct pet_scop
*scop
;
4445 isl_ctx
*ctx
= ps
->ctx
;
4447 if (!scop1
|| !scop2
)
4450 expr1
= pet_scop_get_skip_expr(scop1
, type
);
4451 expr2
= pet_scop_get_skip_expr(scop2
, type
);
4452 pet_scop_reset_skip(scop2
, type
);
4454 expr2
= pet_expr_filter(expr2
, isl_map_copy(expr1
->acc
.access
), 0);
4456 expr
= universally_true(ctx
);
4457 expr
= pet_expr_new_ternary(ctx
, expr1
, expr
, expr2
);
4458 expr_skip
= pet_expr_from_access(isl_map_copy(skip_access
));
4460 expr_skip
->acc
.write
= 1;
4461 expr_skip
->acc
.read
= 0;
4463 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, expr_skip
, expr
);
4464 stmt
= pet_stmt_from_pet_expr(ctx
, -1, NULL
, ps
->n_stmt
++, expr
);
4466 scop
= pet_scop_from_pet_stmt(ctx
, stmt
);
4467 scop
= scop_add_array(scop
, skip_access
, ps
->ast_context
);
4468 isl_map_free(skip_access
);
4472 isl_map_free(skip_access
);
4476 /* Structure that handles the construction of skip conditions
4477 * on sequences of statements.
4479 * scop1 and scop2 represent the two statements that are combined
4481 struct pet_skip_info_seq
: public pet_skip_info
{
4482 struct pet_scop
*scop1
, *scop2
;
4484 pet_skip_info_seq(isl_ctx
*ctx
, struct pet_scop
*scop1
,
4485 struct pet_scop
*scop2
);
4486 void extract(PetScan
*scan
, enum pet_skip type
);
4487 void extract(PetScan
*scan
);
4488 struct pet_scop
*add(struct pet_scop
*scop
, enum pet_skip type
,
4490 struct pet_scop
*add(struct pet_scop
*scop
, int offset
);
4493 /* Initialize a pet_skip_info_seq structure based on
4494 * on the two statements that are going to be combined.
4496 pet_skip_info_seq::pet_skip_info_seq(isl_ctx
*ctx
, struct pet_scop
*scop1
,
4497 struct pet_scop
*scop2
) : pet_skip_info(ctx
), scop1(scop1
), scop2(scop2
)
4499 skip
[pet_skip_now
] = need_skip_seq(scop1
, scop2
, pet_skip_now
);
4500 equal
= skip
[pet_skip_now
] && skip_equals_skip_later(scop1
) &&
4501 skip_equals_skip_later(scop2
);
4502 skip
[pet_skip_later
] = skip
[pet_skip_now
] && !equal
&&
4503 need_skip_seq(scop1
, scop2
, pet_skip_later
);
4506 /* If we need to construct a skip condition of the given type,
4509 void pet_skip_info_seq::extract(PetScan
*scan
, enum pet_skip type
)
4514 access
[type
] = create_test_access(ctx
, scan
->n_test
++);
4515 scop
[type
] = extract_skip_seq(scan
, isl_map_copy(access
[type
]),
4516 scop1
, scop2
, type
);
4519 /* Construct the required skip conditions.
4521 void pet_skip_info_seq::extract(PetScan
*scan
)
4523 extract(scan
, pet_skip_now
);
4524 extract(scan
, pet_skip_later
);
4526 drop_skip_later(scop1
, scop2
);
4529 /* Add the computed skip condition of the give type to "main" and
4530 * add the scop for computing the condition at the given offset (the statement
4531 * number). Within this offset, the condition is computed at position 1
4532 * to ensure that it is computed after the corresponding statement.
4534 * If equal is set, then we only computed a skip condition for pet_skip_now,
4535 * but we also need to set it as main's pet_skip_later.
4537 struct pet_scop
*pet_skip_info_seq::add(struct pet_scop
*main
,
4538 enum pet_skip type
, int offset
)
4545 skip_set
= isl_map_range(access
[type
]);
4546 access
[type
] = NULL
;
4547 scop
[type
] = pet_scop_prefix(scop
[type
], 1);
4548 scop
[type
] = pet_scop_prefix(scop
[type
], offset
);
4549 main
= pet_scop_add_par(ctx
, main
, scop
[type
]);
4553 main
= pet_scop_set_skip(main
, pet_skip_later
,
4554 isl_set_copy(skip_set
));
4556 main
= pet_scop_set_skip(main
, type
, skip_set
);
4561 /* Add the computed skip conditions to "main" and
4562 * add the scops for computing the conditions at the given offset.
4564 struct pet_scop
*pet_skip_info_seq::add(struct pet_scop
*scop
, int offset
)
4566 scop
= add(scop
, pet_skip_now
, offset
);
4567 scop
= add(scop
, pet_skip_later
, offset
);
4572 /* Extract a clone of the kill statement in "scop".
4573 * "scop" is expected to have been created from a DeclStmt
4574 * and should have the kill as its first statement.
4576 struct pet_stmt
*PetScan::extract_kill(struct pet_scop
*scop
)
4578 struct pet_expr
*kill
;
4579 struct pet_stmt
*stmt
;
4584 if (scop
->n_stmt
< 1)
4585 isl_die(ctx
, isl_error_internal
,
4586 "expecting at least one statement", return NULL
);
4587 stmt
= scop
->stmts
[0];
4588 if (stmt
->body
->type
!= pet_expr_unary
||
4589 stmt
->body
->op
!= pet_op_kill
)
4590 isl_die(ctx
, isl_error_internal
,
4591 "expecting kill statement", return NULL
);
4593 access
= isl_map_copy(stmt
->body
->args
[0]->acc
.access
);
4594 access
= isl_map_reset_tuple_id(access
, isl_dim_in
);
4595 kill
= pet_expr_kill_from_access(access
);
4596 return pet_stmt_from_pet_expr(ctx
, stmt
->line
, NULL
, n_stmt
++, kill
);
4599 /* Mark all arrays in "scop" as being exposed.
4601 static struct pet_scop
*mark_exposed(struct pet_scop
*scop
)
4605 for (int i
= 0; i
< scop
->n_array
; ++i
)
4606 scop
->arrays
[i
]->exposed
= 1;
4610 /* Try and construct a pet_scop corresponding to (part of)
4611 * a sequence of statements.
4613 * "block" is set if the sequence respresents the children of
4614 * a compound statement.
4615 * "skip_declarations" is set if we should skip initial declarations
4616 * in the sequence of statements.
4618 * If there are any breaks or continues in the individual statements,
4619 * then we may have to compute a new skip condition.
4620 * This is handled using a pet_skip_info_seq object.
4621 * On initialization, the object checks if skip conditions need
4622 * to be computed. If so, it does so in "extract" and adds them in "add".
4624 * If "block" is set, then we need to insert kill statements at
4625 * the end of the block for any array that has been declared by
4626 * one of the statements in the sequence. Each of these declarations
4627 * results in the construction of a kill statement at the place
4628 * of the declaration, so we simply collect duplicates of
4629 * those kill statements and append these duplicates to the constructed scop.
4631 * If "block" is not set, then any array declared by one of the statements
4632 * in the sequence is marked as being exposed.
4634 struct pet_scop
*PetScan::extract(StmtRange stmt_range
, bool block
,
4635 bool skip_declarations
)
4640 bool partial_range
= false;
4641 set
<struct pet_stmt
*> kills
;
4642 set
<struct pet_stmt
*>::iterator it
;
4644 scop
= pet_scop_empty(ctx
);
4645 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
4647 struct pet_scop
*scop_i
;
4649 if (skip_declarations
&&
4650 child
->getStmtClass() == Stmt::DeclStmtClass
)
4653 scop_i
= extract(child
);
4654 if (scop
&& partial
) {
4655 pet_scop_free(scop_i
);
4658 pet_skip_info_seq
skip(ctx
, scop
, scop_i
);
4661 scop_i
= pet_scop_prefix(scop_i
, 0);
4662 if (scop_i
&& child
->getStmtClass() == Stmt::DeclStmtClass
) {
4664 kills
.insert(extract_kill(scop_i
));
4666 scop_i
= mark_exposed(scop_i
);
4668 scop_i
= pet_scop_prefix(scop_i
, j
);
4669 if (options
->autodetect
) {
4671 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4673 partial_range
= true;
4674 if (scop
->n_stmt
!= 0 && !scop_i
)
4677 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4680 scop
= skip
.add(scop
, j
);
4686 for (it
= kills
.begin(); it
!= kills
.end(); ++it
) {
4688 scop_j
= pet_scop_from_pet_stmt(ctx
, *it
);
4689 scop_j
= pet_scop_prefix(scop_j
, j
);
4690 scop
= pet_scop_add_seq(ctx
, scop
, scop_j
);
4693 if (scop
&& partial_range
)
4699 /* Check if the scop marked by the user is exactly this Stmt
4700 * or part of this Stmt.
4701 * If so, return a pet_scop corresponding to the marked region.
4702 * Otherwise, return NULL.
4704 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
4706 SourceManager
&SM
= PP
.getSourceManager();
4707 unsigned start_off
, end_off
;
4709 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
4710 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
4712 if (start_off
> loc
.end
)
4714 if (end_off
< loc
.start
)
4716 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
4717 return extract(stmt
);
4721 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
4722 Stmt
*child
= *start
;
4725 start_off
= getExpansionOffset(SM
, child
->getLocStart());
4726 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
4727 if (start_off
< loc
.start
&& end_off
> loc
.end
)
4729 if (start_off
>= loc
.start
)
4734 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
4736 start_off
= SM
.getFileOffset(child
->getLocStart());
4737 if (start_off
>= loc
.end
)
4741 return extract(StmtRange(start
, end
), false, false);
4744 /* Set the size of index "pos" of "array" to "size".
4745 * In particular, add a constraint of the form
4749 * to array->extent and a constraint of the form
4753 * to array->context.
4755 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
4756 __isl_take isl_pw_aff
*size
)
4766 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
4767 array
->context
= isl_set_intersect(array
->context
, valid
);
4769 dim
= isl_set_get_space(array
->extent
);
4770 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
4771 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
4772 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
4773 index
= isl_pw_aff_alloc(univ
, aff
);
4775 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
4776 isl_set_dim(array
->extent
, isl_dim_set
));
4777 id
= isl_set_get_tuple_id(array
->extent
);
4778 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
4779 bound
= isl_pw_aff_lt_set(index
, size
);
4781 array
->extent
= isl_set_intersect(array
->extent
, bound
);
4783 if (!array
->context
|| !array
->extent
)
4788 pet_array_free(array
);
4792 /* Figure out the size of the array at position "pos" and all
4793 * subsequent positions from "type" and update "array" accordingly.
4795 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
4796 const Type
*type
, int pos
)
4798 const ArrayType
*atype
;
4804 if (type
->isPointerType()) {
4805 type
= type
->getPointeeType().getTypePtr();
4806 return set_upper_bounds(array
, type
, pos
+ 1);
4808 if (!type
->isArrayType())
4811 type
= type
->getCanonicalTypeInternal().getTypePtr();
4812 atype
= cast
<ArrayType
>(type
);
4814 if (type
->isConstantArrayType()) {
4815 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
4816 size
= extract_affine(ca
->getSize());
4817 array
= update_size(array
, pos
, size
);
4818 } else if (type
->isVariableArrayType()) {
4819 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
4820 size
= extract_affine(vla
->getSizeExpr());
4821 array
= update_size(array
, pos
, size
);
4824 type
= atype
->getElementType().getTypePtr();
4826 return set_upper_bounds(array
, type
, pos
+ 1);
4829 /* Is "T" the type of a variable length array with static size?
4831 static bool is_vla_with_static_size(QualType T
)
4833 const VariableArrayType
*vlatype
;
4835 if (!T
->isVariableArrayType())
4837 vlatype
= cast
<VariableArrayType
>(T
);
4838 return vlatype
->getSizeModifier() == VariableArrayType::Static
;
4841 /* Return the type of "decl" as an array.
4843 * In particular, if "decl" is a parameter declaration that
4844 * is a variable length array with a static size, then
4845 * return the original type (i.e., the variable length array).
4846 * Otherwise, return the type of decl.
4848 static QualType
get_array_type(ValueDecl
*decl
)
4853 parm
= dyn_cast
<ParmVarDecl
>(decl
);
4855 return decl
->getType();
4857 T
= parm
->getOriginalType();
4858 if (!is_vla_with_static_size(T
))
4859 return decl
->getType();
4863 /* Construct and return a pet_array corresponding to the variable "decl".
4864 * In particular, initialize array->extent to
4866 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4868 * and then call set_upper_bounds to set the upper bounds on the indices
4869 * based on the type of the variable.
4871 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
)
4873 struct pet_array
*array
;
4874 QualType qt
= get_array_type(decl
);
4875 const Type
*type
= qt
.getTypePtr();
4876 int depth
= array_depth(type
);
4877 QualType base
= base_type(qt
);
4882 array
= isl_calloc_type(ctx
, struct pet_array
);
4886 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
4887 dim
= isl_space_set_alloc(ctx
, 0, depth
);
4888 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
4890 array
->extent
= isl_set_nat_universe(dim
);
4892 dim
= isl_space_params_alloc(ctx
, 0);
4893 array
->context
= isl_set_universe(dim
);
4895 array
= set_upper_bounds(array
, type
, 0);
4899 name
= base
.getAsString();
4900 array
->element_type
= strdup(name
.c_str());
4901 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
4906 /* Construct a list of pet_arrays, one for each array (or scalar)
4907 * accessed inside "scop", add this list to "scop" and return the result.
4909 * The context of "scop" is updated with the intersection of
4910 * the contexts of all arrays, i.e., constraints on the parameters
4911 * that ensure that the arrays have a valid (non-negative) size.
4913 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
4916 set
<ValueDecl
*> arrays
;
4917 set
<ValueDecl
*>::iterator it
;
4919 struct pet_array
**scop_arrays
;
4924 pet_scop_collect_arrays(scop
, arrays
);
4925 if (arrays
.size() == 0)
4928 n_array
= scop
->n_array
;
4930 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
4931 n_array
+ arrays
.size());
4934 scop
->arrays
= scop_arrays
;
4936 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
4937 struct pet_array
*array
;
4938 scop
->arrays
[n_array
+ i
] = array
= extract_array(ctx
, *it
);
4939 if (!scop
->arrays
[n_array
+ i
])
4942 scop
->context
= isl_set_intersect(scop
->context
,
4943 isl_set_copy(array
->context
));
4950 pet_scop_free(scop
);
4954 /* Bound all parameters in scop->context to the possible values
4955 * of the corresponding C variable.
4957 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
4964 n
= isl_set_dim(scop
->context
, isl_dim_param
);
4965 for (int i
= 0; i
< n
; ++i
) {
4969 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
4970 if (is_nested_parameter(id
)) {
4972 isl_die(isl_set_get_ctx(scop
->context
),
4974 "unresolved nested parameter", goto error
);
4976 decl
= (ValueDecl
*) isl_id_get_user(id
);
4979 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
4987 pet_scop_free(scop
);
4991 /* Construct a pet_scop from the given function.
4993 * If the scop was delimited by scop and endscop pragmas, then we override
4994 * the file offsets by those derived from the pragmas.
4996 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
5001 stmt
= fd
->getBody();
5003 if (options
->autodetect
)
5004 scop
= extract(stmt
, true);
5007 scop
= pet_scop_update_start_end(scop
, loc
.start
, loc
.end
);
5009 scop
= pet_scop_detect_parameter_accesses(scop
);
5010 scop
= scan_arrays(scop
);
5011 scop
= add_parameter_bounds(scop
);
5012 scop
= pet_scop_gist(scop
, value_bounds
);