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
;
55 #ifdef DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION
56 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
58 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
59 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
63 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
65 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
66 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
70 /* Check if the element type corresponding to the given array type
71 * has a const qualifier.
73 static bool const_base(QualType qt
)
75 const Type
*type
= qt
.getTypePtr();
77 if (type
->isPointerType())
78 return const_base(type
->getPointeeType());
79 if (type
->isArrayType()) {
80 const ArrayType
*atype
;
81 type
= type
->getCanonicalTypeInternal().getTypePtr();
82 atype
= cast
<ArrayType
>(type
);
83 return const_base(atype
->getElementType());
86 return qt
.isConstQualified();
89 /* Mark "decl" as having an unknown value in "assigned_value".
91 * If no (known or unknown) value was assigned to "decl" before,
92 * then it may have been treated as a parameter before and may
93 * therefore appear in a value assigned to another variable.
94 * If so, this assignment needs to be turned into an unknown value too.
96 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
99 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
101 it
= assigned_value
.find(decl
);
103 assigned_value
[decl
] = NULL
;
105 if (it
== assigned_value
.end())
108 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
109 isl_pw_aff
*pa
= it
->second
;
110 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
112 for (int i
= 0; i
< nparam
; ++i
) {
115 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
117 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
118 if (isl_id_get_user(id
) == decl
)
125 /* Look for any assignments to scalar variables in part of the parse
126 * tree and set assigned_value to NULL for each of them.
127 * Also reset assigned_value if the address of a scalar variable
128 * is being taken. As an exception, if the address is passed to a function
129 * that is declared to receive a const pointer, then assigned_value is
132 * This ensures that we won't use any previously stored value
133 * in the current subtree and its parents.
135 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
136 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
137 set
<UnaryOperator
*> skip
;
139 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
140 assigned_value(assigned_value
) {}
142 /* Check for "address of" operators whose value is passed
143 * to a const pointer argument and add them to "skip", so that
144 * we can skip them in VisitUnaryOperator.
146 bool VisitCallExpr(CallExpr
*expr
) {
148 fd
= expr
->getDirectCallee();
151 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
152 Expr
*arg
= expr
->getArg(i
);
154 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
155 ImplicitCastExpr
*ice
;
156 ice
= cast
<ImplicitCastExpr
>(arg
);
157 arg
= ice
->getSubExpr();
159 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
161 op
= cast
<UnaryOperator
>(arg
);
162 if (op
->getOpcode() != UO_AddrOf
)
164 if (const_base(fd
->getParamDecl(i
)->getType()))
170 bool VisitUnaryOperator(UnaryOperator
*expr
) {
175 if (expr
->getOpcode() != UO_AddrOf
)
177 if (skip
.find(expr
) != skip
.end())
180 arg
= expr
->getSubExpr();
181 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
183 ref
= cast
<DeclRefExpr
>(arg
);
184 decl
= ref
->getDecl();
185 clear_assignment(assigned_value
, decl
);
189 bool VisitBinaryOperator(BinaryOperator
*expr
) {
194 if (!expr
->isAssignmentOp())
196 lhs
= expr
->getLHS();
197 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
199 ref
= cast
<DeclRefExpr
>(lhs
);
200 decl
= ref
->getDecl();
201 clear_assignment(assigned_value
, decl
);
206 /* Keep a copy of the currently assigned values.
208 * Any variable that is assigned a value inside the current scope
209 * is removed again when we leave the scope (either because it wasn't
210 * stored in the cache or because it has a different value in the cache).
212 struct assigned_value_cache
{
213 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
214 map
<ValueDecl
*, isl_pw_aff
*> cache
;
216 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
217 assigned_value(assigned_value
), cache(assigned_value
) {}
218 ~assigned_value_cache() {
219 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
220 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
223 (cache
.find(it
->first
) != cache
.end() &&
224 cache
[it
->first
] != it
->second
))
225 cache
[it
->first
] = NULL
;
227 assigned_value
= cache
;
231 /* Insert an expression into the collection of expressions,
232 * provided it is not already in there.
233 * The isl_pw_affs are freed in the destructor.
235 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
237 std::set
<isl_pw_aff
*>::iterator it
;
239 if (expressions
.find(expr
) == expressions
.end())
240 expressions
.insert(expr
);
242 isl_pw_aff_free(expr
);
247 std::set
<isl_pw_aff
*>::iterator it
;
249 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
250 isl_pw_aff_free(*it
);
252 isl_union_map_free(value_bounds
);
255 /* Called if we found something we (currently) cannot handle.
256 * We'll provide more informative warnings later.
258 * We only actually complain if autodetect is false.
260 void PetScan::unsupported(Stmt
*stmt
, const char *msg
)
265 SourceLocation loc
= stmt
->getLocStart();
266 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
267 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
268 msg
? msg
: "unsupported");
269 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
272 /* Extract an integer from "expr" and store it in "v".
274 int PetScan::extract_int(IntegerLiteral
*expr
, isl_int
*v
)
276 const Type
*type
= expr
->getType().getTypePtr();
277 int is_signed
= type
->hasSignedIntegerRepresentation();
280 int64_t i
= expr
->getValue().getSExtValue();
281 isl_int_set_si(*v
, i
);
283 uint64_t i
= expr
->getValue().getZExtValue();
284 isl_int_set_ui(*v
, i
);
290 /* Extract an integer from "expr" and store it in "v".
291 * Return -1 if "expr" does not (obviously) represent an integer.
293 int PetScan::extract_int(clang::ParenExpr
*expr
, isl_int
*v
)
295 return extract_int(expr
->getSubExpr(), v
);
298 /* Extract an integer from "expr" and store it in "v".
299 * Return -1 if "expr" does not (obviously) represent an integer.
301 int PetScan::extract_int(clang::Expr
*expr
, isl_int
*v
)
303 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
304 return extract_int(cast
<IntegerLiteral
>(expr
), v
);
305 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
306 return extract_int(cast
<ParenExpr
>(expr
), v
);
312 /* Extract an affine expression from the IntegerLiteral "expr".
314 __isl_give isl_pw_aff
*PetScan::extract_affine(IntegerLiteral
*expr
)
316 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
317 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
318 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
319 isl_set
*dom
= isl_set_universe(dim
);
323 extract_int(expr
, &v
);
324 aff
= isl_aff_add_constant(aff
, v
);
327 return isl_pw_aff_alloc(dom
, aff
);
330 /* Extract an affine expression from the APInt "val".
332 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
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
);
341 isl_int_set_ui(v
, val
.getZExtValue());
342 aff
= isl_aff_add_constant(aff
, v
);
345 return isl_pw_aff_alloc(dom
, aff
);
348 __isl_give isl_pw_aff
*PetScan::extract_affine(ImplicitCastExpr
*expr
)
350 return extract_affine(expr
->getSubExpr());
353 /* Extract an affine expression from the DeclRefExpr "expr".
355 * If the variable has been assigned a value, then we check whether
356 * we know what (affine) value was assigned.
357 * If so, we return this value. Otherwise we convert "expr"
358 * to an extra parameter (provided nesting_enabled is set).
360 * Otherwise, we simply return an expression that is equal
361 * to a parameter corresponding to the referenced variable.
363 __isl_give isl_pw_aff
*PetScan::extract_affine(DeclRefExpr
*expr
)
365 ValueDecl
*decl
= expr
->getDecl();
366 const Type
*type
= decl
->getType().getTypePtr();
372 if (!type
->isIntegerType()) {
377 if (assigned_value
.find(decl
) != assigned_value
.end()) {
378 if (assigned_value
[decl
])
379 return isl_pw_aff_copy(assigned_value
[decl
]);
381 return nested_access(expr
);
384 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
385 dim
= isl_space_params_alloc(ctx
, 1);
387 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
389 dom
= isl_set_universe(isl_space_copy(dim
));
390 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
391 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
393 return isl_pw_aff_alloc(dom
, aff
);
396 /* Extract an affine expression from an integer division operation.
397 * In particular, if "expr" is lhs/rhs, then return
399 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
401 * The second argument (rhs) is required to be a (positive) integer constant.
403 __isl_give isl_pw_aff
*PetScan::extract_affine_div(BinaryOperator
*expr
)
406 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
411 rhs_expr
= expr
->getRHS();
413 if (extract_int(rhs_expr
, &v
) < 0) {
418 lhs
= extract_affine(expr
->getLHS());
419 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
421 lhs
= isl_pw_aff_scale_down(lhs
, v
);
424 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(lhs
));
425 lhs_c
= isl_pw_aff_ceil(lhs
);
426 res
= isl_pw_aff_cond(isl_set_indicator_function(cond
), lhs_f
, lhs_c
);
431 /* Extract an affine expression from a modulo operation.
432 * In particular, if "expr" is lhs/rhs, then return
434 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
436 * The second argument (rhs) is required to be a (positive) integer constant.
438 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
441 isl_pw_aff
*lhs
, *lhs_f
, *lhs_c
;
446 rhs_expr
= expr
->getRHS();
447 if (rhs_expr
->getStmtClass() != Stmt::IntegerLiteralClass
) {
452 lhs
= extract_affine(expr
->getLHS());
453 cond
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs
));
456 extract_int(cast
<IntegerLiteral
>(rhs_expr
), &v
);
457 res
= isl_pw_aff_scale_down(isl_pw_aff_copy(lhs
), v
);
459 lhs_f
= isl_pw_aff_floor(isl_pw_aff_copy(res
));
460 lhs_c
= isl_pw_aff_ceil(res
);
461 res
= isl_pw_aff_cond(isl_set_indicator_function(cond
), lhs_f
, lhs_c
);
463 res
= isl_pw_aff_scale(res
, v
);
466 res
= isl_pw_aff_sub(lhs
, res
);
471 /* Extract an affine expression from a multiplication operation.
472 * This is only allowed if at least one of the two arguments
473 * is a (piecewise) constant.
475 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
480 lhs
= extract_affine(expr
->getLHS());
481 rhs
= extract_affine(expr
->getRHS());
483 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
484 isl_pw_aff_free(lhs
);
485 isl_pw_aff_free(rhs
);
490 return isl_pw_aff_mul(lhs
, rhs
);
493 /* Extract an affine expression from an addition or subtraction operation.
495 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
500 lhs
= extract_affine(expr
->getLHS());
501 rhs
= extract_affine(expr
->getRHS());
503 switch (expr
->getOpcode()) {
505 return isl_pw_aff_add(lhs
, rhs
);
507 return isl_pw_aff_sub(lhs
, rhs
);
509 isl_pw_aff_free(lhs
);
510 isl_pw_aff_free(rhs
);
520 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
526 isl_int_set_si(mod
, 1);
527 isl_int_mul_2exp(mod
, mod
, width
);
529 pwaff
= isl_pw_aff_mod(pwaff
, mod
);
536 /* Extract an affine expression from a boolean expression.
537 * In particular, return the expression "expr ? 1 : 0".
539 __isl_give isl_pw_aff
*PetScan::extract_implicit_affine(Expr
*expr
)
541 isl_set
*cond
= extract_condition(expr
);
542 return isl_set_indicator_function(cond
);
545 /* Extract an affine expression from some binary operations.
546 * If the result of the expression is unsigned, then we wrap it
547 * based on the size of the type.
549 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
553 switch (expr
->getOpcode()) {
556 res
= extract_affine_add(expr
);
559 res
= extract_affine_div(expr
);
562 res
= extract_affine_mod(expr
);
565 res
= extract_affine_mul(expr
);
575 res
= extract_implicit_affine(expr
);
582 if (expr
->getType()->isUnsignedIntegerType())
583 res
= wrap(res
, ast_context
.getIntWidth(expr
->getType()));
588 /* Extract an affine expression from a negation operation.
590 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
592 if (expr
->getOpcode() == UO_Minus
)
593 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
594 if (expr
->getOpcode() == UO_LNot
)
595 return extract_implicit_affine(expr
);
601 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
603 return extract_affine(expr
->getSubExpr());
606 /* Extract an affine expression from some special function calls.
607 * In particular, we handle "min", "max", "ceild" and "floord".
608 * In case of the latter two, the second argument needs to be
609 * a (positive) integer constant.
611 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
615 isl_pw_aff
*aff1
, *aff2
;
617 fd
= expr
->getDirectCallee();
623 name
= fd
->getDeclName().getAsString();
624 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
625 !(expr
->getNumArgs() == 2 && name
== "max") &&
626 !(expr
->getNumArgs() == 2 && name
== "floord") &&
627 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
632 if (name
== "min" || name
== "max") {
633 aff1
= extract_affine(expr
->getArg(0));
634 aff2
= extract_affine(expr
->getArg(1));
637 aff1
= isl_pw_aff_min(aff1
, aff2
);
639 aff1
= isl_pw_aff_max(aff1
, aff2
);
640 } else if (name
== "floord" || name
== "ceild") {
642 Expr
*arg2
= expr
->getArg(1);
644 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
648 aff1
= extract_affine(expr
->getArg(0));
650 extract_int(cast
<IntegerLiteral
>(arg2
), &v
);
651 aff1
= isl_pw_aff_scale_down(aff1
, v
);
653 if (name
== "floord")
654 aff1
= isl_pw_aff_floor(aff1
);
656 aff1
= isl_pw_aff_ceil(aff1
);
666 /* This method is called when we come across an access that is
667 * nested in what is supposed to be an affine expression.
668 * If nesting is allowed, we return a new parameter that corresponds
669 * to this nested access. Otherwise, we simply complain.
671 * The new parameter is resolved in resolve_nested.
673 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
680 if (!nesting_enabled
) {
685 id
= isl_id_alloc(ctx
, NULL
, expr
);
686 dim
= isl_space_params_alloc(ctx
, 1);
688 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
690 dom
= isl_set_universe(isl_space_copy(dim
));
691 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
692 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
694 return isl_pw_aff_alloc(dom
, aff
);
697 /* Affine expressions are not supposed to contain array accesses,
698 * but if nesting is allowed, we return a parameter corresponding
699 * to the array access.
701 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
703 return nested_access(expr
);
706 /* Extract an affine expression from a conditional operation.
708 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
711 isl_pw_aff
*lhs
, *rhs
;
713 cond
= extract_condition(expr
->getCond());
714 lhs
= extract_affine(expr
->getTrueExpr());
715 rhs
= extract_affine(expr
->getFalseExpr());
717 return isl_pw_aff_cond(isl_set_indicator_function(cond
), lhs
, rhs
);
720 /* Extract an affine expression, if possible, from "expr".
721 * Otherwise return NULL.
723 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
725 switch (expr
->getStmtClass()) {
726 case Stmt::ImplicitCastExprClass
:
727 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
728 case Stmt::IntegerLiteralClass
:
729 return extract_affine(cast
<IntegerLiteral
>(expr
));
730 case Stmt::DeclRefExprClass
:
731 return extract_affine(cast
<DeclRefExpr
>(expr
));
732 case Stmt::BinaryOperatorClass
:
733 return extract_affine(cast
<BinaryOperator
>(expr
));
734 case Stmt::UnaryOperatorClass
:
735 return extract_affine(cast
<UnaryOperator
>(expr
));
736 case Stmt::ParenExprClass
:
737 return extract_affine(cast
<ParenExpr
>(expr
));
738 case Stmt::CallExprClass
:
739 return extract_affine(cast
<CallExpr
>(expr
));
740 case Stmt::ArraySubscriptExprClass
:
741 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
742 case Stmt::ConditionalOperatorClass
:
743 return extract_affine(cast
<ConditionalOperator
>(expr
));
750 __isl_give isl_map
*PetScan::extract_access(ImplicitCastExpr
*expr
)
752 return extract_access(expr
->getSubExpr());
755 /* Return the depth of an array of the given type.
757 static int array_depth(const Type
*type
)
759 if (type
->isPointerType())
760 return 1 + array_depth(type
->getPointeeType().getTypePtr());
761 if (type
->isArrayType()) {
762 const ArrayType
*atype
;
763 type
= type
->getCanonicalTypeInternal().getTypePtr();
764 atype
= cast
<ArrayType
>(type
);
765 return 1 + array_depth(atype
->getElementType().getTypePtr());
770 /* Return the element type of the given array type.
772 static QualType
base_type(QualType qt
)
774 const Type
*type
= qt
.getTypePtr();
776 if (type
->isPointerType())
777 return base_type(type
->getPointeeType());
778 if (type
->isArrayType()) {
779 const ArrayType
*atype
;
780 type
= type
->getCanonicalTypeInternal().getTypePtr();
781 atype
= cast
<ArrayType
>(type
);
782 return base_type(atype
->getElementType());
787 /* Extract an access relation from a reference to a variable.
788 * If the variable has name "A" and its type corresponds to an
789 * array of depth d, then the returned access relation is of the
792 * { [] -> A[i_1,...,i_d] }
794 __isl_give isl_map
*PetScan::extract_access(DeclRefExpr
*expr
)
796 ValueDecl
*decl
= expr
->getDecl();
797 int depth
= array_depth(decl
->getType().getTypePtr());
798 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
799 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, depth
);
802 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
804 access_rel
= isl_map_universe(dim
);
809 /* Extract an access relation from an integer contant.
810 * If the value of the constant is "v", then the returned access relation
815 __isl_give isl_map
*PetScan::extract_access(IntegerLiteral
*expr
)
817 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr
)));
820 /* Try and extract an access relation from the given Expr.
821 * Return NULL if it doesn't work out.
823 __isl_give isl_map
*PetScan::extract_access(Expr
*expr
)
825 switch (expr
->getStmtClass()) {
826 case Stmt::ImplicitCastExprClass
:
827 return extract_access(cast
<ImplicitCastExpr
>(expr
));
828 case Stmt::DeclRefExprClass
:
829 return extract_access(cast
<DeclRefExpr
>(expr
));
830 case Stmt::ArraySubscriptExprClass
:
831 return extract_access(cast
<ArraySubscriptExpr
>(expr
));
838 /* Assign the affine expression "index" to the output dimension "pos" of "map"
839 * and return the result.
841 __isl_give isl_map
*set_index(__isl_take isl_map
*map
, int pos
,
842 __isl_take isl_pw_aff
*index
)
845 int len
= isl_map_dim(map
, isl_dim_out
);
848 index_map
= isl_map_from_range(isl_set_from_pw_aff(index
));
849 index_map
= isl_map_insert_dims(index_map
, isl_dim_out
, 0, pos
);
850 index_map
= isl_map_add_dims(index_map
, isl_dim_out
, len
- pos
- 1);
851 id
= isl_map_get_tuple_id(map
, isl_dim_out
);
852 index_map
= isl_map_set_tuple_id(index_map
, isl_dim_out
, id
);
854 map
= isl_map_intersect(map
, index_map
);
859 /* Extract an access relation from the given array subscript expression.
860 * If nesting is allowed in general, then we turn it on while
861 * examining the index expression.
863 * We first extract an access relation from the base.
864 * This will result in an access relation with a range that corresponds
865 * to the array being accessed and with earlier indices filled in already.
866 * We then extract the current index and fill that in as well.
867 * The position of the current index is based on the type of base.
868 * If base is the actual array variable, then the depth of this type
869 * will be the same as the depth of the array and we will fill in
870 * the first array index.
871 * Otherwise, the depth of the base type will be smaller and we will fill
874 __isl_give isl_map
*PetScan::extract_access(ArraySubscriptExpr
*expr
)
876 Expr
*base
= expr
->getBase();
877 Expr
*idx
= expr
->getIdx();
879 isl_map
*base_access
;
881 int depth
= array_depth(base
->getType().getTypePtr());
883 bool save_nesting
= nesting_enabled
;
885 nesting_enabled
= allow_nested
;
887 base_access
= extract_access(base
);
888 index
= extract_affine(idx
);
890 nesting_enabled
= save_nesting
;
892 pos
= isl_map_dim(base_access
, isl_dim_out
) - depth
;
893 access
= set_index(base_access
, pos
, index
);
898 /* Check if "expr" calls function "minmax" with two arguments and if so
899 * make lhs and rhs refer to these two arguments.
901 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
907 if (expr
->getStmtClass() != Stmt::CallExprClass
)
910 call
= cast
<CallExpr
>(expr
);
911 fd
= call
->getDirectCallee();
915 if (call
->getNumArgs() != 2)
918 name
= fd
->getDeclName().getAsString();
922 lhs
= call
->getArg(0);
923 rhs
= call
->getArg(1);
928 /* Check if "expr" is of the form min(lhs, rhs) and if so make
929 * lhs and rhs refer to the two arguments.
931 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
933 return is_minmax(expr
, "min", lhs
, rhs
);
936 /* Check if "expr" is of the form max(lhs, rhs) and if so make
937 * lhs and rhs refer to the two arguments.
939 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
941 return is_minmax(expr
, "max", lhs
, rhs
);
944 /* Extract a set of values satisfying the comparison "LHS op RHS"
945 * "comp" is the original statement that "LHS op RHS" is derived from
946 * and is used for diagnostics.
948 * If the comparison is of the form
952 * then the set is constructed as the intersection of the set corresponding
957 * A similar optimization is performed for max(a,b) <= c.
958 * We do this because that will lead to simpler representations of the set.
959 * If isl is ever enhanced to explicitly deal with min and max expressions,
960 * this optimization can be removed.
962 __isl_give isl_set
*PetScan::extract_comparison(BinaryOperatorKind op
,
963 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
970 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
972 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
974 if (op
== BO_LT
|| op
== BO_LE
) {
976 isl_set
*set1
, *set2
;
977 if (is_min(RHS
, expr1
, expr2
)) {
978 set1
= extract_comparison(op
, LHS
, expr1
, comp
);
979 set2
= extract_comparison(op
, LHS
, expr2
, comp
);
980 return isl_set_intersect(set1
, set2
);
982 if (is_max(LHS
, expr1
, expr2
)) {
983 set1
= extract_comparison(op
, expr1
, RHS
, comp
);
984 set2
= extract_comparison(op
, expr2
, RHS
, comp
);
985 return isl_set_intersect(set1
, set2
);
989 lhs
= extract_affine(LHS
);
990 rhs
= extract_affine(RHS
);
994 cond
= isl_pw_aff_lt_set(lhs
, rhs
);
997 cond
= isl_pw_aff_le_set(lhs
, rhs
);
1000 cond
= isl_pw_aff_eq_set(lhs
, rhs
);
1003 cond
= isl_pw_aff_ne_set(lhs
, rhs
);
1006 isl_pw_aff_free(lhs
);
1007 isl_pw_aff_free(rhs
);
1012 cond
= isl_set_coalesce(cond
);
1017 __isl_give isl_set
*PetScan::extract_comparison(BinaryOperator
*comp
)
1019 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1020 comp
->getRHS(), comp
);
1023 /* Extract a set of values satisfying the negation (logical not)
1024 * of a subexpression.
1026 __isl_give isl_set
*PetScan::extract_boolean(UnaryOperator
*op
)
1030 cond
= extract_condition(op
->getSubExpr());
1032 return isl_set_complement(cond
);
1035 /* Extract a set of values satisfying the union (logical or)
1036 * or intersection (logical and) of two subexpressions.
1038 __isl_give isl_set
*PetScan::extract_boolean(BinaryOperator
*comp
)
1044 lhs
= extract_condition(comp
->getLHS());
1045 rhs
= extract_condition(comp
->getRHS());
1047 switch (comp
->getOpcode()) {
1049 cond
= isl_set_intersect(lhs
, rhs
);
1052 cond
= isl_set_union(lhs
, rhs
);
1064 __isl_give isl_set
*PetScan::extract_condition(UnaryOperator
*expr
)
1066 switch (expr
->getOpcode()) {
1068 return extract_boolean(expr
);
1075 /* Extract a set of values satisfying the condition "expr != 0".
1077 __isl_give isl_set
*PetScan::extract_implicit_condition(Expr
*expr
)
1079 return isl_pw_aff_non_zero_set(extract_affine(expr
));
1082 /* Extract a set of values satisfying the condition expressed by "expr".
1084 * If the expression doesn't look like a condition, we assume it
1085 * is an affine expression and return the condition "expr != 0".
1087 __isl_give isl_set
*PetScan::extract_condition(Expr
*expr
)
1089 BinaryOperator
*comp
;
1092 return isl_set_universe(isl_space_params_alloc(ctx
, 0));
1094 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1095 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1097 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1098 return extract_condition(cast
<UnaryOperator
>(expr
));
1100 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1101 return extract_implicit_condition(expr
);
1103 comp
= cast
<BinaryOperator
>(expr
);
1104 switch (comp
->getOpcode()) {
1111 return extract_comparison(comp
);
1114 return extract_boolean(comp
);
1116 return extract_implicit_condition(expr
);
1120 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
1124 return pet_op_minus
;
1130 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
1134 return pet_op_add_assign
;
1136 return pet_op_sub_assign
;
1138 return pet_op_mul_assign
;
1140 return pet_op_div_assign
;
1142 return pet_op_assign
;
1164 /* Construct a pet_expr representing a unary operator expression.
1166 struct pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1168 struct pet_expr
*arg
;
1169 enum pet_op_type op
;
1171 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1172 if (op
== pet_op_last
) {
1177 arg
= extract_expr(expr
->getSubExpr());
1179 return pet_expr_new_unary(ctx
, op
, arg
);
1182 /* Mark the given access pet_expr as a write.
1183 * If a scalar is being accessed, then mark its value
1184 * as unknown in assigned_value.
1186 void PetScan::mark_write(struct pet_expr
*access
)
1191 access
->acc
.write
= 1;
1192 access
->acc
.read
= 0;
1194 if (isl_map_dim(access
->acc
.access
, isl_dim_out
) != 0)
1197 id
= isl_map_get_tuple_id(access
->acc
.access
, isl_dim_out
);
1198 decl
= (ValueDecl
*) isl_id_get_user(id
);
1199 clear_assignment(assigned_value
, decl
);
1203 /* Construct a pet_expr representing a binary operator expression.
1205 * If the top level operator is an assignment and the LHS is an access,
1206 * then we mark that access as a write. If the operator is a compound
1207 * assignment, the access is marked as both a read and a write.
1209 * If "expr" assigns something to a scalar variable, then we mark
1210 * the variable as having been assigned. If, furthermore, the expression
1211 * is affine, then keep track of this value in assigned_value
1212 * so that we can plug it in when we later come across the same variable.
1214 struct pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1216 struct pet_expr
*lhs
, *rhs
;
1217 enum pet_op_type op
;
1219 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1220 if (op
== pet_op_last
) {
1225 lhs
= extract_expr(expr
->getLHS());
1226 rhs
= extract_expr(expr
->getRHS());
1228 if (expr
->isAssignmentOp() && lhs
&& lhs
->type
== pet_expr_access
) {
1230 if (expr
->isCompoundAssignmentOp())
1234 if (expr
->getOpcode() == BO_Assign
&&
1235 lhs
&& lhs
->type
== pet_expr_access
&&
1236 isl_map_dim(lhs
->acc
.access
, isl_dim_out
) == 0) {
1237 isl_id
*id
= isl_map_get_tuple_id(lhs
->acc
.access
, isl_dim_out
);
1238 ValueDecl
*decl
= (ValueDecl
*) isl_id_get_user(id
);
1239 Expr
*rhs
= expr
->getRHS();
1240 isl_pw_aff
*pa
= try_extract_affine(rhs
);
1241 clear_assignment(assigned_value
, decl
);
1243 assigned_value
[decl
] = pa
;
1244 insert_expression(pa
);
1249 return pet_expr_new_binary(ctx
, op
, lhs
, rhs
);
1252 /* Construct a pet_expr representing a conditional operation.
1254 struct pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1256 struct pet_expr
*cond
, *lhs
, *rhs
;
1258 cond
= extract_expr(expr
->getCond());
1259 lhs
= extract_expr(expr
->getTrueExpr());
1260 rhs
= extract_expr(expr
->getFalseExpr());
1262 return pet_expr_new_ternary(ctx
, cond
, lhs
, rhs
);
1265 struct pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1267 return extract_expr(expr
->getSubExpr());
1270 /* Construct a pet_expr representing a floating point value.
1272 struct pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1274 return pet_expr_new_double(ctx
, expr
->getValueAsApproximateDouble());
1277 /* Extract an access relation from "expr" and then convert it into
1280 struct pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1283 struct pet_expr
*pe
;
1285 switch (expr
->getStmtClass()) {
1286 case Stmt::ArraySubscriptExprClass
:
1287 access
= extract_access(cast
<ArraySubscriptExpr
>(expr
));
1289 case Stmt::DeclRefExprClass
:
1290 access
= extract_access(cast
<DeclRefExpr
>(expr
));
1292 case Stmt::IntegerLiteralClass
:
1293 access
= extract_access(cast
<IntegerLiteral
>(expr
));
1300 pe
= pet_expr_from_access(access
);
1305 struct pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1307 return extract_expr(expr
->getSubExpr());
1310 /* Construct a pet_expr representing a function call.
1312 * If we are passing along a pointer to an array element
1313 * or an entire row or even higher dimensional slice of an array,
1314 * then the function being called may write into the array.
1316 * We assume here that if the function is declared to take a pointer
1317 * to a const type, then the function will perform a read
1318 * and that otherwise, it will perform a write.
1320 struct pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1322 struct pet_expr
*res
= NULL
;
1326 fd
= expr
->getDirectCallee();
1332 name
= fd
->getDeclName().getAsString();
1333 res
= pet_expr_new_call(ctx
, name
.c_str(), expr
->getNumArgs());
1337 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
1338 Expr
*arg
= expr
->getArg(i
);
1342 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1343 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(arg
);
1344 arg
= ice
->getSubExpr();
1346 if (arg
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1347 UnaryOperator
*op
= cast
<UnaryOperator
>(arg
);
1348 if (op
->getOpcode() == UO_AddrOf
) {
1350 arg
= op
->getSubExpr();
1353 res
->args
[i
] = PetScan::extract_expr(arg
);
1354 main_arg
= res
->args
[i
];
1356 res
->args
[i
] = pet_expr_new_unary(ctx
,
1357 pet_op_address_of
, res
->args
[i
]);
1360 if (arg
->getStmtClass() == Stmt::ArraySubscriptExprClass
&&
1361 array_depth(arg
->getType().getTypePtr()) > 0)
1363 if (is_addr
&& main_arg
->type
== pet_expr_access
) {
1365 if (!fd
->hasPrototype()) {
1366 unsupported(expr
, "prototype required");
1369 parm
= fd
->getParamDecl(i
);
1370 if (!const_base(parm
->getType()))
1371 mark_write(main_arg
);
1381 /* Try and onstruct a pet_expr representing "expr".
1383 struct pet_expr
*PetScan::extract_expr(Expr
*expr
)
1385 switch (expr
->getStmtClass()) {
1386 case Stmt::UnaryOperatorClass
:
1387 return extract_expr(cast
<UnaryOperator
>(expr
));
1388 case Stmt::CompoundAssignOperatorClass
:
1389 case Stmt::BinaryOperatorClass
:
1390 return extract_expr(cast
<BinaryOperator
>(expr
));
1391 case Stmt::ImplicitCastExprClass
:
1392 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1393 case Stmt::ArraySubscriptExprClass
:
1394 case Stmt::DeclRefExprClass
:
1395 case Stmt::IntegerLiteralClass
:
1396 return extract_access_expr(expr
);
1397 case Stmt::FloatingLiteralClass
:
1398 return extract_expr(cast
<FloatingLiteral
>(expr
));
1399 case Stmt::ParenExprClass
:
1400 return extract_expr(cast
<ParenExpr
>(expr
));
1401 case Stmt::ConditionalOperatorClass
:
1402 return extract_expr(cast
<ConditionalOperator
>(expr
));
1403 case Stmt::CallExprClass
:
1404 return extract_expr(cast
<CallExpr
>(expr
));
1411 /* Check if the given initialization statement is an assignment.
1412 * If so, return that assignment. Otherwise return NULL.
1414 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1416 BinaryOperator
*ass
;
1418 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1421 ass
= cast
<BinaryOperator
>(init
);
1422 if (ass
->getOpcode() != BO_Assign
)
1428 /* Check if the given initialization statement is a declaration
1429 * of a single variable.
1430 * If so, return that declaration. Otherwise return NULL.
1432 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1436 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1439 decl
= cast
<DeclStmt
>(init
);
1441 if (!decl
->isSingleDecl())
1444 return decl
->getSingleDecl();
1447 /* Given the assignment operator in the initialization of a for loop,
1448 * extract the induction variable, i.e., the (integer)variable being
1451 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1458 lhs
= init
->getLHS();
1459 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1464 ref
= cast
<DeclRefExpr
>(lhs
);
1465 decl
= ref
->getDecl();
1466 type
= decl
->getType().getTypePtr();
1468 if (!type
->isIntegerType()) {
1476 /* Given the initialization statement of a for loop and the single
1477 * declaration in this initialization statement,
1478 * extract the induction variable, i.e., the (integer) variable being
1481 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1485 vd
= cast
<VarDecl
>(decl
);
1487 const QualType type
= vd
->getType();
1488 if (!type
->isIntegerType()) {
1493 if (!vd
->getInit()) {
1501 /* Check that op is of the form iv++ or iv--.
1502 * "inc" is accordingly set to 1 or -1.
1504 bool PetScan::check_unary_increment(UnaryOperator
*op
, clang::ValueDecl
*iv
,
1510 if (!op
->isIncrementDecrementOp()) {
1515 if (op
->isIncrementOp())
1516 isl_int_set_si(inc
, 1);
1518 isl_int_set_si(inc
, -1);
1520 sub
= op
->getSubExpr();
1521 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1526 ref
= cast
<DeclRefExpr
>(sub
);
1527 if (ref
->getDecl() != iv
) {
1535 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1536 * has a single constant expression on a universe domain, then
1537 * put this constant in *user.
1539 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
1542 isl_int
*inc
= (isl_int
*)user
;
1545 if (!isl_set_plain_is_universe(set
) || !isl_aff_is_cst(aff
))
1548 isl_aff_get_constant(aff
, inc
);
1556 /* Check if op is of the form
1560 * with inc a constant and set "inc" accordingly.
1562 * We extract an affine expression from the RHS and the subtract iv.
1563 * The result should be a constant.
1565 bool PetScan::check_binary_increment(BinaryOperator
*op
, clang::ValueDecl
*iv
,
1575 if (op
->getOpcode() != BO_Assign
) {
1581 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1586 ref
= cast
<DeclRefExpr
>(lhs
);
1587 if (ref
->getDecl() != iv
) {
1592 val
= extract_affine(op
->getRHS());
1594 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1596 dim
= isl_space_params_alloc(ctx
, 1);
1597 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1598 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1599 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1601 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
1603 if (isl_pw_aff_foreach_piece(val
, &extract_cst
, &inc
) < 0) {
1604 isl_pw_aff_free(val
);
1609 isl_pw_aff_free(val
);
1614 /* Check that op is of the form iv += cst or iv -= cst.
1615 * "inc" is set to cst or -cst accordingly.
1617 bool PetScan::check_compound_increment(CompoundAssignOperator
*op
,
1618 clang::ValueDecl
*iv
, isl_int
&inc
)
1624 BinaryOperatorKind opcode
;
1626 opcode
= op
->getOpcode();
1627 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1631 if (opcode
== BO_SubAssign
)
1635 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1640 ref
= cast
<DeclRefExpr
>(lhs
);
1641 if (ref
->getDecl() != iv
) {
1648 if (rhs
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1649 UnaryOperator
*op
= cast
<UnaryOperator
>(rhs
);
1650 if (op
->getOpcode() != UO_Minus
) {
1657 rhs
= op
->getSubExpr();
1660 if (rhs
->getStmtClass() != Stmt::IntegerLiteralClass
) {
1665 extract_int(cast
<IntegerLiteral
>(rhs
), &inc
);
1667 isl_int_neg(inc
, inc
);
1672 /* Check that the increment of the given for loop increments
1673 * (or decrements) the induction variable "iv".
1674 * "up" is set to true if the induction variable is incremented.
1676 bool PetScan::check_increment(ForStmt
*stmt
, ValueDecl
*iv
, isl_int
&v
)
1678 Stmt
*inc
= stmt
->getInc();
1685 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1686 return check_unary_increment(cast
<UnaryOperator
>(inc
), iv
, v
);
1687 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1688 return check_compound_increment(
1689 cast
<CompoundAssignOperator
>(inc
), iv
, v
);
1690 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1691 return check_binary_increment(cast
<BinaryOperator
>(inc
), iv
, v
);
1697 /* Embed the given iteration domain in an extra outer loop
1698 * with induction variable "var".
1699 * If this variable appeared as a parameter in the constraints,
1700 * it is replaced by the new outermost dimension.
1702 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1703 __isl_take isl_id
*var
)
1707 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1708 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1710 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1711 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1718 /* Construct a pet_scop for an infinite loop around the given body.
1720 * We extract a pet_scop for the body and then embed it in a loop with
1729 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
1735 struct pet_scop
*scop
;
1737 scop
= extract(body
);
1741 id
= isl_id_alloc(ctx
, "t", NULL
);
1742 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
1743 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
1744 dim
= isl_space_from_domain(isl_set_get_space(domain
));
1745 dim
= isl_space_add_dims(dim
, isl_dim_out
, 1);
1746 sched
= isl_map_universe(dim
);
1747 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
1748 scop
= pet_scop_embed(scop
, domain
, sched
, id
);
1753 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1759 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
1761 return extract_infinite_loop(stmt
->getBody());
1764 /* Check if the while loop is of the form
1769 * If so, construct a scop for an infinite loop around body.
1772 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
1778 cond
= stmt
->getCond();
1784 set
= extract_condition(cond
);
1785 is_universe
= isl_set_plain_is_universe(set
);
1793 return extract_infinite_loop(stmt
->getBody());
1796 /* Check whether "cond" expresses a simple loop bound
1797 * on the only set dimension.
1798 * In particular, if "up" is set then "cond" should contain only
1799 * upper bounds on the set dimension.
1800 * Otherwise, it should contain only lower bounds.
1802 static bool is_simple_bound(__isl_keep isl_set
*cond
, isl_int inc
)
1804 if (isl_int_is_pos(inc
))
1805 return !isl_set_dim_has_lower_bound(cond
, isl_dim_set
, 0);
1807 return !isl_set_dim_has_upper_bound(cond
, isl_dim_set
, 0);
1810 /* Extend a condition on a given iteration of a loop to one that
1811 * imposes the same condition on all previous iterations.
1812 * "domain" expresses the lower [upper] bound on the iterations
1813 * when inc is positive [negative].
1815 * In particular, we construct the condition (when inc is positive)
1817 * forall i' : (domain(i') and i' <= i) => cond(i')
1819 * which is equivalent to
1821 * not exists i' : domain(i') and i' <= i and not cond(i')
1823 * We construct this set by negating cond, applying a map
1825 * { [i'] -> [i] : domain(i') and i' <= i }
1827 * and then negating the result again.
1829 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
1830 __isl_take isl_set
*domain
, isl_int inc
)
1832 isl_map
*previous_to_this
;
1834 if (isl_int_is_pos(inc
))
1835 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
1837 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
1839 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
1841 cond
= isl_set_complement(cond
);
1842 cond
= isl_set_apply(cond
, previous_to_this
);
1843 cond
= isl_set_complement(cond
);
1848 /* Construct a domain of the form
1850 * [id] -> { [] : exists a: id = init + a * inc and a >= 0 }
1852 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
1853 __isl_take isl_pw_aff
*init
, isl_int inc
)
1859 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
1860 dim
= isl_pw_aff_get_domain_space(init
);
1861 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1862 aff
= isl_aff_add_coefficient(aff
, isl_dim_in
, 0, inc
);
1863 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
1865 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
1866 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1867 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1868 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1870 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
1872 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
1874 return isl_set_project_out(set
, isl_dim_set
, 0, 1);
1877 static unsigned get_type_size(ValueDecl
*decl
)
1879 return decl
->getASTContext().getIntWidth(decl
->getType());
1882 /* Assuming "cond" represents a simple bound on a loop where the loop
1883 * iterator "iv" is incremented (or decremented) by one, check if wrapping
1886 * Under the given assumptions, wrapping is only possible if "cond" allows
1887 * for the last value before wrapping, i.e., 2^width - 1 in case of an
1888 * increasing iterator and 0 in case of a decreasing iterator.
1890 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
, isl_int inc
)
1896 test
= isl_set_copy(cond
);
1898 isl_int_init(limit
);
1899 if (isl_int_is_neg(inc
))
1900 isl_int_set_si(limit
, 0);
1902 isl_int_set_si(limit
, 1);
1903 isl_int_mul_2exp(limit
, limit
, get_type_size(iv
));
1904 isl_int_sub_ui(limit
, limit
, 1);
1907 test
= isl_set_fix(cond
, isl_dim_set
, 0, limit
);
1908 cw
= !isl_set_is_empty(test
);
1911 isl_int_clear(limit
);
1916 /* Given a one-dimensional space, construct the following mapping on this
1919 * { [v] -> [v mod 2^width] }
1921 * where width is the number of bits used to represent the values
1922 * of the unsigned variable "iv".
1924 static __isl_give isl_map
*compute_wrapping(__isl_take isl_space
*dim
,
1932 isl_int_set_si(mod
, 1);
1933 isl_int_mul_2exp(mod
, mod
, get_type_size(iv
));
1935 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1936 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
1937 aff
= isl_aff_mod(aff
, mod
);
1941 return isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
1942 map
= isl_map_reverse(map
);
1945 /* Construct a pet_scop for a for statement.
1946 * The for loop is required to be of the form
1948 * for (i = init; condition; ++i)
1952 * for (i = init; condition; --i)
1954 * The initialization of the for loop should either be an assignment
1955 * to an integer variable, or a declaration of such a variable with
1958 * The condition is allowed to contain nested accesses, provided
1959 * they are not being written to inside the body of the loop.
1961 * We extract a pet_scop for the body and then embed it in a loop with
1962 * iteration domain and schedule
1964 * { [i] : i >= init and condition' }
1969 * { [i] : i <= init and condition' }
1972 * Where condition' is equal to condition if the latter is
1973 * a simple upper [lower] bound and a condition that is extended
1974 * to apply to all previous iterations otherwise.
1976 * If the stride of the loop is not 1, then "i >= init" is replaced by
1978 * (exists a: i = init + stride * a and a >= 0)
1980 * If the loop iterator i is unsigned, then wrapping may occur.
1981 * During the computation, we work with a virtual iterator that
1982 * does not wrap. However, the condition in the code applies
1983 * to the wrapped value, so we need to change condition(i)
1984 * into condition([i % 2^width]).
1985 * After computing the virtual domain and schedule, we apply
1986 * the function { [v] -> [v % 2^width] } to the domain and the domain
1987 * of the schedule. In order not to lose any information, we also
1988 * need to intersect the domain of the schedule with the virtual domain
1989 * first, since some iterations in the wrapped domain may be scheduled
1990 * several times, typically an infinite number of times.
1991 * Note that there is no need to perform this final wrapping
1992 * if the loop condition (after wrapping) is simple.
1994 * Wrapping on unsigned iterators can be avoided entirely if
1995 * loop condition is simple, the loop iterator is incremented
1996 * [decremented] by one and the last value before wrapping cannot
1997 * possibly satisfy the loop condition.
1999 * Before extracting a pet_scop from the body we remove all
2000 * assignments in assigned_value to variables that are assigned
2001 * somewhere in the body of the loop.
2003 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2005 BinaryOperator
*ass
;
2013 isl_set
*cond
= NULL
;
2015 struct pet_scop
*scop
;
2016 assigned_value_cache
cache(assigned_value
);
2021 isl_map
*wrap
= NULL
;
2023 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2024 return extract_infinite_for(stmt
);
2026 init
= stmt
->getInit();
2031 if ((ass
= initialization_assignment(init
)) != NULL
) {
2032 iv
= extract_induction_variable(ass
);
2035 lhs
= ass
->getLHS();
2036 rhs
= ass
->getRHS();
2037 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2038 VarDecl
*var
= extract_induction_variable(init
, decl
);
2042 rhs
= var
->getInit();
2043 lhs
= create_DeclRefExpr(var
);
2045 unsupported(stmt
->getInit());
2050 if (!check_increment(stmt
, iv
, inc
)) {
2055 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2057 assigned_value
.erase(iv
);
2058 clear_assignments
clear(assigned_value
);
2059 clear
.TraverseStmt(stmt
->getBody());
2061 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
2063 is_one
= isl_int_is_one(inc
) || isl_int_is_negone(inc
);
2065 domain
= extract_comparison(isl_int_is_pos(inc
) ? BO_GE
: BO_LE
,
2068 isl_pw_aff
*lb
= extract_affine(rhs
);
2069 domain
= strided_domain(isl_id_copy(id
), lb
, inc
);
2072 scop
= extract(stmt
->getBody());
2074 cond
= try_extract_nested_condition(stmt
->getCond());
2075 if (cond
&& !is_nested_allowed(cond
, scop
)) {
2081 cond
= extract_condition(stmt
->getCond());
2082 cond
= embed(cond
, isl_id_copy(id
));
2083 domain
= embed(domain
, isl_id_copy(id
));
2084 is_simple
= is_simple_bound(cond
, inc
);
2086 (!is_simple
|| !is_one
|| can_wrap(cond
, iv
, inc
))) {
2087 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2088 cond
= isl_set_apply(cond
, isl_map_reverse(isl_map_copy(wrap
)));
2089 is_simple
= is_simple
&& is_simple_bound(cond
, inc
);
2092 cond
= valid_for_each_iteration(cond
,
2093 isl_set_copy(domain
), inc
);
2094 domain
= isl_set_intersect(domain
, cond
);
2095 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2096 dim
= isl_space_from_domain(isl_set_get_space(domain
));
2097 dim
= isl_space_add_dims(dim
, isl_dim_out
, 1);
2098 sched
= isl_map_universe(dim
);
2099 if (isl_int_is_pos(inc
))
2100 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2102 sched
= isl_map_oppose(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2104 if (is_unsigned
&& !is_simple
) {
2105 wrap
= isl_map_set_dim_id(wrap
,
2106 isl_dim_out
, 0, isl_id_copy(id
));
2107 sched
= isl_map_intersect_domain(sched
, isl_set_copy(domain
));
2108 domain
= isl_set_apply(domain
, isl_map_copy(wrap
));
2109 sched
= isl_map_apply_domain(sched
, wrap
);
2113 scop
= pet_scop_embed(scop
, domain
, sched
, id
);
2114 scop
= resolve_nested(scop
);
2115 clear_assignment(assigned_value
, iv
);
2121 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
)
2123 return extract(stmt
->children());
2126 /* Does "id" refer to a nested access?
2128 static bool is_nested_parameter(__isl_keep isl_id
*id
)
2130 return id
&& isl_id_get_user(id
) && !isl_id_get_name(id
);
2133 /* Does parameter "pos" of "space" refer to a nested access?
2135 static bool is_nested_parameter(__isl_keep isl_space
*space
, int pos
)
2140 id
= isl_space_get_dim_id(space
, isl_dim_param
, pos
);
2141 nested
= is_nested_parameter(id
);
2147 /* Does parameter "pos" of "map" refer to a nested access?
2149 static bool is_nested_parameter(__isl_keep isl_map
*map
, int pos
)
2154 id
= isl_map_get_dim_id(map
, isl_dim_param
, pos
);
2155 nested
= is_nested_parameter(id
);
2161 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2163 static int n_nested_parameter(__isl_keep isl_space
*space
)
2168 nparam
= isl_space_dim(space
, isl_dim_param
);
2169 for (int i
= 0; i
< nparam
; ++i
)
2170 if (is_nested_parameter(space
, i
))
2176 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2178 static int n_nested_parameter(__isl_keep isl_map
*map
)
2183 space
= isl_map_get_space(map
);
2184 n
= n_nested_parameter(space
);
2185 isl_space_free(space
);
2190 /* For each nested access parameter in "space",
2191 * construct a corresponding pet_expr, place it in args and
2192 * record its position in "param2pos".
2193 * "n_arg" is the number of elements that are already in args.
2194 * The position recorded in "param2pos" takes this number into account.
2195 * If the pet_expr corresponding to a parameter is identical to
2196 * the pet_expr corresponding to an earlier parameter, then these two
2197 * parameters are made to refer to the same element in args.
2199 * Return the final number of elements in args or -1 if an error has occurred.
2201 int PetScan::extract_nested(__isl_keep isl_space
*space
,
2202 int n_arg
, struct pet_expr
**args
, std::map
<int,int> ¶m2pos
)
2206 nparam
= isl_space_dim(space
, isl_dim_param
);
2207 for (int i
= 0; i
< nparam
; ++i
) {
2209 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
2212 if (!is_nested_parameter(id
)) {
2217 nested
= (Expr
*) isl_id_get_user(id
);
2218 args
[n_arg
] = extract_expr(nested
);
2222 for (j
= 0; j
< n_arg
; ++j
)
2223 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
2227 pet_expr_free(args
[n_arg
]);
2231 param2pos
[i
] = n_arg
++;
2239 /* For each nested access parameter in the access relations in "expr",
2240 * construct a corresponding pet_expr, place it in expr->args and
2241 * record its position in "param2pos".
2242 * n is the number of nested access parameters.
2244 struct pet_expr
*PetScan::extract_nested(struct pet_expr
*expr
, int n
,
2245 std::map
<int,int> ¶m2pos
)
2249 expr
->args
= isl_calloc_array(ctx
, struct pet_expr
*, n
);
2254 space
= isl_map_get_space(expr
->acc
.access
);
2255 n
= extract_nested(space
, 0, expr
->args
, param2pos
);
2256 isl_space_free(space
);
2264 pet_expr_free(expr
);
2268 /* Look for parameters in any access relation in "expr" that
2269 * refer to nested accesses. In particular, these are
2270 * parameters with no name.
2272 * If there are any such parameters, then the domain of the access
2273 * relation, which is still [] at this point, is replaced by
2274 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2275 * (after identifying identical nested accesses).
2276 * The parameters are then equated to the corresponding t dimensions
2277 * and subsequently projected out.
2278 * param2pos maps the position of the parameter to the position
2279 * of the corresponding t dimension.
2281 struct pet_expr
*PetScan::resolve_nested(struct pet_expr
*expr
)
2288 std::map
<int,int> param2pos
;
2293 for (int i
= 0; i
< expr
->n_arg
; ++i
) {
2294 expr
->args
[i
] = resolve_nested(expr
->args
[i
]);
2295 if (!expr
->args
[i
]) {
2296 pet_expr_free(expr
);
2301 if (expr
->type
!= pet_expr_access
)
2304 n
= n_nested_parameter(expr
->acc
.access
);
2308 expr
= extract_nested(expr
, n
, param2pos
);
2313 nparam
= isl_map_dim(expr
->acc
.access
, isl_dim_param
);
2314 n_in
= isl_map_dim(expr
->acc
.access
, isl_dim_in
);
2315 dim
= isl_map_get_space(expr
->acc
.access
);
2316 dim
= isl_space_domain(dim
);
2317 dim
= isl_space_from_domain(dim
);
2318 dim
= isl_space_add_dims(dim
, isl_dim_out
, n
);
2319 map
= isl_map_universe(dim
);
2320 map
= isl_map_domain_map(map
);
2321 map
= isl_map_reverse(map
);
2322 expr
->acc
.access
= isl_map_apply_domain(expr
->acc
.access
, map
);
2324 for (int i
= nparam
- 1; i
>= 0; --i
) {
2325 isl_id
*id
= isl_map_get_dim_id(expr
->acc
.access
,
2327 if (!is_nested_parameter(id
)) {
2332 expr
->acc
.access
= isl_map_equate(expr
->acc
.access
,
2333 isl_dim_param
, i
, isl_dim_in
,
2334 n_in
+ param2pos
[i
]);
2335 expr
->acc
.access
= isl_map_project_out(expr
->acc
.access
,
2336 isl_dim_param
, i
, 1);
2343 pet_expr_free(expr
);
2347 /* Convert a top-level pet_expr to a pet_scop with one statement.
2348 * This mainly involves resolving nested expression parameters
2349 * and setting the name of the iteration space.
2350 * The name is given by "label" if it is non-NULL. Otherwise,
2351 * it is of the form S_<n_stmt>.
2353 struct pet_scop
*PetScan::extract(Stmt
*stmt
, struct pet_expr
*expr
,
2354 __isl_take isl_id
*label
)
2356 struct pet_stmt
*ps
;
2357 SourceLocation loc
= stmt
->getLocStart();
2358 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
2360 expr
= resolve_nested(expr
);
2361 ps
= pet_stmt_from_pet_expr(ctx
, line
, label
, n_stmt
++, expr
);
2362 return pet_scop_from_pet_stmt(ctx
, ps
);
2365 /* Check if we can extract an affine expression from "expr".
2366 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2367 * We turn on autodetection so that we won't generate any warnings
2368 * and turn off nesting, so that we won't accept any non-affine constructs.
2370 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
2373 int save_autodetect
= autodetect
;
2374 bool save_nesting
= nesting_enabled
;
2377 nesting_enabled
= false;
2379 pwaff
= extract_affine(expr
);
2381 autodetect
= save_autodetect
;
2382 nesting_enabled
= save_nesting
;
2387 /* Check whether "expr" is an affine expression.
2389 bool PetScan::is_affine(Expr
*expr
)
2393 pwaff
= try_extract_affine(expr
);
2394 isl_pw_aff_free(pwaff
);
2396 return pwaff
!= NULL
;
2399 /* Check whether "expr" is an affine constraint.
2400 * We turn on autodetection so that we won't generate any warnings
2401 * and turn off nesting, so that we won't accept any non-affine constructs.
2403 bool PetScan::is_affine_condition(Expr
*expr
)
2406 int save_autodetect
= autodetect
;
2407 bool save_nesting
= nesting_enabled
;
2410 nesting_enabled
= false;
2412 set
= extract_condition(expr
);
2415 autodetect
= save_autodetect
;
2416 nesting_enabled
= save_nesting
;
2421 /* Check if we can extract a condition from "expr".
2422 * Return the condition as an isl_set if we can and NULL otherwise.
2423 * If allow_nested is set, then the condition may involve parameters
2424 * corresponding to nested accesses.
2425 * We turn on autodetection so that we won't generate any warnings.
2427 __isl_give isl_set
*PetScan::try_extract_nested_condition(Expr
*expr
)
2430 int save_autodetect
= autodetect
;
2431 bool save_nesting
= nesting_enabled
;
2434 nesting_enabled
= allow_nested
;
2435 set
= extract_condition(expr
);
2437 autodetect
= save_autodetect
;
2438 nesting_enabled
= save_nesting
;
2443 /* If the top-level expression of "stmt" is an assignment, then
2444 * return that assignment as a BinaryOperator.
2445 * Otherwise return NULL.
2447 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
2449 BinaryOperator
*ass
;
2453 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
2456 ass
= cast
<BinaryOperator
>(stmt
);
2457 if(ass
->getOpcode() != BO_Assign
)
2463 /* Check if the given if statement is a conditional assignement
2464 * with a non-affine condition. If so, construct a pet_scop
2465 * corresponding to this conditional assignment. Otherwise return NULL.
2467 * In particular we check if "stmt" is of the form
2474 * where a is some array or scalar access.
2475 * The constructed pet_scop then corresponds to the expression
2477 * a = condition ? f(...) : g(...)
2479 * All access relations in f(...) are intersected with condition
2480 * while all access relation in g(...) are intersected with the complement.
2482 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
2484 BinaryOperator
*ass_then
, *ass_else
;
2485 isl_map
*write_then
, *write_else
;
2486 isl_set
*cond
, *comp
;
2487 isl_map
*map
, *map_true
, *map_false
;
2489 struct pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
2490 bool save_nesting
= nesting_enabled
;
2492 ass_then
= top_assignment_or_null(stmt
->getThen());
2493 ass_else
= top_assignment_or_null(stmt
->getElse());
2495 if (!ass_then
|| !ass_else
)
2498 if (is_affine_condition(stmt
->getCond()))
2501 write_then
= extract_access(ass_then
->getLHS());
2502 write_else
= extract_access(ass_else
->getLHS());
2504 equal
= isl_map_is_equal(write_then
, write_else
);
2505 isl_map_free(write_else
);
2506 if (equal
< 0 || !equal
) {
2507 isl_map_free(write_then
);
2511 nesting_enabled
= allow_nested
;
2512 cond
= extract_condition(stmt
->getCond());
2513 nesting_enabled
= save_nesting
;
2514 comp
= isl_set_complement(isl_set_copy(cond
));
2515 map_true
= isl_map_from_domain(isl_set_from_params(isl_set_copy(cond
)));
2516 map_true
= isl_map_add_dims(map_true
, isl_dim_out
, 1);
2517 map_true
= isl_map_fix_si(map_true
, isl_dim_out
, 0, 1);
2518 map_false
= isl_map_from_domain(isl_set_from_params(isl_set_copy(comp
)));
2519 map_false
= isl_map_add_dims(map_false
, isl_dim_out
, 1);
2520 map_false
= isl_map_fix_si(map_false
, isl_dim_out
, 0, 0);
2521 map
= isl_map_union_disjoint(map_true
, map_false
);
2523 pe_cond
= pet_expr_from_access(map
);
2525 pe_then
= extract_expr(ass_then
->getRHS());
2526 pe_then
= pet_expr_restrict(pe_then
, cond
);
2527 pe_else
= extract_expr(ass_else
->getRHS());
2528 pe_else
= pet_expr_restrict(pe_else
, comp
);
2530 pe
= pet_expr_new_ternary(ctx
, pe_cond
, pe_then
, pe_else
);
2531 pe_write
= pet_expr_from_access(write_then
);
2533 pe_write
->acc
.write
= 1;
2534 pe_write
->acc
.read
= 0;
2536 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, pe_write
, pe
);
2537 return extract(stmt
, pe
);
2540 /* Create an access to a virtual array representing the result
2542 * Unlike other accessed data, the id of the array is NULL as
2543 * there is no ValueDecl in the program corresponding to the virtual
2545 * The array starts out as a scalar, but grows along with the
2546 * statement writing to the array in pet_scop_embed.
2548 static __isl_give isl_map
*create_test_access(isl_ctx
*ctx
, int test_nr
)
2550 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, 0);
2554 snprintf(name
, sizeof(name
), "__pet_test_%d", test_nr
);
2555 id
= isl_id_alloc(ctx
, name
, NULL
);
2556 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
2557 return isl_map_universe(dim
);
2560 /* Create a pet_scop with a single statement evaluating "cond"
2561 * and writing the result to a virtual scalar, as expressed by
2564 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
,
2565 __isl_take isl_map
*access
)
2567 struct pet_expr
*expr
, *write
;
2568 struct pet_stmt
*ps
;
2569 SourceLocation loc
= cond
->getLocStart();
2570 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
2572 write
= pet_expr_from_access(access
);
2574 write
->acc
.write
= 1;
2575 write
->acc
.read
= 0;
2577 expr
= extract_expr(cond
);
2578 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, write
, expr
);
2579 ps
= pet_stmt_from_pet_expr(ctx
, line
, NULL
, n_stmt
++, expr
);
2580 return pet_scop_from_pet_stmt(ctx
, ps
);
2583 /* Add an array with the given extent ("access") to the list
2584 * of arrays in "scop" and return the extended pet_scop.
2585 * The array is marked as attaining values 0 and 1 only.
2587 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2588 __isl_keep isl_map
*access
, clang::ASTContext
&ast_ctx
)
2590 isl_ctx
*ctx
= isl_map_get_ctx(access
);
2592 struct pet_array
**arrays
;
2593 struct pet_array
*array
;
2600 arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
2604 scop
->arrays
= arrays
;
2606 array
= isl_calloc_type(ctx
, struct pet_array
);
2610 array
->extent
= isl_map_range(isl_map_copy(access
));
2611 dim
= isl_space_params_alloc(ctx
, 0);
2612 array
->context
= isl_set_universe(dim
);
2613 dim
= isl_space_set_alloc(ctx
, 0, 1);
2614 array
->value_bounds
= isl_set_universe(dim
);
2615 array
->value_bounds
= isl_set_lower_bound_si(array
->value_bounds
,
2617 array
->value_bounds
= isl_set_upper_bound_si(array
->value_bounds
,
2619 array
->element_type
= strdup("int");
2620 array
->element_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
2622 scop
->arrays
[scop
->n_array
] = array
;
2625 if (!array
->extent
|| !array
->context
)
2630 pet_scop_free(scop
);
2635 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
,
2639 /* Apply the map pointed to by "user" to the domain of the access
2640 * relation, thereby embedding it in the range of the map.
2641 * The domain of both relations is the zero-dimensional domain.
2643 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
, void *user
)
2645 isl_map
*map
= (isl_map
*) user
;
2647 return isl_map_apply_domain(access
, isl_map_copy(map
));
2650 /* Apply "map" to all access relations in "expr".
2652 static struct pet_expr
*embed(struct pet_expr
*expr
, __isl_keep isl_map
*map
)
2654 return pet_expr_foreach_access(expr
, &embed_access
, map
);
2657 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2659 static int n_nested_parameter(__isl_keep isl_set
*set
)
2664 space
= isl_set_get_space(set
);
2665 n
= n_nested_parameter(space
);
2666 isl_space_free(space
);
2671 /* Remove all parameters from "map" that refer to nested accesses.
2673 static __isl_give isl_map
*remove_nested_parameters(__isl_take isl_map
*map
)
2678 space
= isl_map_get_space(map
);
2679 nparam
= isl_space_dim(space
, isl_dim_param
);
2680 for (int i
= nparam
- 1; i
>= 0; --i
)
2681 if (is_nested_parameter(space
, i
))
2682 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
2683 isl_space_free(space
);
2689 static __isl_give isl_map
*access_remove_nested_parameters(
2690 __isl_take isl_map
*access
, void *user
);
2693 static __isl_give isl_map
*access_remove_nested_parameters(
2694 __isl_take isl_map
*access
, void *user
)
2696 return remove_nested_parameters(access
);
2699 /* Remove all nested access parameters from the schedule and all
2700 * accesses of "stmt".
2701 * There is no need to remove them from the domain as these parameters
2702 * have already been removed from the domain when this function is called.
2704 static struct pet_stmt
*remove_nested_parameters(struct pet_stmt
*stmt
)
2708 stmt
->schedule
= remove_nested_parameters(stmt
->schedule
);
2709 stmt
->body
= pet_expr_foreach_access(stmt
->body
,
2710 &access_remove_nested_parameters
, NULL
);
2711 if (!stmt
->schedule
|| !stmt
->body
)
2713 for (int i
= 0; i
< stmt
->n_arg
; ++i
) {
2714 stmt
->args
[i
] = pet_expr_foreach_access(stmt
->args
[i
],
2715 &access_remove_nested_parameters
, NULL
);
2722 pet_stmt_free(stmt
);
2726 /* For each nested access parameter in the domain of "stmt",
2727 * construct a corresponding pet_expr, place it in stmt->args and
2728 * record its position in "param2pos".
2729 * n is the number of nested access parameters.
2731 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
2732 std::map
<int,int> ¶m2pos
)
2736 struct pet_expr
**args
;
2738 n_arg
= stmt
->n_arg
;
2739 args
= isl_realloc_array(ctx
, stmt
->args
, struct pet_expr
*, n_arg
+ n
);
2745 space
= isl_set_get_space(stmt
->domain
);
2746 n
= extract_nested(space
, n_arg
, stmt
->args
, param2pos
);
2747 isl_space_free(space
);
2755 pet_stmt_free(stmt
);
2759 /* Look for parameters in the iteration domain of "stmt" that
2760 * refer to nested accesses. In particular, these are
2761 * parameters with no name.
2763 * If there are any such parameters, then as many extra variables
2764 * (after identifying identical nested accesses) are added to the
2765 * range of the map wrapped inside the domain.
2766 * If the original domain is not a wrapped map, then a new wrapped
2767 * map is created with zero output dimensions.
2768 * The parameters are then equated to the corresponding output dimensions
2769 * and subsequently projected out, from the iteration domain,
2770 * the schedule and the access relations.
2771 * For each of the output dimensions, a corresponding argument
2772 * expression is added. Initially they are created with
2773 * a zero-dimensional domain, so they have to be embedded
2774 * in the current iteration domain.
2775 * param2pos maps the position of the parameter to the position
2776 * of the corresponding output dimension in the wrapped map.
2778 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
2784 std::map
<int,int> param2pos
;
2789 n
= n_nested_parameter(stmt
->domain
);
2793 n_arg
= stmt
->n_arg
;
2794 stmt
= extract_nested(stmt
, n
, param2pos
);
2798 n
= stmt
->n_arg
- n_arg
;
2799 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
2800 if (isl_set_is_wrapping(stmt
->domain
))
2801 map
= isl_set_unwrap(stmt
->domain
);
2803 map
= isl_map_from_domain(stmt
->domain
);
2804 map
= isl_map_add_dims(map
, isl_dim_out
, n
);
2806 for (int i
= nparam
- 1; i
>= 0; --i
) {
2809 if (!is_nested_parameter(map
, i
))
2812 id
= isl_map_get_tuple_id(stmt
->args
[param2pos
[i
]]->acc
.access
,
2814 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
2815 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
2817 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
2820 stmt
->domain
= isl_map_wrap(map
);
2822 map
= isl_set_unwrap(isl_set_copy(stmt
->domain
));
2823 map
= isl_map_from_range(isl_map_domain(map
));
2824 for (int pos
= n_arg
; pos
< stmt
->n_arg
; ++pos
)
2825 stmt
->args
[pos
] = embed(stmt
->args
[pos
], map
);
2828 stmt
= remove_nested_parameters(stmt
);
2832 pet_stmt_free(stmt
);
2836 /* For each statement in "scop", move the parameters that correspond
2837 * to nested access into the ranges of the domains and create
2838 * corresponding argument expressions.
2840 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
2845 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
2846 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
2847 if (!scop
->stmts
[i
])
2853 pet_scop_free(scop
);
2857 /* Does "space" involve any parameters that refer to nested
2858 * accesses, i.e., parameters with no name?
2860 static bool has_nested(__isl_keep isl_space
*space
)
2864 nparam
= isl_space_dim(space
, isl_dim_param
);
2865 for (int i
= 0; i
< nparam
; ++i
)
2866 if (is_nested_parameter(space
, i
))
2872 /* Does "set" involve any parameters that refer to nested
2873 * accesses, i.e., parameters with no name?
2875 static bool has_nested(__isl_keep isl_set
*set
)
2880 space
= isl_set_get_space(set
);
2881 nested
= has_nested(space
);
2882 isl_space_free(space
);
2887 /* Given an access expression "expr", is the variable accessed by
2888 * "expr" assigned anywhere inside "scop"?
2890 static bool is_assigned(pet_expr
*expr
, pet_scop
*scop
)
2892 bool assigned
= false;
2895 id
= isl_map_get_tuple_id(expr
->acc
.access
, isl_dim_out
);
2896 assigned
= pet_scop_writes(scop
, id
);
2902 /* Are all nested access parameters in "set" allowed given "scop".
2903 * In particular, is none of them written by anywhere inside "scop".
2905 bool PetScan::is_nested_allowed(__isl_keep isl_set
*set
, pet_scop
*scop
)
2909 nparam
= isl_set_dim(set
, isl_dim_param
);
2910 for (int i
= 0; i
< nparam
; ++i
) {
2912 isl_id
*id
= isl_set_get_dim_id(set
, isl_dim_param
, i
);
2916 if (!is_nested_parameter(id
)) {
2921 nested
= (Expr
*) isl_id_get_user(id
);
2922 expr
= extract_expr(nested
);
2923 allowed
= expr
&& expr
->type
== pet_expr_access
&&
2924 !is_assigned(expr
, scop
);
2926 pet_expr_free(expr
);
2936 /* Construct a pet_scop for an if statement.
2938 * If the condition fits the pattern of a conditional assignment,
2939 * then it is handled by extract_conditional_assignment.
2940 * Otherwise, we do the following.
2942 * If the condition is affine, then the condition is added
2943 * to the iteration domains of the then branch, while the
2944 * opposite of the condition in added to the iteration domains
2945 * of the else branch, if any.
2946 * We allow the condition to be dynamic, i.e., to refer to
2947 * scalars or array elements that may be written to outside
2948 * of the given if statement. These nested accesses are then represented
2949 * as output dimensions in the wrapping iteration domain.
2950 * If it also written _inside_ the then or else branch, then
2951 * we treat the condition as non-affine.
2952 * As explained below, this will introduce an extra statement.
2953 * For aesthetic reasons, we want this statement to have a statement
2954 * number that is lower than those of the then and else branches.
2955 * In order to evaluate if will need such a statement, however, we
2956 * first construct scops for the then and else branches.
2957 * We therefore reserve a statement number if we might have to
2958 * introduce such an extra statement.
2960 * If the condition is not affine, then we create a separate
2961 * statement that writes the result of the condition to a virtual scalar.
2962 * A constraint requiring the value of this virtual scalar to be one
2963 * is added to the iteration domains of the then branch.
2964 * Similarly, a constraint requiring the value of this virtual scalar
2965 * to be zero is added to the iteration domains of the else branch, if any.
2966 * We adjust the schedules to ensure that the virtual scalar is written
2967 * before it is read.
2969 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
2971 struct pet_scop
*scop_then
, *scop_else
, *scop
;
2972 assigned_value_cache
cache(assigned_value
);
2973 isl_map
*test_access
= NULL
;
2977 scop
= extract_conditional_assignment(stmt
);
2981 cond
= try_extract_nested_condition(stmt
->getCond());
2982 if (allow_nested
&& (!cond
|| has_nested(cond
)))
2985 scop_then
= extract(stmt
->getThen());
2987 if (stmt
->getElse()) {
2988 scop_else
= extract(stmt
->getElse());
2990 if (scop_then
&& !scop_else
) {
2995 if (!scop_then
&& scop_else
) {
3004 (!is_nested_allowed(cond
, scop_then
) ||
3005 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
3009 if (allow_nested
&& !cond
) {
3010 int save_n_stmt
= n_stmt
;
3011 test_access
= create_test_access(ctx
, n_test
++);
3013 scop
= extract_non_affine_condition(stmt
->getCond(),
3014 isl_map_copy(test_access
));
3015 n_stmt
= save_n_stmt
;
3016 scop
= scop_add_array(scop
, test_access
, ast_context
);
3018 pet_scop_free(scop_then
);
3019 pet_scop_free(scop_else
);
3020 isl_map_free(test_access
);
3027 cond
= extract_condition(stmt
->getCond());
3028 scop
= pet_scop_restrict(scop_then
, isl_set_copy(cond
));
3030 if (stmt
->getElse()) {
3031 cond
= isl_set_complement(cond
);
3032 scop_else
= pet_scop_restrict(scop_else
, cond
);
3033 scop
= pet_scop_add(ctx
, scop
, scop_else
);
3036 scop
= resolve_nested(scop
);
3038 scop
= pet_scop_prefix(scop
, 0);
3039 scop_then
= pet_scop_prefix(scop_then
, 1);
3040 scop_then
= pet_scop_filter(scop_then
,
3041 isl_map_copy(test_access
), 1);
3042 scop
= pet_scop_add(ctx
, scop
, scop_then
);
3043 if (stmt
->getElse()) {
3044 scop_else
= pet_scop_prefix(scop_else
, 1);
3045 scop_else
= pet_scop_filter(scop_else
, test_access
, 0);
3046 scop
= pet_scop_add(ctx
, scop
, scop_else
);
3048 isl_map_free(test_access
);
3054 /* Try and construct a pet_scop for a label statement.
3055 * We currently only allow labels on expression statements.
3057 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
3062 sub
= stmt
->getSubStmt();
3063 if (!isa
<Expr
>(sub
)) {
3068 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
3070 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
3073 /* Try and construct a pet_scop corresponding to "stmt".
3075 struct pet_scop
*PetScan::extract(Stmt
*stmt
)
3077 if (isa
<Expr
>(stmt
))
3078 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
3080 switch (stmt
->getStmtClass()) {
3081 case Stmt::WhileStmtClass
:
3082 return extract(cast
<WhileStmt
>(stmt
));
3083 case Stmt::ForStmtClass
:
3084 return extract_for(cast
<ForStmt
>(stmt
));
3085 case Stmt::IfStmtClass
:
3086 return extract(cast
<IfStmt
>(stmt
));
3087 case Stmt::CompoundStmtClass
:
3088 return extract(cast
<CompoundStmt
>(stmt
));
3089 case Stmt::LabelStmtClass
:
3090 return extract(cast
<LabelStmt
>(stmt
));
3098 /* Try and construct a pet_scop corresponding to (part of)
3099 * a sequence of statements.
3101 struct pet_scop
*PetScan::extract(StmtRange stmt_range
)
3106 bool partial_range
= false;
3108 scop
= pet_scop_empty(ctx
);
3109 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
3111 struct pet_scop
*scop_i
;
3112 scop_i
= extract(child
);
3113 if (scop
&& partial
) {
3114 pet_scop_free(scop_i
);
3117 scop_i
= pet_scop_prefix(scop_i
, j
);
3120 scop
= pet_scop_add(ctx
, scop
, scop_i
);
3122 partial_range
= true;
3123 if (scop
->n_stmt
!= 0 && !scop_i
)
3126 scop
= pet_scop_add(ctx
, scop
, scop_i
);
3132 if (scop
&& partial_range
)
3138 /* Check if the scop marked by the user is exactly this Stmt
3139 * or part of this Stmt.
3140 * If so, return a pet_scop corresponding to the marked region.
3141 * Otherwise, return NULL.
3143 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
3145 SourceManager
&SM
= PP
.getSourceManager();
3146 unsigned start_off
, end_off
;
3148 start_off
= SM
.getFileOffset(stmt
->getLocStart());
3149 end_off
= SM
.getFileOffset(stmt
->getLocEnd());
3151 if (start_off
> loc
.end
)
3153 if (end_off
< loc
.start
)
3155 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
3156 return extract(stmt
);
3160 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
3161 Stmt
*child
= *start
;
3164 start_off
= SM
.getFileOffset(child
->getLocStart());
3165 end_off
= SM
.getFileOffset(child
->getLocEnd());
3166 if (start_off
< loc
.start
&& end_off
> loc
.end
)
3168 if (start_off
>= loc
.start
)
3173 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
3175 start_off
= SM
.getFileOffset(child
->getLocStart());
3176 if (start_off
>= loc
.end
)
3180 return extract(StmtRange(start
, end
));
3183 /* Set the size of index "pos" of "array" to "size".
3184 * In particular, add a constraint of the form
3188 * to array->extent and a constraint of the form
3192 * to array->context.
3194 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
3195 __isl_take isl_pw_aff
*size
)
3205 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
3206 array
->context
= isl_set_intersect(array
->context
, valid
);
3208 dim
= isl_set_get_space(array
->extent
);
3209 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
3210 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
3211 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
3212 index
= isl_pw_aff_alloc(univ
, aff
);
3214 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
3215 isl_set_dim(array
->extent
, isl_dim_set
));
3216 id
= isl_set_get_tuple_id(array
->extent
);
3217 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
3218 bound
= isl_pw_aff_lt_set(index
, size
);
3220 array
->extent
= isl_set_intersect(array
->extent
, bound
);
3222 if (!array
->context
|| !array
->extent
)
3227 pet_array_free(array
);
3231 /* Figure out the size of the array at position "pos" and all
3232 * subsequent positions from "type" and update "array" accordingly.
3234 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
3235 const Type
*type
, int pos
)
3237 const ArrayType
*atype
;
3243 if (type
->isPointerType()) {
3244 type
= type
->getPointeeType().getTypePtr();
3245 return set_upper_bounds(array
, type
, pos
+ 1);
3247 if (!type
->isArrayType())
3250 type
= type
->getCanonicalTypeInternal().getTypePtr();
3251 atype
= cast
<ArrayType
>(type
);
3253 if (type
->isConstantArrayType()) {
3254 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
3255 size
= extract_affine(ca
->getSize());
3256 array
= update_size(array
, pos
, size
);
3257 } else if (type
->isVariableArrayType()) {
3258 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
3259 size
= extract_affine(vla
->getSizeExpr());
3260 array
= update_size(array
, pos
, size
);
3263 type
= atype
->getElementType().getTypePtr();
3265 return set_upper_bounds(array
, type
, pos
+ 1);
3268 /* Construct and return a pet_array corresponding to the variable "decl".
3269 * In particular, initialize array->extent to
3271 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3273 * and then call set_upper_bounds to set the upper bounds on the indices
3274 * based on the type of the variable.
3276 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
)
3278 struct pet_array
*array
;
3279 QualType qt
= decl
->getType();
3280 const Type
*type
= qt
.getTypePtr();
3281 int depth
= array_depth(type
);
3282 QualType base
= base_type(qt
);
3287 array
= isl_calloc_type(ctx
, struct pet_array
);
3291 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
3292 dim
= isl_space_set_alloc(ctx
, 0, depth
);
3293 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
3295 array
->extent
= isl_set_nat_universe(dim
);
3297 dim
= isl_space_params_alloc(ctx
, 0);
3298 array
->context
= isl_set_universe(dim
);
3300 array
= set_upper_bounds(array
, type
, 0);
3304 name
= base
.getAsString();
3305 array
->element_type
= strdup(name
.c_str());
3306 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
3311 /* Construct a list of pet_arrays, one for each array (or scalar)
3312 * accessed inside "scop" add this list to "scop" and return the result.
3314 * The context of "scop" is updated with the intesection of
3315 * the contexts of all arrays, i.e., constraints on the parameters
3316 * that ensure that the arrays have a valid (non-negative) size.
3318 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
3321 set
<ValueDecl
*> arrays
;
3322 set
<ValueDecl
*>::iterator it
;
3324 struct pet_array
**scop_arrays
;
3329 pet_scop_collect_arrays(scop
, arrays
);
3330 if (arrays
.size() == 0)
3333 n_array
= scop
->n_array
;
3335 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
3336 n_array
+ arrays
.size());
3339 scop
->arrays
= scop_arrays
;
3341 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
3342 struct pet_array
*array
;
3343 scop
->arrays
[n_array
+ i
] = array
= extract_array(ctx
, *it
);
3344 if (!scop
->arrays
[n_array
+ i
])
3347 scop
->context
= isl_set_intersect(scop
->context
,
3348 isl_set_copy(array
->context
));
3355 pet_scop_free(scop
);
3359 /* Construct a pet_scop from the given function.
3361 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
3366 stmt
= fd
->getBody();
3369 scop
= extract(stmt
);
3372 scop
= pet_scop_detect_parameter_accesses(scop
);
3373 scop
= scan_arrays(scop
);
3374 scop
= pet_scop_gist(scop
, value_bounds
);