2 * Copyright 2011 Leiden University. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following
13 * disclaimer in the documentation and/or other materials provided
14 * with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
20 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 * The views and conclusions contained in the software and documentation
29 * are those of the authors and should not be interpreted as
30 * representing official policies, either expressed or implied, of
37 #include <clang/AST/ASTDiagnostic.h>
38 #include <clang/AST/Expr.h>
39 #include <clang/AST/RecursiveASTVisitor.h>
42 #include <isl/space.h>
48 #include "scop_plus.h"
53 using namespace clang
;
56 /* Check if the element type corresponding to the given array type
57 * has a const qualifier.
59 static bool const_base(QualType qt
)
61 const Type
*type
= qt
.getTypePtr();
63 if (type
->isPointerType())
64 return const_base(type
->getPointeeType());
65 if (type
->isArrayType()) {
66 const ArrayType
*atype
;
67 type
= type
->getCanonicalTypeInternal().getTypePtr();
68 atype
= cast
<ArrayType
>(type
);
69 return const_base(atype
->getElementType());
72 return qt
.isConstQualified();
75 /* Look for any assignments to scalar variables in part of the parse
76 * tree and set assigned_value to NULL for each of them.
77 * Also reset assigned_value if the address of a scalar variable
78 * is being taken. As an exception, if the address is passed to a function
79 * that is declared to receive a const pointer, then assigned_value is
82 * This ensures that we won't use any previously stored value
83 * in the current subtree and its parents.
85 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
86 map
<ValueDecl
*, Expr
*> &assigned_value
;
87 set
<UnaryOperator
*> skip
;
89 clear_assignments(map
<ValueDecl
*, Expr
*> &assigned_value
) :
90 assigned_value(assigned_value
) {}
92 /* Check for "address of" operators whose value is passed
93 * to a const pointer argument and add them to "skip", so that
94 * we can skip them in VisitUnaryOperator.
96 bool VisitCallExpr(CallExpr
*expr
) {
98 fd
= expr
->getDirectCallee();
101 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
102 Expr
*arg
= expr
->getArg(i
);
104 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
105 ImplicitCastExpr
*ice
;
106 ice
= cast
<ImplicitCastExpr
>(arg
);
107 arg
= ice
->getSubExpr();
109 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
111 op
= cast
<UnaryOperator
>(arg
);
112 if (op
->getOpcode() != UO_AddrOf
)
114 if (const_base(fd
->getParamDecl(i
)->getType()))
120 bool VisitUnaryOperator(UnaryOperator
*expr
) {
125 if (expr
->getOpcode() != UO_AddrOf
)
127 if (skip
.find(expr
) != skip
.end())
130 arg
= expr
->getSubExpr();
131 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
133 ref
= cast
<DeclRefExpr
>(arg
);
134 decl
= ref
->getDecl();
135 assigned_value
[decl
] = NULL
;
139 bool VisitBinaryOperator(BinaryOperator
*expr
) {
144 if (!expr
->isAssignmentOp())
146 lhs
= expr
->getLHS();
147 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
149 ref
= cast
<DeclRefExpr
>(lhs
);
150 decl
= ref
->getDecl();
151 assigned_value
[decl
] = NULL
;
156 /* Keep a copy of the currently assigned values.
158 * Any variable that is assigned a value inside the current scope
159 * is removed again when we leave the scope (either because it wasn't
160 * stored in the cache or because it has a different value in the cache).
162 struct assigned_value_cache
{
163 map
<ValueDecl
*, Expr
*> &assigned_value
;
164 map
<ValueDecl
*, Expr
*> cache
;
166 assigned_value_cache(map
<ValueDecl
*, Expr
*> &assigned_value
) :
167 assigned_value(assigned_value
), cache(assigned_value
) {}
168 ~assigned_value_cache() {
169 map
<ValueDecl
*, Expr
*>::iterator it
= cache
.begin();
170 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
173 (cache
.find(it
->first
) != cache
.end() &&
174 cache
[it
->first
] != it
->second
))
175 cache
[it
->first
] = NULL
;
177 assigned_value
= cache
;
181 /* Called if we found something we (currently) cannot handle.
182 * We'll provide more informative warnings later.
184 * We only actually complain if autodetect is false.
186 void PetScan::unsupported(Stmt
*stmt
)
191 SourceLocation loc
= stmt
->getLocStart();
192 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
193 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
195 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
198 /* Extract an integer from "expr" and store it in "v".
200 int PetScan::extract_int(IntegerLiteral
*expr
, isl_int
*v
)
202 const Type
*type
= expr
->getType().getTypePtr();
203 int is_signed
= type
->hasSignedIntegerRepresentation();
206 int64_t i
= expr
->getValue().getSExtValue();
207 isl_int_set_si(*v
, i
);
209 uint64_t i
= expr
->getValue().getZExtValue();
210 isl_int_set_ui(*v
, i
);
216 /* Extract an integer from "expr" and store it in "v".
217 * Return -1 if "expr" does not (obviously) represent an integer.
219 int PetScan::extract_int(clang::ParenExpr
*expr
, isl_int
*v
)
221 return extract_int(expr
->getSubExpr(), v
);
224 /* Extract an integer from "expr" and store it in "v".
225 * Return -1 if "expr" does not (obviously) represent an integer.
227 int PetScan::extract_int(clang::Expr
*expr
, isl_int
*v
)
229 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
230 return extract_int(cast
<IntegerLiteral
>(expr
), v
);
231 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
232 return extract_int(cast
<ParenExpr
>(expr
), v
);
238 /* Extract an affine expression from the IntegerLiteral "expr".
240 __isl_give isl_pw_aff
*PetScan::extract_affine(IntegerLiteral
*expr
)
242 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
243 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
244 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
245 isl_set
*dom
= isl_set_universe(dim
);
249 extract_int(expr
, &v
);
250 aff
= isl_aff_add_constant(aff
, v
);
253 return isl_pw_aff_alloc(dom
, aff
);
256 /* Extract an affine expression from the APInt "val".
258 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
260 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
261 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
262 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
263 isl_set
*dom
= isl_set_universe(dim
);
267 isl_int_set_ui(v
, val
.getZExtValue());
268 aff
= isl_aff_add_constant(aff
, v
);
271 return isl_pw_aff_alloc(dom
, aff
);
274 __isl_give isl_pw_aff
*PetScan::extract_affine(ImplicitCastExpr
*expr
)
276 return extract_affine(expr
->getSubExpr());
279 /* Extract an affine expression from the DeclRefExpr "expr".
281 * If the variable has been assigned a value, then we check whether
282 * we know what expression was assigned and whether this expression
283 * is affine. If so, we convert the expression to an isl_pw_aff
284 * and to an extra parameter otherwise (provided nesting_enabled is set).
286 * Otherwise, we simply return an expression that is equal
287 * to a parameter corresponding to the referenced variable.
289 __isl_give isl_pw_aff
*PetScan::extract_affine(DeclRefExpr
*expr
)
291 ValueDecl
*decl
= expr
->getDecl();
292 const Type
*type
= decl
->getType().getTypePtr();
298 if (!type
->isIntegerType()) {
303 if (assigned_value
.find(decl
) != assigned_value
.end()) {
304 if (assigned_value
[decl
] && is_affine(assigned_value
[decl
]))
305 return extract_affine(assigned_value
[decl
]);
307 return nested_access(expr
);
310 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
311 dim
= isl_space_params_alloc(ctx
, 1);
313 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
315 dom
= isl_set_universe(isl_space_copy(dim
));
316 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
317 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
319 return isl_pw_aff_alloc(dom
, aff
);
322 /* Extract an affine expression from an integer division operation.
323 * In particular, if "expr" is lhs/rhs, then return
325 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
327 * The second argument (rhs) is required to be a (positive) integer constant.
329 __isl_give isl_pw_aff
*PetScan::extract_affine_div(BinaryOperator
*expr
)
332 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
337 rhs_expr
= expr
->getRHS();
339 if (extract_int(rhs_expr
, &v
) < 0) {
344 lhs
= extract_affine(expr
->getLHS());
345 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
347 lhs
= isl_pw_aff_scale_down(lhs
, v
);
350 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(lhs
));
351 lhs_c
= isl_pw_aff_ceil(lhs
);
352 res
= isl_pw_aff_cond(cond
, lhs_f
, lhs_c
);
357 /* Extract an affine expression from a modulo operation.
358 * In particular, if "expr" is lhs/rhs, then return
360 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
362 * The second argument (rhs) is required to be a (positive) integer constant.
364 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
367 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
372 rhs_expr
= expr
->getRHS();
373 if (rhs_expr
->getStmtClass() != Stmt::IntegerLiteralClass
) {
378 lhs
= extract_affine(expr
->getLHS());
379 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
382 extract_int(cast
<IntegerLiteral
>(rhs_expr
), &v
);
383 res
= isl_pw_aff_scale_down(isl_pw_aff_copy(lhs
), v
);
385 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(res
));
386 lhs_c
= isl_pw_aff_ceil(res
);
387 res
= isl_pw_aff_cond(cond
, lhs_f
, lhs_c
);
389 res
= isl_pw_aff_scale(res
, v
);
392 res
= isl_pw_aff_sub(lhs
, res
);
397 /* Extract an affine expression from a multiplication operation.
398 * This is only allowed if at least one of the two arguments
399 * is a (piecewise) constant.
401 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
406 lhs
= extract_affine(expr
->getLHS());
407 rhs
= extract_affine(expr
->getRHS());
409 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
410 isl_pw_aff_free(lhs
);
411 isl_pw_aff_free(rhs
);
416 return isl_pw_aff_mul(lhs
, rhs
);
419 /* Extract an affine expression from an addition or subtraction operation.
421 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
426 lhs
= extract_affine(expr
->getLHS());
427 rhs
= extract_affine(expr
->getRHS());
429 switch (expr
->getOpcode()) {
431 return isl_pw_aff_add(lhs
, rhs
);
433 return isl_pw_aff_sub(lhs
, rhs
);
435 isl_pw_aff_free(lhs
);
436 isl_pw_aff_free(rhs
);
446 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
452 isl_int_set_si(mod
, 1);
453 isl_int_mul_2exp(mod
, mod
, width
);
455 pwaff
= isl_pw_aff_mod(pwaff
, mod
);
462 /* Extract an affine expression from some binary operations.
463 * If the result of the expression is unsigned, then we wrap it
464 * based on the size of the type.
466 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
470 switch (expr
->getOpcode()) {
473 res
= extract_affine_add(expr
);
476 res
= extract_affine_div(expr
);
479 res
= extract_affine_mod(expr
);
482 res
= extract_affine_mul(expr
);
489 if (expr
->getType()->isUnsignedIntegerType())
490 res
= wrap(res
, ast_context
.getIntWidth(expr
->getType()));
495 /* Extract an affine expression from a negation operation.
497 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
499 if (expr
->getOpcode() == UO_Minus
)
500 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
506 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
508 return extract_affine(expr
->getSubExpr());
511 /* Extract an affine expression from some special function calls.
512 * In particular, we handle "min", "max", "ceild" and "floord".
513 * In case of the latter two, the second argument needs to be
514 * a (positive) integer constant.
516 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
520 isl_pw_aff
*aff1
, *aff2
;
522 fd
= expr
->getDirectCallee();
528 name
= fd
->getDeclName().getAsString();
529 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
530 !(expr
->getNumArgs() == 2 && name
== "max") &&
531 !(expr
->getNumArgs() == 2 && name
== "floord") &&
532 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
537 if (name
== "min" || name
== "max") {
538 aff1
= extract_affine(expr
->getArg(0));
539 aff2
= extract_affine(expr
->getArg(1));
542 aff1
= isl_pw_aff_min(aff1
, aff2
);
544 aff1
= isl_pw_aff_max(aff1
, aff2
);
545 } else if (name
== "floord" || name
== "ceild") {
547 Expr
*arg2
= expr
->getArg(1);
549 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
553 aff1
= extract_affine(expr
->getArg(0));
555 extract_int(cast
<IntegerLiteral
>(arg2
), &v
);
556 aff1
= isl_pw_aff_scale_down(aff1
, v
);
558 if (name
== "floord")
559 aff1
= isl_pw_aff_floor(aff1
);
561 aff1
= isl_pw_aff_ceil(aff1
);
571 /* This method is called when we come across an access that is
572 * nested in what is supposed to be an affine expression.
573 * If nesting is allowed, we return a new parameter that corresponds
574 * to this nested access. Otherwise, we simply complain.
576 * The new parameter is resolved in resolve_nested.
578 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
585 if (!nesting_enabled
) {
590 id
= isl_id_alloc(ctx
, NULL
, expr
);
591 dim
= isl_space_params_alloc(ctx
, 1);
593 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
595 dom
= isl_set_universe(isl_space_copy(dim
));
596 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
597 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
599 return isl_pw_aff_alloc(dom
, aff
);
602 /* Affine expressions are not supposed to contain array accesses,
603 * but if nesting is allowed, we return a parameter corresponding
604 * to the array access.
606 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
608 return nested_access(expr
);
611 /* Extract an affine expression from a conditional operation.
613 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
616 isl_pw_aff
*lhs
, *rhs
;
618 cond
= extract_condition(expr
->getCond());
619 lhs
= extract_affine(expr
->getTrueExpr());
620 rhs
= extract_affine(expr
->getFalseExpr());
622 return isl_pw_aff_cond(cond
, lhs
, rhs
);
625 /* Extract an affine expression, if possible, from "expr".
626 * Otherwise return NULL.
628 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
630 switch (expr
->getStmtClass()) {
631 case Stmt::ImplicitCastExprClass
:
632 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
633 case Stmt::IntegerLiteralClass
:
634 return extract_affine(cast
<IntegerLiteral
>(expr
));
635 case Stmt::DeclRefExprClass
:
636 return extract_affine(cast
<DeclRefExpr
>(expr
));
637 case Stmt::BinaryOperatorClass
:
638 return extract_affine(cast
<BinaryOperator
>(expr
));
639 case Stmt::UnaryOperatorClass
:
640 return extract_affine(cast
<UnaryOperator
>(expr
));
641 case Stmt::ParenExprClass
:
642 return extract_affine(cast
<ParenExpr
>(expr
));
643 case Stmt::CallExprClass
:
644 return extract_affine(cast
<CallExpr
>(expr
));
645 case Stmt::ArraySubscriptExprClass
:
646 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
647 case Stmt::ConditionalOperatorClass
:
648 return extract_affine(cast
<ConditionalOperator
>(expr
));
655 __isl_give isl_map
*PetScan::extract_access(ImplicitCastExpr
*expr
)
657 return extract_access(expr
->getSubExpr());
660 /* Return the depth of an array of the given type.
662 static int array_depth(const Type
*type
)
664 if (type
->isPointerType())
665 return 1 + array_depth(type
->getPointeeType().getTypePtr());
666 if (type
->isArrayType()) {
667 const ArrayType
*atype
;
668 type
= type
->getCanonicalTypeInternal().getTypePtr();
669 atype
= cast
<ArrayType
>(type
);
670 return 1 + array_depth(atype
->getElementType().getTypePtr());
675 /* Return the element type of the given array type.
677 static QualType
base_type(QualType qt
)
679 const Type
*type
= qt
.getTypePtr();
681 if (type
->isPointerType())
682 return base_type(type
->getPointeeType());
683 if (type
->isArrayType()) {
684 const ArrayType
*atype
;
685 type
= type
->getCanonicalTypeInternal().getTypePtr();
686 atype
= cast
<ArrayType
>(type
);
687 return base_type(atype
->getElementType());
692 /* Extract an access relation from a reference to a variable.
693 * If the variable has name "A" and its type corresponds to an
694 * array of depth d, then the returned access relation is of the
697 * { [] -> A[i_1,...,i_d] }
699 __isl_give isl_map
*PetScan::extract_access(DeclRefExpr
*expr
)
701 ValueDecl
*decl
= expr
->getDecl();
702 int depth
= array_depth(decl
->getType().getTypePtr());
703 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
704 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, depth
);
707 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
709 access_rel
= isl_map_universe(dim
);
714 /* Extract an access relation from an integer contant.
715 * If the value of the constant is "v", then the returned access relation
720 __isl_give isl_map
*PetScan::extract_access(IntegerLiteral
*expr
)
722 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr
)));
725 /* Try and extract an access relation from the given Expr.
726 * Return NULL if it doesn't work out.
728 __isl_give isl_map
*PetScan::extract_access(Expr
*expr
)
730 switch (expr
->getStmtClass()) {
731 case Stmt::ImplicitCastExprClass
:
732 return extract_access(cast
<ImplicitCastExpr
>(expr
));
733 case Stmt::DeclRefExprClass
:
734 return extract_access(cast
<DeclRefExpr
>(expr
));
735 case Stmt::ArraySubscriptExprClass
:
736 return extract_access(cast
<ArraySubscriptExpr
>(expr
));
743 /* Assign the affine expression "index" to the output dimension "pos" of "map"
744 * and return the result.
746 __isl_give isl_map
*set_index(__isl_take isl_map
*map
, int pos
,
747 __isl_take isl_pw_aff
*index
)
750 int len
= isl_map_dim(map
, isl_dim_out
);
753 index_map
= isl_map_from_range(isl_set_from_pw_aff(index
));
754 index_map
= isl_map_insert_dims(index_map
, isl_dim_out
, 0, pos
);
755 index_map
= isl_map_add_dims(index_map
, isl_dim_out
, len
- pos
- 1);
756 id
= isl_map_get_tuple_id(map
, isl_dim_out
);
757 index_map
= isl_map_set_tuple_id(index_map
, isl_dim_out
, id
);
759 map
= isl_map_intersect(map
, index_map
);
764 /* Extract an access relation from the given array subscript expression.
765 * If nesting is allowed in general, then we turn it on while
766 * examining the index expression.
768 * We first extract an access relation from the base.
769 * This will result in an access relation with a range that corresponds
770 * to the array being accessed and with earlier indices filled in already.
771 * We then extract the current index and fill that in as well.
772 * The position of the current index is based on the type of base.
773 * If base is the actual array variable, then the depth of this type
774 * will be the same as the depth of the array and we will fill in
775 * the first array index.
776 * Otherwise, the depth of the base type will be smaller and we will fill
779 __isl_give isl_map
*PetScan::extract_access(ArraySubscriptExpr
*expr
)
781 Expr
*base
= expr
->getBase();
782 Expr
*idx
= expr
->getIdx();
784 isl_map
*base_access
;
786 int depth
= array_depth(base
->getType().getTypePtr());
788 bool save_nesting
= nesting_enabled
;
790 nesting_enabled
= allow_nested
;
792 base_access
= extract_access(base
);
793 index
= extract_affine(idx
);
795 nesting_enabled
= save_nesting
;
797 pos
= isl_map_dim(base_access
, isl_dim_out
) - depth
;
798 access
= set_index(base_access
, pos
, index
);
803 /* Check if "expr" calls function "minmax" with two arguments and if so
804 * make lhs and rhs refer to these two arguments.
806 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
812 if (expr
->getStmtClass() != Stmt::CallExprClass
)
815 call
= cast
<CallExpr
>(expr
);
816 fd
= call
->getDirectCallee();
820 if (call
->getNumArgs() != 2)
823 name
= fd
->getDeclName().getAsString();
827 lhs
= call
->getArg(0);
828 rhs
= call
->getArg(1);
833 /* Check if "expr" is of the form min(lhs, rhs) and if so make
834 * lhs and rhs refer to the two arguments.
836 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
838 return is_minmax(expr
, "min", lhs
, rhs
);
841 /* Check if "expr" is of the form max(lhs, rhs) and if so make
842 * lhs and rhs refer to the two arguments.
844 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
846 return is_minmax(expr
, "max", lhs
, rhs
);
849 /* Extract a set of values satisfying the comparison "LHS op RHS"
850 * "comp" is the original statement that "LHS op RHS" is derived from
851 * and is used for diagnostics.
853 * If the comparison is of the form
857 * then the set is constructed as the intersection of the set corresponding
862 * A similar optimization is performed for max(a,b) <= c.
863 * We do this because that will lead to simpler representations of the set.
864 * If isl is ever enhanced to explicitly deal with min and max expressions,
865 * this optimization can be removed.
867 __isl_give isl_set
*PetScan::extract_comparison(BinaryOperatorKind op
,
868 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
875 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
877 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
879 if (op
== BO_LT
|| op
== BO_LE
) {
881 isl_set
*set1
, *set2
;
882 if (is_min(RHS
, expr1
, expr2
)) {
883 set1
= extract_comparison(op
, LHS
, expr1
, comp
);
884 set2
= extract_comparison(op
, LHS
, expr2
, comp
);
885 return isl_set_intersect(set1
, set2
);
887 if (is_max(LHS
, expr1
, expr2
)) {
888 set1
= extract_comparison(op
, expr1
, RHS
, comp
);
889 set2
= extract_comparison(op
, expr2
, RHS
, comp
);
890 return isl_set_intersect(set1
, set2
);
894 lhs
= extract_affine(LHS
);
895 rhs
= extract_affine(RHS
);
899 cond
= isl_pw_aff_lt_set(lhs
, rhs
);
902 cond
= isl_pw_aff_le_set(lhs
, rhs
);
905 cond
= isl_pw_aff_eq_set(lhs
, rhs
);
908 cond
= isl_pw_aff_ne_set(lhs
, rhs
);
911 isl_pw_aff_free(lhs
);
912 isl_pw_aff_free(rhs
);
917 cond
= isl_set_coalesce(cond
);
922 __isl_give isl_set
*PetScan::extract_comparison(BinaryOperator
*comp
)
924 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
925 comp
->getRHS(), comp
);
928 /* Extract a set of values satisfying the negation (logical not)
929 * of a subexpression.
931 __isl_give isl_set
*PetScan::extract_boolean(UnaryOperator
*op
)
935 cond
= extract_condition(op
->getSubExpr());
937 return isl_set_complement(cond
);
940 /* Extract a set of values satisfying the union (logical or)
941 * or intersection (logical and) of two subexpressions.
943 __isl_give isl_set
*PetScan::extract_boolean(BinaryOperator
*comp
)
949 lhs
= extract_condition(comp
->getLHS());
950 rhs
= extract_condition(comp
->getRHS());
952 switch (comp
->getOpcode()) {
954 cond
= isl_set_intersect(lhs
, rhs
);
957 cond
= isl_set_union(lhs
, rhs
);
969 __isl_give isl_set
*PetScan::extract_condition(UnaryOperator
*expr
)
971 switch (expr
->getOpcode()) {
973 return extract_boolean(expr
);
980 /* Extract a set of values satisfying the condition "expr != 0".
982 __isl_give isl_set
*PetScan::extract_implicit_condition(Expr
*expr
)
984 return isl_pw_aff_non_zero_set(extract_affine(expr
));
987 /* Extract a set of values satisfying the condition expressed by "expr".
989 * If the expression doesn't look like a condition, we assume it
990 * is an affine expression and return the condition "expr != 0".
992 __isl_give isl_set
*PetScan::extract_condition(Expr
*expr
)
994 BinaryOperator
*comp
;
997 return isl_set_universe(isl_space_params_alloc(ctx
, 0));
999 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1000 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1002 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1003 return extract_condition(cast
<UnaryOperator
>(expr
));
1005 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1006 return extract_implicit_condition(expr
);
1008 comp
= cast
<BinaryOperator
>(expr
);
1009 switch (comp
->getOpcode()) {
1016 return extract_comparison(comp
);
1019 return extract_boolean(comp
);
1021 return extract_implicit_condition(expr
);
1025 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
1029 return pet_op_minus
;
1035 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
1039 return pet_op_add_assign
;
1041 return pet_op_sub_assign
;
1043 return pet_op_mul_assign
;
1045 return pet_op_div_assign
;
1047 return pet_op_assign
;
1069 /* Construct a pet_expr representing a unary operator expression.
1071 struct pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1073 struct pet_expr
*arg
;
1074 enum pet_op_type op
;
1076 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1077 if (op
== pet_op_last
) {
1082 arg
= extract_expr(expr
->getSubExpr());
1084 return pet_expr_new_unary(ctx
, op
, arg
);
1087 /* Mark the given access pet_expr as a write.
1088 * If a scalar is being accessed, then mark its value
1089 * as unknown in assigned_value.
1091 void PetScan::mark_write(struct pet_expr
*access
)
1096 access
->acc
.write
= 1;
1097 access
->acc
.read
= 0;
1099 if (isl_map_dim(access
->acc
.access
, isl_dim_out
) != 0)
1102 id
= isl_map_get_tuple_id(access
->acc
.access
, isl_dim_out
);
1103 decl
= (ValueDecl
*) isl_id_get_user(id
);
1104 assigned_value
[decl
] = NULL
;
1108 /* Construct a pet_expr representing a binary operator expression.
1110 * If the top level operator is an assignment and the LHS is an access,
1111 * then we mark that access as a write. If the operator is a compound
1112 * assignment, the access is marked as both a read and a write.
1114 * If "expr" assigns something to a scalar variable, then we keep track
1115 * of the assigned expression in assigned_value so that we can plug
1116 * it in when we later come across the same variable.
1118 struct pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1120 struct pet_expr
*lhs
, *rhs
;
1121 enum pet_op_type op
;
1123 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1124 if (op
== pet_op_last
) {
1129 lhs
= extract_expr(expr
->getLHS());
1130 rhs
= extract_expr(expr
->getRHS());
1132 if (expr
->isAssignmentOp() && lhs
&& lhs
->type
== pet_expr_access
) {
1134 if (expr
->isCompoundAssignmentOp())
1138 if (expr
->getOpcode() == BO_Assign
&&
1139 lhs
&& lhs
->type
== pet_expr_access
&&
1140 isl_map_dim(lhs
->acc
.access
, isl_dim_out
) == 0) {
1141 isl_id
*id
= isl_map_get_tuple_id(lhs
->acc
.access
, isl_dim_out
);
1142 ValueDecl
*decl
= (ValueDecl
*) isl_id_get_user(id
);
1143 assigned_value
[decl
] = expr
->getRHS();
1147 return pet_expr_new_binary(ctx
, op
, lhs
, rhs
);
1150 /* Construct a pet_expr representing a conditional operation.
1152 struct pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1154 struct pet_expr
*cond
, *lhs
, *rhs
;
1156 cond
= extract_expr(expr
->getCond());
1157 lhs
= extract_expr(expr
->getTrueExpr());
1158 rhs
= extract_expr(expr
->getFalseExpr());
1160 return pet_expr_new_ternary(ctx
, cond
, lhs
, rhs
);
1163 struct pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1165 return extract_expr(expr
->getSubExpr());
1168 /* Construct a pet_expr representing a floating point value.
1170 struct pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1172 return pet_expr_new_double(ctx
, expr
->getValueAsApproximateDouble());
1175 /* Extract an access relation from "expr" and then convert it into
1178 struct pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1181 struct pet_expr
*pe
;
1183 switch (expr
->getStmtClass()) {
1184 case Stmt::ArraySubscriptExprClass
:
1185 access
= extract_access(cast
<ArraySubscriptExpr
>(expr
));
1187 case Stmt::DeclRefExprClass
:
1188 access
= extract_access(cast
<DeclRefExpr
>(expr
));
1190 case Stmt::IntegerLiteralClass
:
1191 access
= extract_access(cast
<IntegerLiteral
>(expr
));
1198 pe
= pet_expr_from_access(access
);
1203 struct pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1205 return extract_expr(expr
->getSubExpr());
1208 /* Construct a pet_expr representing a function call.
1210 * If we are passing along a pointer to an array element
1211 * or an entire row or even higher dimensional slice of an array,
1212 * then the function being called may write into the array.
1214 * We assume here that if the function is declared to take a pointer
1215 * to a const type, then the function will perform a read
1216 * and that otherwise, it will perform a write.
1218 struct pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1220 struct pet_expr
*res
= NULL
;
1224 fd
= expr
->getDirectCallee();
1230 name
= fd
->getDeclName().getAsString();
1231 res
= pet_expr_new_call(ctx
, name
.c_str(), expr
->getNumArgs());
1235 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
1236 Expr
*arg
= expr
->getArg(i
);
1239 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1240 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(arg
);
1241 arg
= ice
->getSubExpr();
1243 if (arg
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1244 UnaryOperator
*op
= cast
<UnaryOperator
>(arg
);
1245 if (op
->getOpcode() == UO_AddrOf
) {
1247 arg
= op
->getSubExpr();
1250 res
->args
[i
] = PetScan::extract_expr(arg
);
1253 if (arg
->getStmtClass() == Stmt::ArraySubscriptExprClass
&&
1254 array_depth(arg
->getType().getTypePtr()) > 0)
1256 if (is_addr
&& res
->args
[i
]->type
== pet_expr_access
) {
1257 ParmVarDecl
*parm
= fd
->getParamDecl(i
);
1258 if (!const_base(parm
->getType()))
1259 mark_write(res
->args
[i
]);
1269 /* Try and onstruct a pet_expr representing "expr".
1271 struct pet_expr
*PetScan::extract_expr(Expr
*expr
)
1273 switch (expr
->getStmtClass()) {
1274 case Stmt::UnaryOperatorClass
:
1275 return extract_expr(cast
<UnaryOperator
>(expr
));
1276 case Stmt::CompoundAssignOperatorClass
:
1277 case Stmt::BinaryOperatorClass
:
1278 return extract_expr(cast
<BinaryOperator
>(expr
));
1279 case Stmt::ImplicitCastExprClass
:
1280 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1281 case Stmt::ArraySubscriptExprClass
:
1282 case Stmt::DeclRefExprClass
:
1283 case Stmt::IntegerLiteralClass
:
1284 return extract_access_expr(expr
);
1285 case Stmt::FloatingLiteralClass
:
1286 return extract_expr(cast
<FloatingLiteral
>(expr
));
1287 case Stmt::ParenExprClass
:
1288 return extract_expr(cast
<ParenExpr
>(expr
));
1289 case Stmt::ConditionalOperatorClass
:
1290 return extract_expr(cast
<ConditionalOperator
>(expr
));
1291 case Stmt::CallExprClass
:
1292 return extract_expr(cast
<CallExpr
>(expr
));
1299 /* Check if the given initialization statement is an assignment.
1300 * If so, return that assignment. Otherwise return NULL.
1302 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1304 BinaryOperator
*ass
;
1306 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1309 ass
= cast
<BinaryOperator
>(init
);
1310 if (ass
->getOpcode() != BO_Assign
)
1316 /* Check if the given initialization statement is a declaration
1317 * of a single variable.
1318 * If so, return that declaration. Otherwise return NULL.
1320 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1324 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1327 decl
= cast
<DeclStmt
>(init
);
1329 if (!decl
->isSingleDecl())
1332 return decl
->getSingleDecl();
1335 /* Given the assignment operator in the initialization of a for loop,
1336 * extract the induction variable, i.e., the (integer)variable being
1339 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1346 lhs
= init
->getLHS();
1347 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1352 ref
= cast
<DeclRefExpr
>(lhs
);
1353 decl
= ref
->getDecl();
1354 type
= decl
->getType().getTypePtr();
1356 if (!type
->isIntegerType()) {
1364 /* Given the initialization statement of a for loop and the single
1365 * declaration in this initialization statement,
1366 * extract the induction variable, i.e., the (integer) variable being
1369 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1373 vd
= cast
<VarDecl
>(decl
);
1375 const QualType type
= vd
->getType();
1376 if (!type
->isIntegerType()) {
1381 if (!vd
->getInit()) {
1389 /* Check that op is of the form iv++ or iv--.
1390 * "inc" is accordingly set to 1 or -1.
1392 bool PetScan::check_unary_increment(UnaryOperator
*op
, clang::ValueDecl
*iv
,
1398 if (!op
->isIncrementDecrementOp()) {
1403 if (op
->isIncrementOp())
1404 isl_int_set_si(inc
, 1);
1406 isl_int_set_si(inc
, -1);
1408 sub
= op
->getSubExpr();
1409 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1414 ref
= cast
<DeclRefExpr
>(sub
);
1415 if (ref
->getDecl() != iv
) {
1423 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1424 * has a single constant expression on a universe domain, then
1425 * put this constant in *user.
1427 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
1430 isl_int
*inc
= (isl_int
*)user
;
1433 if (!isl_set_plain_is_universe(set
) || !isl_aff_is_cst(aff
))
1436 isl_aff_get_constant(aff
, inc
);
1444 /* Check if op is of the form
1448 * with inc a constant and set "inc" accordingly.
1450 * We extract an affine expression from the RHS and the subtract iv.
1451 * The result should be a constant.
1453 bool PetScan::check_binary_increment(BinaryOperator
*op
, clang::ValueDecl
*iv
,
1463 if (op
->getOpcode() != BO_Assign
) {
1469 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1474 ref
= cast
<DeclRefExpr
>(lhs
);
1475 if (ref
->getDecl() != iv
) {
1480 val
= extract_affine(op
->getRHS());
1482 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1484 dim
= isl_space_params_alloc(ctx
, 1);
1485 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1486 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1487 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1489 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
1491 if (isl_pw_aff_foreach_piece(val
, &extract_cst
, &inc
) < 0) {
1492 isl_pw_aff_free(val
);
1497 isl_pw_aff_free(val
);
1502 /* Check that op is of the form iv += cst or iv -= cst.
1503 * "inc" is set to cst or -cst accordingly.
1505 bool PetScan::check_compound_increment(CompoundAssignOperator
*op
,
1506 clang::ValueDecl
*iv
, isl_int
&inc
)
1512 BinaryOperatorKind opcode
;
1514 opcode
= op
->getOpcode();
1515 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1519 if (opcode
== BO_SubAssign
)
1523 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1528 ref
= cast
<DeclRefExpr
>(lhs
);
1529 if (ref
->getDecl() != iv
) {
1536 if (rhs
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1537 UnaryOperator
*op
= cast
<UnaryOperator
>(rhs
);
1538 if (op
->getOpcode() != UO_Minus
) {
1545 rhs
= op
->getSubExpr();
1548 if (rhs
->getStmtClass() != Stmt::IntegerLiteralClass
) {
1553 extract_int(cast
<IntegerLiteral
>(rhs
), &inc
);
1555 isl_int_neg(inc
, inc
);
1560 /* Check that the increment of the given for loop increments
1561 * (or decrements) the induction variable "iv".
1562 * "up" is set to true if the induction variable is incremented.
1564 bool PetScan::check_increment(ForStmt
*stmt
, ValueDecl
*iv
, isl_int
&v
)
1566 Stmt
*inc
= stmt
->getInc();
1573 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1574 return check_unary_increment(cast
<UnaryOperator
>(inc
), iv
, v
);
1575 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1576 return check_compound_increment(
1577 cast
<CompoundAssignOperator
>(inc
), iv
, v
);
1578 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1579 return check_binary_increment(cast
<BinaryOperator
>(inc
), iv
, v
);
1585 /* Embed the given iteration domain in an extra outer loop
1586 * with induction variable "var".
1587 * If this variable appeared as a parameter in the constraints,
1588 * it is replaced by the new outermost dimension.
1590 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1591 __isl_take isl_id
*var
)
1595 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1596 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1598 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1599 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1606 /* Construct a pet_scop for an infinite loop around the given body.
1608 * We extract a pet_scop for the body and then embed it in a loop with
1617 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
1623 struct pet_scop
*scop
;
1625 scop
= extract(body
);
1629 id
= isl_id_alloc(ctx
, "t", NULL
);
1630 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
1631 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
1632 dim
= isl_space_from_domain(isl_set_get_space(domain
));
1633 dim
= isl_space_add_dims(dim
, isl_dim_out
, 1);
1634 sched
= isl_map_universe(dim
);
1635 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
1636 scop
= pet_scop_embed(scop
, domain
, sched
, id
);
1641 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1647 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
1649 return extract_infinite_loop(stmt
->getBody());
1652 /* Check if the while loop is of the form
1657 * If so, construct a scop for an infinite loop around body.
1660 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
1666 cond
= stmt
->getCond();
1672 set
= extract_condition(cond
);
1673 is_universe
= isl_set_plain_is_universe(set
);
1681 return extract_infinite_loop(stmt
->getBody());
1684 /* Check whether "cond" expresses a simple loop bound
1685 * on the only set dimension.
1686 * In particular, if "up" is set then "cond" should contain only
1687 * upper bounds on the set dimension.
1688 * Otherwise, it should contain only lower bounds.
1690 static bool is_simple_bound(__isl_keep isl_set
*cond
, isl_int inc
)
1692 if (isl_int_is_pos(inc
))
1693 return !isl_set_dim_has_lower_bound(cond
, isl_dim_set
, 0);
1695 return !isl_set_dim_has_upper_bound(cond
, isl_dim_set
, 0);
1698 /* Extend a condition on a given iteration of a loop to one that
1699 * imposes the same condition on all previous iterations.
1700 * "domain" expresses the lower [upper] bound on the iterations
1701 * when inc is positive [negative].
1703 * In particular, we construct the condition (when inc is positive)
1705 * forall i' : (domain(i') and i' <= i) => cond(i')
1707 * which is equivalent to
1709 * not exists i' : domain(i') and i' <= i and not cond(i')
1711 * We construct this set by negating cond, applying a map
1713 * { [i'] -> [i] : domain(i') and i' <= i }
1715 * and then negating the result again.
1717 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
1718 __isl_take isl_set
*domain
, isl_int inc
)
1720 isl_map
*previous_to_this
;
1722 if (isl_int_is_pos(inc
))
1723 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
1725 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
1727 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
1729 cond
= isl_set_complement(cond
);
1730 cond
= isl_set_apply(cond
, previous_to_this
);
1731 cond
= isl_set_complement(cond
);
1736 /* Construct a domain of the form
1738 * [id] -> { [] : exists a: id = init + a * inc and a >= 0 }
1740 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
1741 __isl_take isl_pw_aff
*init
, isl_int inc
)
1747 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
1748 dim
= isl_pw_aff_get_domain_space(init
);
1749 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1750 aff
= isl_aff_add_coefficient(aff
, isl_dim_in
, 0, inc
);
1751 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
1753 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
1754 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1755 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1756 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1758 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
1760 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
1762 return isl_set_project_out(set
, isl_dim_set
, 0, 1);
1765 static unsigned get_type_size(ValueDecl
*decl
)
1767 return decl
->getASTContext().getIntWidth(decl
->getType());
1770 /* Assuming "cond" represents a simple bound on a loop where the loop
1771 * iterator "iv" is incremented (or decremented) by one, check if wrapping
1774 * Under the given assumptions, wrapping is only possible if "cond" allows
1775 * for the last value before wrapping, i.e., 2^width - 1 in case of an
1776 * increasing iterator and 0 in case of a decreasing iterator.
1778 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
, isl_int inc
)
1784 test
= isl_set_copy(cond
);
1786 isl_int_init(limit
);
1787 if (isl_int_is_neg(inc
))
1788 isl_int_set_si(limit
, 0);
1790 isl_int_set_si(limit
, 1);
1791 isl_int_mul_2exp(limit
, limit
, get_type_size(iv
));
1792 isl_int_sub_ui(limit
, limit
, 1);
1795 test
= isl_set_fix(cond
, isl_dim_set
, 0, limit
);
1796 cw
= !isl_set_is_empty(test
);
1799 isl_int_clear(limit
);
1804 /* Given a one-dimensional space, construct the following mapping on this
1807 * { [v] -> [v mod 2^width] }
1809 * where width is the number of bits used to represent the values
1810 * of the unsigned variable "iv".
1812 static __isl_give isl_map
*compute_wrapping(__isl_take isl_space
*dim
,
1820 isl_int_set_si(mod
, 1);
1821 isl_int_mul_2exp(mod
, mod
, get_type_size(iv
));
1823 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1824 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
1825 aff
= isl_aff_mod(aff
, mod
);
1829 return isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
1830 map
= isl_map_reverse(map
);
1833 /* Construct a pet_scop for a for statement.
1834 * The for loop is required to be of the form
1836 * for (i = init; condition; ++i)
1840 * for (i = init; condition; --i)
1842 * The initialization of the for loop should either be an assignment
1843 * to an integer variable, or a declaration of such a variable with
1846 * The condition is allowed to contain nested accesses, provided
1847 * they are not being written to inside the body of the loop.
1849 * We extract a pet_scop for the body and then embed it in a loop with
1850 * iteration domain and schedule
1852 * { [i] : i >= init and condition' }
1857 * { [i] : i <= init and condition' }
1860 * Where condition' is equal to condition if the latter is
1861 * a simple upper [lower] bound and a condition that is extended
1862 * to apply to all previous iterations otherwise.
1864 * If the stride of the loop is not 1, then "i >= init" is replaced by
1866 * (exists a: i = init + stride * a and a >= 0)
1868 * If the loop iterator i is unsigned, then wrapping may occur.
1869 * During the computation, we work with a virtual iterator that
1870 * does not wrap. However, the condition in the code applies
1871 * to the wrapped value, so we need to change condition(i)
1872 * into condition([i % 2^width]).
1873 * After computing the virtual domain and schedule, we apply
1874 * the function { [v] -> [v % 2^width] } to the domain and the domain
1875 * of the schedule. In order not to lose any information, we also
1876 * need to intersect the domain of the schedule with the virtual domain
1877 * first, since some iterations in the wrapped domain may be scheduled
1878 * several times, typically an infinite number of times.
1879 * Note that there is no need to perform this final wrapping
1880 * if the loop condition (after wrapping) is simple.
1882 * Wrapping on unsigned iterators can be avoided entirely if
1883 * loop condition is simple, the loop iterator is incremented
1884 * [decremented] by one and the last value before wrapping cannot
1885 * possibly satisfy the loop condition.
1887 * Before extracting a pet_scop from the body we remove all
1888 * assignments in assigned_value to variables that are assigned
1889 * somewhere in the body of the loop.
1891 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
1893 BinaryOperator
*ass
;
1901 isl_set
*cond
= NULL
;
1903 struct pet_scop
*scop
;
1904 assigned_value_cache
cache(assigned_value
);
1909 isl_map
*wrap
= NULL
;
1911 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
1912 return extract_infinite_for(stmt
);
1914 init
= stmt
->getInit();
1919 if ((ass
= initialization_assignment(init
)) != NULL
) {
1920 iv
= extract_induction_variable(ass
);
1923 lhs
= ass
->getLHS();
1924 rhs
= ass
->getRHS();
1925 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
1926 VarDecl
*var
= extract_induction_variable(init
, decl
);
1930 rhs
= var
->getInit();
1931 lhs
= DeclRefExpr::Create(iv
->getASTContext(),
1932 var
->getQualifierLoc(), iv
, var
->getInnerLocStart(),
1933 var
->getType(), VK_LValue
);
1935 unsupported(stmt
->getInit());
1940 if (!check_increment(stmt
, iv
, inc
)) {
1945 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
1947 assigned_value
.erase(iv
);
1948 clear_assignments
clear(assigned_value
);
1949 clear
.TraverseStmt(stmt
->getBody());
1951 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1953 is_one
= isl_int_is_one(inc
) || isl_int_is_negone(inc
);
1955 domain
= extract_comparison(isl_int_is_pos(inc
) ? BO_GE
: BO_LE
,
1958 isl_pw_aff
*lb
= extract_affine(rhs
);
1959 domain
= strided_domain(isl_id_copy(id
), lb
, inc
);
1962 scop
= extract(stmt
->getBody());
1964 cond
= try_extract_nested_condition(stmt
->getCond());
1965 if (cond
&& !is_nested_allowed(cond
, scop
)) {
1971 cond
= extract_condition(stmt
->getCond());
1972 cond
= embed(cond
, isl_id_copy(id
));
1973 domain
= embed(domain
, isl_id_copy(id
));
1974 is_simple
= is_simple_bound(cond
, inc
);
1976 (!is_simple
|| !is_one
|| can_wrap(cond
, iv
, inc
))) {
1977 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
1978 cond
= isl_set_apply(cond
, isl_map_reverse(isl_map_copy(wrap
)));
1979 is_simple
= is_simple
&& is_simple_bound(cond
, inc
);
1982 cond
= valid_for_each_iteration(cond
,
1983 isl_set_copy(domain
), inc
);
1984 domain
= isl_set_intersect(domain
, cond
);
1985 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
1986 dim
= isl_space_from_domain(isl_set_get_space(domain
));
1987 dim
= isl_space_add_dims(dim
, isl_dim_out
, 1);
1988 sched
= isl_map_universe(dim
);
1989 if (isl_int_is_pos(inc
))
1990 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
1992 sched
= isl_map_oppose(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
1994 if (is_unsigned
&& !is_simple
) {
1995 wrap
= isl_map_set_dim_id(wrap
,
1996 isl_dim_out
, 0, isl_id_copy(id
));
1997 sched
= isl_map_intersect_domain(sched
, isl_set_copy(domain
));
1998 domain
= isl_set_apply(domain
, isl_map_copy(wrap
));
1999 sched
= isl_map_apply_domain(sched
, wrap
);
2003 scop
= pet_scop_embed(scop
, domain
, sched
, id
);
2004 scop
= resolve_nested(scop
);
2005 assigned_value
[iv
] = NULL
;
2011 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
)
2013 return extract(stmt
->children());
2016 /* Does "id" refer to a nested access?
2018 static bool is_nested_parameter(__isl_keep isl_id
*id
)
2020 return id
&& isl_id_get_user(id
) && !isl_id_get_name(id
);
2023 /* Does parameter "pos" of "space" refer to a nested access?
2025 static bool is_nested_parameter(__isl_keep isl_space
*space
, int pos
)
2030 id
= isl_space_get_dim_id(space
, isl_dim_param
, pos
);
2031 nested
= is_nested_parameter(id
);
2037 /* Does parameter "pos" of "map" refer to a nested access?
2039 static bool is_nested_parameter(__isl_keep isl_map
*map
, int pos
)
2044 id
= isl_map_get_dim_id(map
, isl_dim_param
, pos
);
2045 nested
= is_nested_parameter(id
);
2051 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2053 static int n_nested_parameter(__isl_keep isl_space
*space
)
2058 nparam
= isl_space_dim(space
, isl_dim_param
);
2059 for (int i
= 0; i
< nparam
; ++i
)
2060 if (is_nested_parameter(space
, i
))
2066 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2068 static int n_nested_parameter(__isl_keep isl_map
*map
)
2073 space
= isl_map_get_space(map
);
2074 n
= n_nested_parameter(space
);
2075 isl_space_free(space
);
2080 /* For each nested access parameter in "space",
2081 * construct a corresponding pet_expr, place it in args and
2082 * record its position in "param2pos".
2083 * "n_arg" is the number of elements that are already in args.
2084 * The position recorded in "param2pos" takes this number into account.
2085 * If the pet_expr corresponding to a parameter is identical to
2086 * the pet_expr corresponding to an earlier parameter, then these two
2087 * parameters are made to refer to the same element in args.
2089 * Return the final number of elements in args or -1 if an error has occurred.
2091 int PetScan::extract_nested(__isl_keep isl_space
*space
,
2092 int n_arg
, struct pet_expr
**args
, std::map
<int,int> ¶m2pos
)
2096 nparam
= isl_space_dim(space
, isl_dim_param
);
2097 for (int i
= 0; i
< nparam
; ++i
) {
2099 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2102 if (!is_nested_parameter(id
)) {
2107 nested
= (Expr
*) isl_id_get_user(id
);
2108 args
[n_arg
] = extract_expr(nested
);
2112 for (j
= 0; j
< n_arg
; ++j
)
2113 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
2117 pet_expr_free(args
[n_arg
]);
2121 param2pos
[i
] = n_arg
++;
2129 /* For each nested access parameter in the access relations in "expr",
2130 * construct a corresponding pet_expr, place it in expr->args and
2131 * record its position in "param2pos".
2132 * n is the number of nested access parameters.
2134 struct pet_expr
*PetScan::extract_nested(struct pet_expr
*expr
, int n
,
2135 std::map
<int,int> ¶m2pos
)
2139 expr
->args
= isl_calloc_array(ctx
, struct pet_expr
*, n
);
2144 space
= isl_map_get_space(expr
->acc
.access
);
2145 n
= extract_nested(space
, 0, expr
->args
, param2pos
);
2146 isl_space_free(space
);
2154 pet_expr_free(expr
);
2158 /* Look for parameters in any access relation in "expr" that
2159 * refer to nested accesses. In particular, these are
2160 * parameters with no name.
2162 * If there are any such parameters, then the domain of the access
2163 * relation, which is still [] at this point, is replaced by
2164 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2165 * (after identifying identical nested accesses).
2166 * The parameters are then equated to the corresponding t dimensions
2167 * and subsequently projected out.
2168 * param2pos maps the position of the parameter to the position
2169 * of the corresponding t dimension.
2171 struct pet_expr
*PetScan::resolve_nested(struct pet_expr
*expr
)
2178 std::map
<int,int> param2pos
;
2183 for (int i
= 0; i
< expr
->n_arg
; ++i
) {
2184 expr
->args
[i
] = resolve_nested(expr
->args
[i
]);
2185 if (!expr
->args
[i
]) {
2186 pet_expr_free(expr
);
2191 if (expr
->type
!= pet_expr_access
)
2194 n
= n_nested_parameter(expr
->acc
.access
);
2198 expr
= extract_nested(expr
, n
, param2pos
);
2203 nparam
= isl_map_dim(expr
->acc
.access
, isl_dim_param
);
2204 n_in
= isl_map_dim(expr
->acc
.access
, isl_dim_in
);
2205 dim
= isl_map_get_space(expr
->acc
.access
);
2206 dim
= isl_space_domain(dim
);
2207 dim
= isl_space_from_domain(dim
);
2208 dim
= isl_space_add_dims(dim
, isl_dim_out
, n
);
2209 map
= isl_map_universe(dim
);
2210 map
= isl_map_domain_map(map
);
2211 map
= isl_map_reverse(map
);
2212 expr
->acc
.access
= isl_map_apply_domain(expr
->acc
.access
, map
);
2214 for (int i
= nparam
- 1; i
>= 0; --i
) {
2215 isl_id
*id
= isl_map_get_dim_id(expr
->acc
.access
,
2217 if (!is_nested_parameter(id
)) {
2222 expr
->acc
.access
= isl_map_equate(expr
->acc
.access
,
2223 isl_dim_param
, i
, isl_dim_in
,
2224 n_in
+ param2pos
[i
]);
2225 expr
->acc
.access
= isl_map_project_out(expr
->acc
.access
,
2226 isl_dim_param
, i
, 1);
2233 pet_expr_free(expr
);
2237 /* Convert a top-level pet_expr to a pet_scop with one statement.
2238 * This mainly involves resolving nested expression parameters
2239 * and setting the name of the iteration space.
2240 * The name is given by "label" if it is non-NULL. Otherwise,
2241 * it is of the form S_<n_stmt>.
2243 struct pet_scop
*PetScan::extract(Stmt
*stmt
, struct pet_expr
*expr
,
2244 __isl_take isl_id
*label
)
2246 struct pet_stmt
*ps
;
2247 SourceLocation loc
= stmt
->getLocStart();
2248 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
2250 expr
= resolve_nested(expr
);
2251 ps
= pet_stmt_from_pet_expr(ctx
, line
, label
, n_stmt
++, expr
);
2252 return pet_scop_from_pet_stmt(ctx
, ps
);
2255 /* Check whether "expr" is an affine expression.
2256 * We turn on autodetection so that we won't generate any warnings
2257 * and turn off nesting, so that we won't accept any non-affine constructs.
2259 bool PetScan::is_affine(Expr
*expr
)
2262 int save_autodetect
= autodetect
;
2263 bool save_nesting
= nesting_enabled
;
2266 nesting_enabled
= false;
2268 pwaff
= extract_affine(expr
);
2269 isl_pw_aff_free(pwaff
);
2271 autodetect
= save_autodetect
;
2272 nesting_enabled
= save_nesting
;
2274 return pwaff
!= NULL
;
2277 /* Check whether "expr" is an affine constraint.
2278 * We turn on autodetection so that we won't generate any warnings
2279 * and turn off nesting, so that we won't accept any non-affine constructs.
2281 bool PetScan::is_affine_condition(Expr
*expr
)
2284 int save_autodetect
= autodetect
;
2285 bool save_nesting
= nesting_enabled
;
2288 nesting_enabled
= false;
2290 set
= extract_condition(expr
);
2293 autodetect
= save_autodetect
;
2294 nesting_enabled
= save_nesting
;
2299 /* Check if we can extract a condition from "expr".
2300 * Return the condition as an isl_set if we can and NULL otherwise.
2301 * If allow_nested is set, then the condition may involve parameters
2302 * corresponding to nested accesses.
2303 * We turn on autodetection so that we won't generate any warnings.
2305 __isl_give isl_set
*PetScan::try_extract_nested_condition(Expr
*expr
)
2308 int save_autodetect
= autodetect
;
2309 bool save_nesting
= nesting_enabled
;
2312 nesting_enabled
= allow_nested
;
2313 set
= extract_condition(expr
);
2315 autodetect
= save_autodetect
;
2316 nesting_enabled
= save_nesting
;
2321 /* If the top-level expression of "stmt" is an assignment, then
2322 * return that assignment as a BinaryOperator.
2323 * Otherwise return NULL.
2325 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
2327 BinaryOperator
*ass
;
2331 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
2334 ass
= cast
<BinaryOperator
>(stmt
);
2335 if(ass
->getOpcode() != BO_Assign
)
2341 /* Check if the given if statement is a conditional assignement
2342 * with a non-affine condition. If so, construct a pet_scop
2343 * corresponding to this conditional assignment. Otherwise return NULL.
2345 * In particular we check if "stmt" is of the form
2352 * where a is some array or scalar access.
2353 * The constructed pet_scop then corresponds to the expression
2355 * a = condition ? f(...) : g(...)
2357 * All access relations in f(...) are intersected with condition
2358 * while all access relation in g(...) are intersected with the complement.
2360 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
2362 BinaryOperator
*ass_then
, *ass_else
;
2363 isl_map
*write_then
, *write_else
;
2364 isl_set
*cond
, *comp
;
2365 isl_map
*map
, *map_true
, *map_false
;
2367 struct pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
2368 bool save_nesting
= nesting_enabled
;
2370 ass_then
= top_assignment_or_null(stmt
->getThen());
2371 ass_else
= top_assignment_or_null(stmt
->getElse());
2373 if (!ass_then
|| !ass_else
)
2376 if (is_affine_condition(stmt
->getCond()))
2379 write_then
= extract_access(ass_then
->getLHS());
2380 write_else
= extract_access(ass_else
->getLHS());
2382 equal
= isl_map_is_equal(write_then
, write_else
);
2383 isl_map_free(write_else
);
2384 if (equal
< 0 || !equal
) {
2385 isl_map_free(write_then
);
2389 nesting_enabled
= allow_nested
;
2390 cond
= extract_condition(stmt
->getCond());
2391 nesting_enabled
= save_nesting
;
2392 comp
= isl_set_complement(isl_set_copy(cond
));
2393 map_true
= isl_map_from_domain(isl_set_from_params(isl_set_copy(cond
)));
2394 map_true
= isl_map_add_dims(map_true
, isl_dim_out
, 1);
2395 map_true
= isl_map_fix_si(map_true
, isl_dim_out
, 0, 1);
2396 map_false
= isl_map_from_domain(isl_set_from_params(isl_set_copy(comp
)));
2397 map_false
= isl_map_add_dims(map_false
, isl_dim_out
, 1);
2398 map_false
= isl_map_fix_si(map_false
, isl_dim_out
, 0, 0);
2399 map
= isl_map_union_disjoint(map_true
, map_false
);
2401 pe_cond
= pet_expr_from_access(map
);
2403 pe_then
= extract_expr(ass_then
->getRHS());
2404 pe_then
= pet_expr_restrict(pe_then
, cond
);
2405 pe_else
= extract_expr(ass_else
->getRHS());
2406 pe_else
= pet_expr_restrict(pe_else
, comp
);
2408 pe
= pet_expr_new_ternary(ctx
, pe_cond
, pe_then
, pe_else
);
2409 pe_write
= pet_expr_from_access(write_then
);
2411 pe_write
->acc
.write
= 1;
2412 pe_write
->acc
.read
= 0;
2414 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, pe_write
, pe
);
2415 return extract(stmt
, pe
);
2418 /* Create an access to a virtual array representing the result
2420 * Unlike other accessed data, the id of the array is NULL as
2421 * there is no ValueDecl in the program corresponding to the virtual
2423 * The array starts out as a scalar, but grows along with the
2424 * statement writing to the array in pet_scop_embed.
2426 static __isl_give isl_map
*create_test_access(isl_ctx
*ctx
, int test_nr
)
2428 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, 0);
2432 snprintf(name
, sizeof(name
), "__pet_test_%d", test_nr
);
2433 id
= isl_id_alloc(ctx
, name
, NULL
);
2434 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
2435 return isl_map_universe(dim
);
2438 /* Create a pet_scop with a single statement evaluating "cond"
2439 * and writing the result to a virtual scalar, as expressed by
2442 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
,
2443 __isl_take isl_map
*access
)
2445 struct pet_expr
*expr
, *write
;
2446 struct pet_stmt
*ps
;
2447 SourceLocation loc
= cond
->getLocStart();
2448 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
2450 write
= pet_expr_from_access(access
);
2452 write
->acc
.write
= 1;
2453 write
->acc
.read
= 0;
2455 expr
= extract_expr(cond
);
2456 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, write
, expr
);
2457 ps
= pet_stmt_from_pet_expr(ctx
, line
, NULL
, n_stmt
++, expr
);
2458 return pet_scop_from_pet_stmt(ctx
, ps
);
2461 /* Add an array with the given extend ("access") to the list
2462 * of arrays in "scop" and return the extended pet_scop.
2463 * The array is marked as attaining values 0 and 1 only.
2465 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2466 __isl_keep isl_map
*access
)
2468 isl_ctx
*ctx
= isl_map_get_ctx(access
);
2470 struct pet_array
**arrays
;
2471 struct pet_array
*array
;
2478 arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
2482 scop
->arrays
= arrays
;
2484 array
= isl_calloc_type(ctx
, struct pet_array
);
2488 array
->extent
= isl_map_range(isl_map_copy(access
));
2489 dim
= isl_space_params_alloc(ctx
, 0);
2490 array
->context
= isl_set_universe(dim
);
2491 dim
= isl_space_set_alloc(ctx
, 0, 1);
2492 array
->value_bounds
= isl_set_universe(dim
);
2493 array
->value_bounds
= isl_set_lower_bound_si(array
->value_bounds
,
2495 array
->value_bounds
= isl_set_upper_bound_si(array
->value_bounds
,
2497 array
->element_type
= strdup("int");
2499 scop
->arrays
[scop
->n_array
] = array
;
2502 if (!array
->extent
|| !array
->context
)
2507 pet_scop_free(scop
);
2512 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
,
2516 /* Apply the map pointed to by "user" to the domain of the access
2517 * relation, thereby embedding it in the range of the map.
2518 * The domain of both relations is the zero-dimensional domain.
2520 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
, void *user
)
2522 isl_map
*map
= (isl_map
*) user
;
2524 return isl_map_apply_domain(access
, isl_map_copy(map
));
2527 /* Apply "map" to all access relations in "expr".
2529 static struct pet_expr
*embed(struct pet_expr
*expr
, __isl_keep isl_map
*map
)
2531 return pet_expr_foreach_access(expr
, &embed_access
, map
);
2534 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2536 static int n_nested_parameter(__isl_keep isl_set
*set
)
2541 space
= isl_set_get_space(set
);
2542 n
= n_nested_parameter(space
);
2543 isl_space_free(space
);
2548 /* Remove all parameters from "map" that refer to nested accesses.
2550 static __isl_give isl_map
*remove_nested_parameters(__isl_take isl_map
*map
)
2555 space
= isl_map_get_space(map
);
2556 nparam
= isl_space_dim(space
, isl_dim_param
);
2557 for (int i
= nparam
- 1; i
>= 0; --i
)
2558 if (is_nested_parameter(space
, i
))
2559 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
2560 isl_space_free(space
);
2566 static __isl_give isl_map
*access_remove_nested_parameters(
2567 __isl_take isl_map
*access
, void *user
);
2570 static __isl_give isl_map
*access_remove_nested_parameters(
2571 __isl_take isl_map
*access
, void *user
)
2573 return remove_nested_parameters(access
);
2576 /* Remove all nested access parameters from the schedule and all
2577 * accesses of "stmt".
2578 * There is no need to remove them from the domain as these parameters
2579 * have already been removed from the domain when this function is called.
2581 static struct pet_stmt
*remove_nested_parameters(struct pet_stmt
*stmt
)
2585 stmt
->schedule
= remove_nested_parameters(stmt
->schedule
);
2586 stmt
->body
= pet_expr_foreach_access(stmt
->body
,
2587 &access_remove_nested_parameters
, NULL
);
2588 if (!stmt
->schedule
|| !stmt
->body
)
2590 for (int i
= 0; i
< stmt
->n_arg
; ++i
) {
2591 stmt
->args
[i
] = pet_expr_foreach_access(stmt
->args
[i
],
2592 &access_remove_nested_parameters
, NULL
);
2599 pet_stmt_free(stmt
);
2603 /* For each nested access parameter in the domain of "stmt",
2604 * construct a corresponding pet_expr, place it in stmt->args and
2605 * record its position in "param2pos".
2606 * n is the number of nested access parameters.
2608 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
2609 std::map
<int,int> ¶m2pos
)
2613 struct pet_expr
**args
;
2615 n_arg
= stmt
->n_arg
;
2616 args
= isl_realloc_array(ctx
, stmt
->args
, struct pet_expr
*, n_arg
+ n
);
2622 space
= isl_set_get_space(stmt
->domain
);
2623 n
= extract_nested(space
, n_arg
, stmt
->args
, param2pos
);
2624 isl_space_free(space
);
2632 pet_stmt_free(stmt
);
2636 /* Look for parameters in the iteration domain of "stmt" taht
2637 * refer to nested accesses. In particular, these are
2638 * parameters with no name.
2640 * If there are any such parameters, then as many extra variables
2641 * (after identifying identical nested accesses) are added to the
2642 * range of the map wrapped inside the domain.
2643 * If the original domain is not a wrapped map, then a new wrapped
2644 * map is created with zero output dimensions.
2645 * The parameters are then equated to the corresponding output dimensions
2646 * and subsequently projected out, from the iteration domain,
2647 * the schedule and the access relations.
2648 * For each of the output dimensions, a corresponding argument
2649 * expression is added. Initially they are created with
2650 * a zero-dimensional domain, so they have to be embedded
2651 * in the current iteration domain.
2652 * param2pos maps the position of the parameter to the position
2653 * of the corresponding output dimension in the wrapped map.
2655 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
2661 std::map
<int,int> param2pos
;
2666 n
= n_nested_parameter(stmt
->domain
);
2670 n_arg
= stmt
->n_arg
;
2671 stmt
= extract_nested(stmt
, n
, param2pos
);
2675 n
= stmt
->n_arg
- n_arg
;
2676 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
2677 if (isl_set_is_wrapping(stmt
->domain
))
2678 map
= isl_set_unwrap(stmt
->domain
);
2680 map
= isl_map_from_domain(stmt
->domain
);
2681 map
= isl_map_add_dims(map
, isl_dim_out
, n
);
2683 for (int i
= nparam
- 1; i
>= 0; --i
) {
2686 if (!is_nested_parameter(map
, i
))
2689 id
= isl_map_get_tuple_id(stmt
->args
[param2pos
[i
]]->acc
.access
,
2691 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
2692 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
2694 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
2697 stmt
->domain
= isl_map_wrap(map
);
2699 map
= isl_set_unwrap(isl_set_copy(stmt
->domain
));
2700 map
= isl_map_from_range(isl_map_domain(map
));
2701 for (int pos
= n_arg
; pos
< stmt
->n_arg
; ++pos
)
2702 stmt
->args
[pos
] = embed(stmt
->args
[pos
], map
);
2705 stmt
= remove_nested_parameters(stmt
);
2709 pet_stmt_free(stmt
);
2713 /* For each statement in "scop", move the parameters that correspond
2714 * to nested access into the ranges of the domains and create
2715 * corresponding argument expressions.
2717 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
2722 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
2723 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
2724 if (!scop
->stmts
[i
])
2730 pet_scop_free(scop
);
2734 /* Does "space" involve any parameters that refer to nested
2735 * accesses, i.e., parameters with no name?
2737 static bool has_nested(__isl_keep isl_space
*space
)
2741 nparam
= isl_space_dim(space
, isl_dim_param
);
2742 for (int i
= 0; i
< nparam
; ++i
)
2743 if (is_nested_parameter(space
, i
))
2749 /* Does "set" involve any parameters that refer to nested
2750 * accesses, i.e., parameters with no name?
2752 static bool has_nested(__isl_keep isl_set
*set
)
2757 space
= isl_set_get_space(set
);
2758 nested
= has_nested(space
);
2759 isl_space_free(space
);
2764 /* Given an access expression "expr", is the variable accessed by
2765 * "expr" assigned anywhere inside "scop"?
2767 static bool is_assigned(pet_expr
*expr
, pet_scop
*scop
)
2769 bool assigned
= false;
2772 id
= isl_map_get_tuple_id(expr
->acc
.access
, isl_dim_out
);
2773 assigned
= pet_scop_writes(scop
, id
);
2779 /* Are all nested access parameters in "set" allowed given "scop".
2780 * In particular, is none of them written by anywhere inside "scop".
2782 bool PetScan::is_nested_allowed(__isl_keep isl_set
*set
, pet_scop
*scop
)
2786 nparam
= isl_set_dim(set
, isl_dim_param
);
2787 for (int i
= 0; i
< nparam
; ++i
) {
2789 isl_id
*id
= isl_set_get_dim_id(set
, isl_dim_param
, i
);
2793 if (!is_nested_parameter(id
)) {
2798 nested
= (Expr
*) isl_id_get_user(id
);
2799 expr
= extract_expr(nested
);
2800 allowed
= expr
&& expr
->type
== pet_expr_access
&&
2801 !is_assigned(expr
, scop
);
2803 pet_expr_free(expr
);
2813 /* Construct a pet_scop for an if statement.
2815 * If the condition fits the pattern of a conditional assignment,
2816 * then it is handled by extract_conditional_assignment.
2817 * Otherwise, we do the following.
2819 * If the condition is affine, then the condition is added
2820 * to the iteration domains of the then branch, while the
2821 * opposite of the condition in added to the iteration domains
2822 * of the else branch, if any.
2823 * We allow the condition to be dynamic, i.e., to refer to
2824 * scalars or array elements that may be written to outside
2825 * of the given if statement. These nested accesses are then represented
2826 * as output dimensions in the wrapping iteration domain.
2827 * If it also written _inside_ the then or else branch, then
2828 * we treat the condition as non-affine.
2829 * As explained below, this will introduce an extra statement.
2830 * For aesthetic reasons, we want this statement to have a statement
2831 * number that is lower than those of the then and else branches.
2832 * In order to evaluate if will need such a statement, however, we
2833 * first construct scops for the then and else branches.
2834 * We therefore reserve a statement number if we might have to
2835 * introduce such an extra statement.
2837 * If the condition is not affine, then we create a separate
2838 * statement that write the result of the condition to a virtual scalar.
2839 * A constraint requiring the value of this virtual scalar to be one
2840 * is added to the iteration domains of the then branch.
2841 * Similarly, a constraint requiring the value of this virtual scalar
2842 * to be zero is added to the iteration domains of the else branch, if any.
2843 * We adjust the schedules to ensure that the virtual scalar is written
2844 * before it is read.
2846 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
2848 struct pet_scop
*scop_then
, *scop_else
, *scop
;
2849 assigned_value_cache
cache(assigned_value
);
2850 isl_map
*test_access
= NULL
;
2854 scop
= extract_conditional_assignment(stmt
);
2858 cond
= try_extract_nested_condition(stmt
->getCond());
2859 if (allow_nested
&& (!cond
|| has_nested(cond
)))
2862 scop_then
= extract(stmt
->getThen());
2864 if (stmt
->getElse()) {
2865 scop_else
= extract(stmt
->getElse());
2867 if (scop_then
&& !scop_else
) {
2872 if (!scop_then
&& scop_else
) {
2881 (!is_nested_allowed(cond
, scop_then
) ||
2882 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
2886 if (allow_nested
&& !cond
) {
2887 int save_n_stmt
= n_stmt
;
2888 test_access
= create_test_access(ctx
, n_test
++);
2890 scop
= extract_non_affine_condition(stmt
->getCond(),
2891 isl_map_copy(test_access
));
2892 n_stmt
= save_n_stmt
;
2893 scop
= scop_add_array(scop
, test_access
);
2895 pet_scop_free(scop_then
);
2896 pet_scop_free(scop_else
);
2897 isl_map_free(test_access
);
2904 cond
= extract_condition(stmt
->getCond());
2905 scop
= pet_scop_restrict(scop_then
, isl_set_copy(cond
));
2907 if (stmt
->getElse()) {
2908 cond
= isl_set_complement(cond
);
2909 scop_else
= pet_scop_restrict(scop_else
, cond
);
2910 scop
= pet_scop_add(ctx
, scop
, scop_else
);
2913 scop
= resolve_nested(scop
);
2915 scop
= pet_scop_prefix(scop
, 0);
2916 scop_then
= pet_scop_prefix(scop_then
, 1);
2917 scop_then
= pet_scop_filter(scop_then
,
2918 isl_map_copy(test_access
), 1);
2919 scop
= pet_scop_add(ctx
, scop
, scop_then
);
2920 if (stmt
->getElse()) {
2921 scop_else
= pet_scop_prefix(scop_else
, 1);
2922 scop_else
= pet_scop_filter(scop_else
, test_access
, 0);
2923 scop
= pet_scop_add(ctx
, scop
, scop_else
);
2925 isl_map_free(test_access
);
2931 /* Try and construct a pet_scop for a label statement.
2932 * We currently only allow labels on expression statements.
2934 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
2939 sub
= stmt
->getSubStmt();
2940 if (!isa
<Expr
>(sub
)) {
2945 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
2947 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
2950 /* Try and construct a pet_scop corresponding to "stmt".
2952 struct pet_scop
*PetScan::extract(Stmt
*stmt
)
2954 if (isa
<Expr
>(stmt
))
2955 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
2957 switch (stmt
->getStmtClass()) {
2958 case Stmt::WhileStmtClass
:
2959 return extract(cast
<WhileStmt
>(stmt
));
2960 case Stmt::ForStmtClass
:
2961 return extract_for(cast
<ForStmt
>(stmt
));
2962 case Stmt::IfStmtClass
:
2963 return extract(cast
<IfStmt
>(stmt
));
2964 case Stmt::CompoundStmtClass
:
2965 return extract(cast
<CompoundStmt
>(stmt
));
2966 case Stmt::LabelStmtClass
:
2967 return extract(cast
<LabelStmt
>(stmt
));
2975 /* Try and construct a pet_scop corresponding to (part of)
2976 * a sequence of statements.
2978 struct pet_scop
*PetScan::extract(StmtRange stmt_range
)
2983 bool partial_range
= false;
2985 scop
= pet_scop_empty(ctx
);
2986 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
2988 struct pet_scop
*scop_i
;
2989 scop_i
= extract(child
);
2990 if (scop
&& partial
) {
2991 pet_scop_free(scop_i
);
2994 scop_i
= pet_scop_prefix(scop_i
, j
);
2997 scop
= pet_scop_add(ctx
, scop
, scop_i
);
2999 partial_range
= true;
3000 if (scop
->n_stmt
!= 0 && !scop_i
)
3003 scop
= pet_scop_add(ctx
, scop
, scop_i
);
3009 if (scop
&& partial_range
)
3015 /* Check if the scop marked by the user is exactly this Stmt
3016 * or part of this Stmt.
3017 * If so, return a pet_scop corresponding to the marked region.
3018 * Otherwise, return NULL.
3020 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
3022 SourceManager
&SM
= PP
.getSourceManager();
3023 unsigned start_off
, end_off
;
3025 start_off
= SM
.getFileOffset(stmt
->getLocStart());
3026 end_off
= SM
.getFileOffset(stmt
->getLocEnd());
3028 if (start_off
> loc
.end
)
3030 if (end_off
< loc
.start
)
3032 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
3033 return extract(stmt
);
3037 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
3038 Stmt
*child
= *start
;
3041 start_off
= SM
.getFileOffset(child
->getLocStart());
3042 end_off
= SM
.getFileOffset(child
->getLocEnd());
3043 if (start_off
< loc
.start
&& end_off
> loc
.end
)
3045 if (start_off
>= loc
.start
)
3050 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
3052 start_off
= SM
.getFileOffset(child
->getLocStart());
3053 if (start_off
>= loc
.end
)
3057 return extract(StmtRange(start
, end
));
3060 /* Set the size of index "pos" of "array" to "size".
3061 * In particular, add a constraint of the form
3065 * to array->extent and a constraint of the form
3069 * to array->context.
3071 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
3072 __isl_take isl_pw_aff
*size
)
3082 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
3083 array
->context
= isl_set_intersect(array
->context
, valid
);
3085 dim
= isl_set_get_space(array
->extent
);
3086 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
3087 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
3088 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
3089 index
= isl_pw_aff_alloc(univ
, aff
);
3091 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
3092 isl_set_dim(array
->extent
, isl_dim_set
));
3093 id
= isl_set_get_tuple_id(array
->extent
);
3094 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
3095 bound
= isl_pw_aff_lt_set(index
, size
);
3097 array
->extent
= isl_set_intersect(array
->extent
, bound
);
3099 if (!array
->context
|| !array
->extent
)
3104 pet_array_free(array
);
3108 /* Figure out the size of the array at position "pos" and all
3109 * subsequent positions from "type" and update "array" accordingly.
3111 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
3112 const Type
*type
, int pos
)
3114 const ArrayType
*atype
;
3120 if (type
->isPointerType()) {
3121 type
= type
->getPointeeType().getTypePtr();
3122 return set_upper_bounds(array
, type
, pos
+ 1);
3124 if (!type
->isArrayType())
3127 type
= type
->getCanonicalTypeInternal().getTypePtr();
3128 atype
= cast
<ArrayType
>(type
);
3130 if (type
->isConstantArrayType()) {
3131 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
3132 size
= extract_affine(ca
->getSize());
3133 array
= update_size(array
, pos
, size
);
3134 } else if (type
->isVariableArrayType()) {
3135 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
3136 size
= extract_affine(vla
->getSizeExpr());
3137 array
= update_size(array
, pos
, size
);
3140 type
= atype
->getElementType().getTypePtr();
3142 return set_upper_bounds(array
, type
, pos
+ 1);
3145 /* Construct and return a pet_array corresponding to the variable "decl".
3146 * In particular, initialize array->extent to
3148 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3150 * and then call set_upper_bounds to set the upper bounds on the indices
3151 * based on the type of the variable.
3153 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
)
3155 struct pet_array
*array
;
3156 QualType qt
= decl
->getType();
3157 const Type
*type
= qt
.getTypePtr();
3158 int depth
= array_depth(type
);
3159 QualType base
= base_type(qt
);
3164 array
= isl_calloc_type(ctx
, struct pet_array
);
3168 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
3169 dim
= isl_space_set_alloc(ctx
, 0, depth
);
3170 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
3172 array
->extent
= isl_set_nat_universe(dim
);
3174 dim
= isl_space_params_alloc(ctx
, 0);
3175 array
->context
= isl_set_universe(dim
);
3177 array
= set_upper_bounds(array
, type
, 0);
3181 name
= base
.getAsString();
3182 array
->element_type
= strdup(name
.c_str());
3187 /* Construct a list of pet_arrays, one for each array (or scalar)
3188 * accessed inside "scop" add this list to "scop" and return the result.
3190 * The context of "scop" is updated with the intesection of
3191 * the contexts of all arrays, i.e., constraints on the parameters
3192 * that ensure that the arrays have a valid (non-negative) size.
3194 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
3197 set
<ValueDecl
*> arrays
;
3198 set
<ValueDecl
*>::iterator it
;
3200 struct pet_array
**scop_arrays
;
3205 pet_scop_collect_arrays(scop
, arrays
);
3206 if (arrays
.size() == 0)
3209 n_array
= scop
->n_array
;
3211 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
3212 n_array
+ arrays
.size());
3215 scop
->arrays
= scop_arrays
;
3217 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
3218 struct pet_array
*array
;
3219 scop
->arrays
[n_array
+ i
] = array
= extract_array(ctx
, *it
);
3220 if (!scop
->arrays
[n_array
+ i
])
3223 scop
->context
= isl_set_intersect(scop
->context
,
3224 isl_set_copy(array
->context
));
3231 pet_scop_free(scop
);
3235 /* Construct a pet_scop from the given function.
3237 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
3242 stmt
= fd
->getBody();
3245 scop
= extract(stmt
);
3248 scop
= pet_scop_detect_parameter_accesses(scop
);
3249 scop
= scan_arrays(scop
);