2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2013 Ecole Normale Superieure. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
39 #include <llvm/Support/raw_ostream.h>
40 #include <clang/AST/ASTContext.h>
41 #include <clang/AST/ASTDiagnostic.h>
42 #include <clang/AST/Expr.h>
43 #include <clang/AST/RecursiveASTVisitor.h>
46 #include <isl/space.h>
54 #include "scop_plus.h"
59 using namespace clang
;
61 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
62 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
64 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
65 SourceLocation(), var
, false, var
->getInnerLocStart(),
66 var
->getType(), VK_LValue
);
68 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
69 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
71 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
72 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
76 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
78 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
79 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
83 /* Check if the element type corresponding to the given array type
84 * has a const qualifier.
86 static bool const_base(QualType qt
)
88 const Type
*type
= qt
.getTypePtr();
90 if (type
->isPointerType())
91 return const_base(type
->getPointeeType());
92 if (type
->isArrayType()) {
93 const ArrayType
*atype
;
94 type
= type
->getCanonicalTypeInternal().getTypePtr();
95 atype
= cast
<ArrayType
>(type
);
96 return const_base(atype
->getElementType());
99 return qt
.isConstQualified();
102 /* Mark "decl" as having an unknown value in "assigned_value".
104 * If no (known or unknown) value was assigned to "decl" before,
105 * then it may have been treated as a parameter before and may
106 * therefore appear in a value assigned to another variable.
107 * If so, this assignment needs to be turned into an unknown value too.
109 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
112 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
114 it
= assigned_value
.find(decl
);
116 assigned_value
[decl
] = NULL
;
118 if (it
== assigned_value
.end())
121 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
122 isl_pw_aff
*pa
= it
->second
;
123 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
125 for (int i
= 0; i
< nparam
; ++i
) {
128 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
130 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
131 if (isl_id_get_user(id
) == decl
)
138 /* Look for any assignments to scalar variables in part of the parse
139 * tree and set assigned_value to NULL for each of them.
140 * Also reset assigned_value if the address of a scalar variable
141 * is being taken. As an exception, if the address is passed to a function
142 * that is declared to receive a const pointer, then assigned_value is
145 * This ensures that we won't use any previously stored value
146 * in the current subtree and its parents.
148 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
149 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
150 set
<UnaryOperator
*> skip
;
152 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
153 assigned_value(assigned_value
) {}
155 /* Check for "address of" operators whose value is passed
156 * to a const pointer argument and add them to "skip", so that
157 * we can skip them in VisitUnaryOperator.
159 bool VisitCallExpr(CallExpr
*expr
) {
161 fd
= expr
->getDirectCallee();
164 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
165 Expr
*arg
= expr
->getArg(i
);
167 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
168 ImplicitCastExpr
*ice
;
169 ice
= cast
<ImplicitCastExpr
>(arg
);
170 arg
= ice
->getSubExpr();
172 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
174 op
= cast
<UnaryOperator
>(arg
);
175 if (op
->getOpcode() != UO_AddrOf
)
177 if (const_base(fd
->getParamDecl(i
)->getType()))
183 bool VisitUnaryOperator(UnaryOperator
*expr
) {
188 switch (expr
->getOpcode()) {
198 if (skip
.find(expr
) != skip
.end())
201 arg
= expr
->getSubExpr();
202 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
204 ref
= cast
<DeclRefExpr
>(arg
);
205 decl
= ref
->getDecl();
206 clear_assignment(assigned_value
, decl
);
210 bool VisitBinaryOperator(BinaryOperator
*expr
) {
215 if (!expr
->isAssignmentOp())
217 lhs
= expr
->getLHS();
218 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
220 ref
= cast
<DeclRefExpr
>(lhs
);
221 decl
= ref
->getDecl();
222 clear_assignment(assigned_value
, decl
);
227 /* Keep a copy of the currently assigned values.
229 * Any variable that is assigned a value inside the current scope
230 * is removed again when we leave the scope (either because it wasn't
231 * stored in the cache or because it has a different value in the cache).
233 struct assigned_value_cache
{
234 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
235 map
<ValueDecl
*, isl_pw_aff
*> cache
;
237 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
238 assigned_value(assigned_value
), cache(assigned_value
) {}
239 ~assigned_value_cache() {
240 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
241 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
244 (cache
.find(it
->first
) != cache
.end() &&
245 cache
[it
->first
] != it
->second
))
246 cache
[it
->first
] = NULL
;
248 assigned_value
= cache
;
252 /* Insert an expression into the collection of expressions,
253 * provided it is not already in there.
254 * The isl_pw_affs are freed in the destructor.
256 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
258 std::set
<isl_pw_aff
*>::iterator it
;
260 if (expressions
.find(expr
) == expressions
.end())
261 expressions
.insert(expr
);
263 isl_pw_aff_free(expr
);
268 std::set
<isl_pw_aff
*>::iterator it
;
270 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
271 isl_pw_aff_free(*it
);
273 isl_union_map_free(value_bounds
);
276 /* Called if we found something we (currently) cannot handle.
277 * We'll provide more informative warnings later.
279 * We only actually complain if autodetect is false.
281 void PetScan::unsupported(Stmt
*stmt
, const char *msg
)
283 if (options
->autodetect
)
286 SourceLocation loc
= stmt
->getLocStart();
287 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
288 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
289 msg
? msg
: "unsupported");
290 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
293 /* Extract an integer from "expr".
295 __isl_give isl_val
*PetScan::extract_int(isl_ctx
*ctx
, IntegerLiteral
*expr
)
297 const Type
*type
= expr
->getType().getTypePtr();
298 int is_signed
= type
->hasSignedIntegerRepresentation();
299 llvm::APInt val
= expr
->getValue();
300 int is_negative
= is_signed
&& val
.isNegative();
306 v
= extract_unsigned(ctx
, val
);
313 /* Extract an integer from "val", which assumed to be non-negative.
315 __isl_give isl_val
*PetScan::extract_unsigned(isl_ctx
*ctx
,
316 const llvm::APInt
&val
)
319 const uint64_t *data
;
321 data
= val
.getRawData();
322 n
= val
.getNumWords();
323 return isl_val_int_from_chunks(ctx
, n
, sizeof(uint64_t), data
);
326 /* Extract an integer from "expr".
327 * Return NULL if "expr" does not (obviously) represent an integer.
329 __isl_give isl_val
*PetScan::extract_int(clang::ParenExpr
*expr
)
331 return extract_int(expr
->getSubExpr());
334 /* Extract an integer from "expr".
335 * Return NULL if "expr" does not (obviously) represent an integer.
337 __isl_give isl_val
*PetScan::extract_int(clang::Expr
*expr
)
339 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
340 return extract_int(ctx
, cast
<IntegerLiteral
>(expr
));
341 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
342 return extract_int(cast
<ParenExpr
>(expr
));
348 /* Extract an affine expression from the IntegerLiteral "expr".
350 __isl_give isl_pw_aff
*PetScan::extract_affine(IntegerLiteral
*expr
)
352 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
353 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
354 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
355 isl_set
*dom
= isl_set_universe(dim
);
358 v
= extract_int(expr
);
359 aff
= isl_aff_add_constant_val(aff
, v
);
361 return isl_pw_aff_alloc(dom
, aff
);
364 /* Extract an affine expression from the APInt "val", which is assumed
365 * to be non-negative.
367 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
369 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
370 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
371 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
372 isl_set
*dom
= isl_set_universe(dim
);
375 v
= extract_unsigned(ctx
, val
);
376 aff
= isl_aff_add_constant_val(aff
, v
);
378 return isl_pw_aff_alloc(dom
, aff
);
381 __isl_give isl_pw_aff
*PetScan::extract_affine(ImplicitCastExpr
*expr
)
383 return extract_affine(expr
->getSubExpr());
386 static unsigned get_type_size(ValueDecl
*decl
)
388 return decl
->getASTContext().getIntWidth(decl
->getType());
391 /* Bound parameter "pos" of "set" to the possible values of "decl".
393 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
394 unsigned pos
, ValueDecl
*decl
)
400 ctx
= isl_set_get_ctx(set
);
401 width
= get_type_size(decl
);
402 if (decl
->getType()->isUnsignedIntegerType()) {
403 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
404 bound
= isl_val_int_from_ui(ctx
, width
);
405 bound
= isl_val_2exp(bound
);
406 bound
= isl_val_sub_ui(bound
, 1);
407 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
, bound
);
409 bound
= isl_val_int_from_ui(ctx
, width
- 1);
410 bound
= isl_val_2exp(bound
);
411 bound
= isl_val_sub_ui(bound
, 1);
412 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
,
413 isl_val_copy(bound
));
414 bound
= isl_val_neg(bound
);
415 bound
= isl_val_sub_ui(bound
, 1);
416 set
= isl_set_lower_bound_val(set
, isl_dim_param
, pos
, bound
);
422 /* Extract an affine expression from the DeclRefExpr "expr".
424 * If the variable has been assigned a value, then we check whether
425 * we know what (affine) value was assigned.
426 * If so, we return this value. Otherwise we convert "expr"
427 * to an extra parameter (provided nesting_enabled is set).
429 * Otherwise, we simply return an expression that is equal
430 * to a parameter corresponding to the referenced variable.
432 __isl_give isl_pw_aff
*PetScan::extract_affine(DeclRefExpr
*expr
)
434 ValueDecl
*decl
= expr
->getDecl();
435 const Type
*type
= decl
->getType().getTypePtr();
441 if (!type
->isIntegerType()) {
446 if (assigned_value
.find(decl
) != assigned_value
.end()) {
447 if (assigned_value
[decl
])
448 return isl_pw_aff_copy(assigned_value
[decl
]);
450 return nested_access(expr
);
453 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
454 dim
= isl_space_params_alloc(ctx
, 1);
456 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
458 dom
= isl_set_universe(isl_space_copy(dim
));
459 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
460 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
462 return isl_pw_aff_alloc(dom
, aff
);
465 /* Extract an affine expression from an integer division operation.
466 * In particular, if "expr" is lhs/rhs, then return
468 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
470 * The second argument (rhs) is required to be a (positive) integer constant.
472 __isl_give isl_pw_aff
*PetScan::extract_affine_div(BinaryOperator
*expr
)
475 isl_pw_aff
*rhs
, *lhs
;
477 rhs
= extract_affine(expr
->getRHS());
478 is_cst
= isl_pw_aff_is_cst(rhs
);
479 if (is_cst
< 0 || !is_cst
) {
480 isl_pw_aff_free(rhs
);
486 lhs
= extract_affine(expr
->getLHS());
488 return isl_pw_aff_tdiv_q(lhs
, rhs
);
491 /* Extract an affine expression from a modulo operation.
492 * In particular, if "expr" is lhs/rhs, then return
494 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
496 * The second argument (rhs) is required to be a (positive) integer constant.
498 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
501 isl_pw_aff
*rhs
, *lhs
;
503 rhs
= extract_affine(expr
->getRHS());
504 is_cst
= isl_pw_aff_is_cst(rhs
);
505 if (is_cst
< 0 || !is_cst
) {
506 isl_pw_aff_free(rhs
);
512 lhs
= extract_affine(expr
->getLHS());
514 return isl_pw_aff_tdiv_r(lhs
, rhs
);
517 /* Extract an affine expression from a multiplication operation.
518 * This is only allowed if at least one of the two arguments
519 * is a (piecewise) constant.
521 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
526 lhs
= extract_affine(expr
->getLHS());
527 rhs
= extract_affine(expr
->getRHS());
529 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
530 isl_pw_aff_free(lhs
);
531 isl_pw_aff_free(rhs
);
536 return isl_pw_aff_mul(lhs
, rhs
);
539 /* Extract an affine expression from an addition or subtraction operation.
541 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
546 lhs
= extract_affine(expr
->getLHS());
547 rhs
= extract_affine(expr
->getRHS());
549 switch (expr
->getOpcode()) {
551 return isl_pw_aff_add(lhs
, rhs
);
553 return isl_pw_aff_sub(lhs
, rhs
);
555 isl_pw_aff_free(lhs
);
556 isl_pw_aff_free(rhs
);
566 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
572 ctx
= isl_pw_aff_get_ctx(pwaff
);
573 mod
= isl_val_int_from_ui(ctx
, width
);
574 mod
= isl_val_2exp(mod
);
576 pwaff
= isl_pw_aff_mod_val(pwaff
, mod
);
581 /* Limit the domain of "pwaff" to those elements where the function
584 * 2^{width-1} <= pwaff < 2^{width-1}
586 static __isl_give isl_pw_aff
*avoid_overflow(__isl_take isl_pw_aff
*pwaff
,
591 isl_space
*space
= isl_pw_aff_get_domain_space(pwaff
);
592 isl_local_space
*ls
= isl_local_space_from_space(space
);
597 ctx
= isl_pw_aff_get_ctx(pwaff
);
598 v
= isl_val_int_from_ui(ctx
, width
- 1);
601 bound
= isl_aff_zero_on_domain(ls
);
602 bound
= isl_aff_add_constant_val(bound
, v
);
603 b
= isl_pw_aff_from_aff(bound
);
605 dom
= isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff
), isl_pw_aff_copy(b
));
606 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
608 b
= isl_pw_aff_neg(b
);
609 dom
= isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff
), b
);
610 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
615 /* Handle potential overflows on signed computations.
617 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
618 * the we adjust the domain of "pa" to avoid overflows.
620 __isl_give isl_pw_aff
*PetScan::signed_overflow(__isl_take isl_pw_aff
*pa
,
623 if (options
->signed_overflow
== PET_OVERFLOW_AVOID
)
624 pa
= avoid_overflow(pa
, width
);
629 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
631 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
632 __isl_take isl_set
*dom
)
635 pa
= isl_set_indicator_function(set
);
636 pa
= isl_pw_aff_intersect_domain(pa
, dom
);
640 /* Extract an affine expression from some binary operations.
641 * If the result of the expression is unsigned, then we wrap it
642 * based on the size of the type. Otherwise, we ensure that
643 * no overflow occurs.
645 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
650 switch (expr
->getOpcode()) {
653 res
= extract_affine_add(expr
);
656 res
= extract_affine_div(expr
);
659 res
= extract_affine_mod(expr
);
662 res
= extract_affine_mul(expr
);
672 return extract_condition(expr
);
678 width
= ast_context
.getIntWidth(expr
->getType());
679 if (expr
->getType()->isUnsignedIntegerType())
680 res
= wrap(res
, width
);
682 res
= signed_overflow(res
, width
);
687 /* Extract an affine expression from a negation operation.
689 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
691 if (expr
->getOpcode() == UO_Minus
)
692 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
693 if (expr
->getOpcode() == UO_LNot
)
694 return extract_condition(expr
);
700 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
702 return extract_affine(expr
->getSubExpr());
705 /* Extract an affine expression from some special function calls.
706 * In particular, we handle "min", "max", "ceild" and "floord".
707 * In case of the latter two, the second argument needs to be
708 * a (positive) integer constant.
710 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
714 isl_pw_aff
*aff1
, *aff2
;
716 fd
= expr
->getDirectCallee();
722 name
= fd
->getDeclName().getAsString();
723 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
724 !(expr
->getNumArgs() == 2 && name
== "max") &&
725 !(expr
->getNumArgs() == 2 && name
== "floord") &&
726 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
731 if (name
== "min" || name
== "max") {
732 aff1
= extract_affine(expr
->getArg(0));
733 aff2
= extract_affine(expr
->getArg(1));
736 aff1
= isl_pw_aff_min(aff1
, aff2
);
738 aff1
= isl_pw_aff_max(aff1
, aff2
);
739 } else if (name
== "floord" || name
== "ceild") {
741 Expr
*arg2
= expr
->getArg(1);
743 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
747 aff1
= extract_affine(expr
->getArg(0));
748 v
= extract_int(cast
<IntegerLiteral
>(arg2
));
749 aff1
= isl_pw_aff_scale_down_val(aff1
, v
);
750 if (name
== "floord")
751 aff1
= isl_pw_aff_floor(aff1
);
753 aff1
= isl_pw_aff_ceil(aff1
);
762 /* This method is called when we come across an access that is
763 * nested in what is supposed to be an affine expression.
764 * If nesting is allowed, we return a new parameter that corresponds
765 * to this nested access. Otherwise, we simply complain.
767 * Note that we currently don't allow nested accesses themselves
768 * to contain any nested accesses, so we check if we can extract
769 * the access without any nesting and complain if we can't.
771 * The new parameter is resolved in resolve_nested.
773 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
779 isl_multi_pw_aff
*index
;
781 if (!nesting_enabled
) {
786 allow_nested
= false;
787 index
= extract_index(expr
);
793 isl_multi_pw_aff_free(index
);
795 id
= isl_id_alloc(ctx
, NULL
, expr
);
796 dim
= isl_space_params_alloc(ctx
, 1);
798 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
800 dom
= isl_set_universe(isl_space_copy(dim
));
801 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
802 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
804 return isl_pw_aff_alloc(dom
, aff
);
807 /* Affine expressions are not supposed to contain array accesses,
808 * but if nesting is allowed, we return a parameter corresponding
809 * to the array access.
811 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
813 return nested_access(expr
);
816 /* Extract an affine expression from a conditional operation.
818 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
820 isl_pw_aff
*cond
, *lhs
, *rhs
;
822 cond
= extract_condition(expr
->getCond());
823 lhs
= extract_affine(expr
->getTrueExpr());
824 rhs
= extract_affine(expr
->getFalseExpr());
826 return isl_pw_aff_cond(cond
, lhs
, rhs
);
829 /* Extract an affine expression, if possible, from "expr".
830 * Otherwise return NULL.
832 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
834 switch (expr
->getStmtClass()) {
835 case Stmt::ImplicitCastExprClass
:
836 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
837 case Stmt::IntegerLiteralClass
:
838 return extract_affine(cast
<IntegerLiteral
>(expr
));
839 case Stmt::DeclRefExprClass
:
840 return extract_affine(cast
<DeclRefExpr
>(expr
));
841 case Stmt::BinaryOperatorClass
:
842 return extract_affine(cast
<BinaryOperator
>(expr
));
843 case Stmt::UnaryOperatorClass
:
844 return extract_affine(cast
<UnaryOperator
>(expr
));
845 case Stmt::ParenExprClass
:
846 return extract_affine(cast
<ParenExpr
>(expr
));
847 case Stmt::CallExprClass
:
848 return extract_affine(cast
<CallExpr
>(expr
));
849 case Stmt::ArraySubscriptExprClass
:
850 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
851 case Stmt::ConditionalOperatorClass
:
852 return extract_affine(cast
<ConditionalOperator
>(expr
));
859 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ImplicitCastExpr
*expr
)
861 return extract_index(expr
->getSubExpr());
864 /* Return the depth of an array of the given type.
866 static int array_depth(const Type
*type
)
868 if (type
->isPointerType())
869 return 1 + array_depth(type
->getPointeeType().getTypePtr());
870 if (type
->isArrayType()) {
871 const ArrayType
*atype
;
872 type
= type
->getCanonicalTypeInternal().getTypePtr();
873 atype
= cast
<ArrayType
>(type
);
874 return 1 + array_depth(atype
->getElementType().getTypePtr());
879 /* Return the depth of the array accessed by the index expression "index".
880 * If "index" is an affine expression, i.e., if it does not access
881 * any array, then return 1.
883 static int extract_depth(__isl_keep isl_multi_pw_aff
*index
)
891 if (!isl_multi_pw_aff_has_tuple_id(index
, isl_dim_out
))
894 id
= isl_multi_pw_aff_get_tuple_id(index
, isl_dim_out
);
897 decl
= (ValueDecl
*) isl_id_get_user(id
);
900 return array_depth(decl
->getType().getTypePtr());
903 /* Extract an index expression from a reference to a variable.
904 * If the variable has name "A", then the returned index expression
909 __isl_give isl_multi_pw_aff
*PetScan::extract_index(DeclRefExpr
*expr
)
911 return extract_index(expr
->getDecl());
914 /* Extract an index expression from a variable.
915 * If the variable has name "A", then the returned index expression
920 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ValueDecl
*decl
)
922 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
923 isl_space
*space
= isl_space_alloc(ctx
, 0, 0, 0);
925 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
927 return isl_multi_pw_aff_zero(space
);
930 /* Extract an index expression from an integer contant.
931 * If the value of the constant is "v", then the returned access relation
936 __isl_give isl_multi_pw_aff
*PetScan::extract_index(IntegerLiteral
*expr
)
938 isl_multi_pw_aff
*mpa
;
940 mpa
= isl_multi_pw_aff_from_pw_aff(extract_affine(expr
));
941 mpa
= isl_multi_pw_aff_from_range(mpa
);
945 /* Try and extract an index expression from the given Expr.
946 * Return NULL if it doesn't work out.
948 __isl_give isl_multi_pw_aff
*PetScan::extract_index(Expr
*expr
)
950 switch (expr
->getStmtClass()) {
951 case Stmt::ImplicitCastExprClass
:
952 return extract_index(cast
<ImplicitCastExpr
>(expr
));
953 case Stmt::DeclRefExprClass
:
954 return extract_index(cast
<DeclRefExpr
>(expr
));
955 case Stmt::ArraySubscriptExprClass
:
956 return extract_index(cast
<ArraySubscriptExpr
>(expr
));
957 case Stmt::IntegerLiteralClass
:
958 return extract_index(cast
<IntegerLiteral
>(expr
));
965 /* Given a partial index expression "base" and an extra index "index",
966 * append the extra index to "base" and return the result.
967 * Additionally, add the constraints that the extra index is non-negative.
969 static __isl_give isl_multi_pw_aff
*subscript(__isl_take isl_multi_pw_aff
*base
,
970 __isl_take isl_pw_aff
*index
)
974 isl_multi_pw_aff
*access
;
976 id
= isl_multi_pw_aff_get_tuple_id(base
, isl_dim_set
);
977 index
= isl_pw_aff_from_range(index
);
978 domain
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(index
));
979 index
= isl_pw_aff_intersect_domain(index
, domain
);
980 access
= isl_multi_pw_aff_from_pw_aff(index
);
981 access
= isl_multi_pw_aff_flat_range_product(base
, access
);
982 access
= isl_multi_pw_aff_set_tuple_id(access
, isl_dim_set
, id
);
987 /* Extract an index expression from the given array subscript expression.
988 * If nesting is allowed in general, then we turn it on while
989 * examining the index expression.
991 * We first extract an index expression from the base.
992 * This will result in an index expression with a range that corresponds
993 * to the earlier indices.
994 * We then extract the current index, restrict its domain
995 * to those values that result in a non-negative index and
996 * append the index to the base index expression.
998 __isl_give isl_multi_pw_aff
*PetScan::extract_index(ArraySubscriptExpr
*expr
)
1000 Expr
*base
= expr
->getBase();
1001 Expr
*idx
= expr
->getIdx();
1003 isl_multi_pw_aff
*base_access
;
1004 isl_multi_pw_aff
*access
;
1005 bool save_nesting
= nesting_enabled
;
1007 nesting_enabled
= allow_nested
;
1009 base_access
= extract_index(base
);
1010 index
= extract_affine(idx
);
1012 nesting_enabled
= save_nesting
;
1014 access
= subscript(base_access
, index
);
1019 /* Check if "expr" calls function "minmax" with two arguments and if so
1020 * make lhs and rhs refer to these two arguments.
1022 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
1028 if (expr
->getStmtClass() != Stmt::CallExprClass
)
1031 call
= cast
<CallExpr
>(expr
);
1032 fd
= call
->getDirectCallee();
1036 if (call
->getNumArgs() != 2)
1039 name
= fd
->getDeclName().getAsString();
1043 lhs
= call
->getArg(0);
1044 rhs
= call
->getArg(1);
1049 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1050 * lhs and rhs refer to the two arguments.
1052 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1054 return is_minmax(expr
, "min", lhs
, rhs
);
1057 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1058 * lhs and rhs refer to the two arguments.
1060 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1062 return is_minmax(expr
, "max", lhs
, rhs
);
1065 /* Return "lhs && rhs", defined on the shared definition domain.
1067 static __isl_give isl_pw_aff
*pw_aff_and(__isl_take isl_pw_aff
*lhs
,
1068 __isl_take isl_pw_aff
*rhs
)
1073 dom
= isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs
)),
1074 isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1075 cond
= isl_set_intersect(isl_pw_aff_non_zero_set(lhs
),
1076 isl_pw_aff_non_zero_set(rhs
));
1077 return indicator_function(cond
, dom
);
1080 /* Return "lhs && rhs", with shortcut semantics.
1081 * That is, if lhs is false, then the result is defined even if rhs is not.
1082 * In practice, we compute lhs ? rhs : lhs.
1084 static __isl_give isl_pw_aff
*pw_aff_and_then(__isl_take isl_pw_aff
*lhs
,
1085 __isl_take isl_pw_aff
*rhs
)
1087 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), rhs
, lhs
);
1090 /* Return "lhs || rhs", with shortcut semantics.
1091 * That is, if lhs is true, then the result is defined even if rhs is not.
1092 * In practice, we compute lhs ? lhs : rhs.
1094 static __isl_give isl_pw_aff
*pw_aff_or_else(__isl_take isl_pw_aff
*lhs
,
1095 __isl_take isl_pw_aff
*rhs
)
1097 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), lhs
, rhs
);
1100 /* Extract an affine expressions representing the comparison "LHS op RHS"
1101 * "comp" is the original statement that "LHS op RHS" is derived from
1102 * and is used for diagnostics.
1104 * If the comparison is of the form
1108 * then the expression is constructed as the conjunction of
1113 * A similar optimization is performed for max(a,b) <= c.
1114 * We do this because that will lead to simpler representations
1115 * of the expression.
1116 * If isl is ever enhanced to explicitly deal with min and max expressions,
1117 * this optimization can be removed.
1119 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
1120 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
1129 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
1131 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
1133 if (op
== BO_LT
|| op
== BO_LE
) {
1134 Expr
*expr1
, *expr2
;
1135 if (is_min(RHS
, expr1
, expr2
)) {
1136 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
1137 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
1138 return pw_aff_and(lhs
, rhs
);
1140 if (is_max(LHS
, expr1
, expr2
)) {
1141 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
1142 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
1143 return pw_aff_and(lhs
, rhs
);
1147 lhs
= extract_affine(LHS
);
1148 rhs
= extract_affine(RHS
);
1150 dom
= isl_pw_aff_domain(isl_pw_aff_copy(lhs
));
1151 dom
= isl_set_intersect(dom
, isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1155 cond
= isl_pw_aff_lt_set(lhs
, rhs
);
1158 cond
= isl_pw_aff_le_set(lhs
, rhs
);
1161 cond
= isl_pw_aff_eq_set(lhs
, rhs
);
1164 cond
= isl_pw_aff_ne_set(lhs
, rhs
);
1167 isl_pw_aff_free(lhs
);
1168 isl_pw_aff_free(rhs
);
1174 cond
= isl_set_coalesce(cond
);
1175 res
= indicator_function(cond
, dom
);
1180 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
1182 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1183 comp
->getRHS(), comp
);
1186 /* Extract an affine expression representing the negation (logical not)
1187 * of a subexpression.
1189 __isl_give isl_pw_aff
*PetScan::extract_boolean(UnaryOperator
*op
)
1191 isl_set
*set_cond
, *dom
;
1192 isl_pw_aff
*cond
, *res
;
1194 cond
= extract_condition(op
->getSubExpr());
1196 dom
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
1198 set_cond
= isl_pw_aff_zero_set(cond
);
1200 res
= indicator_function(set_cond
, dom
);
1205 /* Extract an affine expression representing the disjunction (logical or)
1206 * or conjunction (logical and) of two subexpressions.
1208 __isl_give isl_pw_aff
*PetScan::extract_boolean(BinaryOperator
*comp
)
1210 isl_pw_aff
*lhs
, *rhs
;
1212 lhs
= extract_condition(comp
->getLHS());
1213 rhs
= extract_condition(comp
->getRHS());
1215 switch (comp
->getOpcode()) {
1217 return pw_aff_and_then(lhs
, rhs
);
1219 return pw_aff_or_else(lhs
, rhs
);
1221 isl_pw_aff_free(lhs
);
1222 isl_pw_aff_free(rhs
);
1229 __isl_give isl_pw_aff
*PetScan::extract_condition(UnaryOperator
*expr
)
1231 switch (expr
->getOpcode()) {
1233 return extract_boolean(expr
);
1240 /* Extract the affine expression "expr != 0 ? 1 : 0".
1242 __isl_give isl_pw_aff
*PetScan::extract_implicit_condition(Expr
*expr
)
1247 res
= extract_affine(expr
);
1249 dom
= isl_pw_aff_domain(isl_pw_aff_copy(res
));
1250 set
= isl_pw_aff_non_zero_set(res
);
1252 res
= indicator_function(set
, dom
);
1257 /* Extract an affine expression from a boolean expression.
1258 * In particular, return the expression "expr ? 1 : 0".
1260 * If the expression doesn't look like a condition, we assume it
1261 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1263 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
1265 BinaryOperator
*comp
;
1268 isl_set
*u
= isl_set_universe(isl_space_params_alloc(ctx
, 0));
1269 return indicator_function(u
, isl_set_copy(u
));
1272 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1273 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1275 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1276 return extract_condition(cast
<UnaryOperator
>(expr
));
1278 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1279 return extract_implicit_condition(expr
);
1281 comp
= cast
<BinaryOperator
>(expr
);
1282 switch (comp
->getOpcode()) {
1289 return extract_comparison(comp
);
1292 return extract_boolean(comp
);
1294 return extract_implicit_condition(expr
);
1298 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
1302 return pet_op_minus
;
1304 return pet_op_post_inc
;
1306 return pet_op_post_dec
;
1308 return pet_op_pre_inc
;
1310 return pet_op_pre_dec
;
1316 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
1320 return pet_op_add_assign
;
1322 return pet_op_sub_assign
;
1324 return pet_op_mul_assign
;
1326 return pet_op_div_assign
;
1328 return pet_op_assign
;
1352 /* Construct a pet_expr representing a unary operator expression.
1354 struct pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1356 struct pet_expr
*arg
;
1357 enum pet_op_type op
;
1359 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1360 if (op
== pet_op_last
) {
1365 arg
= extract_expr(expr
->getSubExpr());
1367 if (expr
->isIncrementDecrementOp() &&
1368 arg
&& arg
->type
== pet_expr_access
) {
1373 return pet_expr_new_unary(ctx
, op
, arg
);
1376 /* Mark the given access pet_expr as a write.
1377 * If a scalar is being accessed, then mark its value
1378 * as unknown in assigned_value.
1380 void PetScan::mark_write(struct pet_expr
*access
)
1388 access
->acc
.write
= 1;
1389 access
->acc
.read
= 0;
1391 if (!pet_expr_is_scalar_access(access
))
1394 id
= pet_expr_access_get_id(access
);
1395 decl
= (ValueDecl
*) isl_id_get_user(id
);
1396 clear_assignment(assigned_value
, decl
);
1400 /* Assign "rhs" to "lhs".
1402 * In particular, if "lhs" is a scalar variable, then mark
1403 * the variable as having been assigned. If, furthermore, "rhs"
1404 * is an affine expression, then keep track of this value in assigned_value
1405 * so that we can plug it in when we later come across the same variable.
1407 void PetScan::assign(struct pet_expr
*lhs
, Expr
*rhs
)
1415 if (!pet_expr_is_scalar_access(lhs
))
1418 id
= pet_expr_access_get_id(lhs
);
1419 decl
= (ValueDecl
*) isl_id_get_user(id
);
1422 pa
= try_extract_affine(rhs
);
1423 clear_assignment(assigned_value
, decl
);
1426 assigned_value
[decl
] = pa
;
1427 insert_expression(pa
);
1430 /* Construct a pet_expr representing a binary operator expression.
1432 * If the top level operator is an assignment and the LHS is an access,
1433 * then we mark that access as a write. If the operator is a compound
1434 * assignment, the access is marked as both a read and a write.
1436 * If "expr" assigns something to a scalar variable, then we mark
1437 * the variable as having been assigned. If, furthermore, the expression
1438 * is affine, then keep track of this value in assigned_value
1439 * so that we can plug it in when we later come across the same variable.
1441 struct pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1443 struct pet_expr
*lhs
, *rhs
;
1444 enum pet_op_type op
;
1446 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1447 if (op
== pet_op_last
) {
1452 lhs
= extract_expr(expr
->getLHS());
1453 rhs
= extract_expr(expr
->getRHS());
1455 if (expr
->isAssignmentOp() && lhs
&& lhs
->type
== pet_expr_access
) {
1457 if (expr
->isCompoundAssignmentOp())
1461 if (expr
->getOpcode() == BO_Assign
)
1462 assign(lhs
, expr
->getRHS());
1464 return pet_expr_new_binary(ctx
, op
, lhs
, rhs
);
1467 /* Construct a pet_scop with a single statement killing the entire
1470 struct pet_scop
*PetScan::kill(Stmt
*stmt
, struct pet_array
*array
)
1474 isl_multi_pw_aff
*index
;
1476 struct pet_expr
*expr
;
1480 access
= isl_map_from_range(isl_set_copy(array
->extent
));
1481 id
= isl_set_get_tuple_id(array
->extent
);
1482 space
= isl_space_alloc(ctx
, 0, 0, 0);
1483 space
= isl_space_set_tuple_id(space
, isl_dim_out
, id
);
1484 index
= isl_multi_pw_aff_zero(space
);
1485 expr
= pet_expr_kill_from_access_and_index(access
, index
);
1486 return extract(stmt
, expr
);
1489 /* Construct a pet_scop for a (single) variable declaration.
1491 * The scop contains the variable being declared (as an array)
1492 * and a statement killing the array.
1494 * If the variable is initialized in the AST, then the scop
1495 * also contains an assignment to the variable.
1497 struct pet_scop
*PetScan::extract(DeclStmt
*stmt
)
1501 struct pet_expr
*lhs
, *rhs
, *pe
;
1502 struct pet_scop
*scop_decl
, *scop
;
1503 struct pet_array
*array
;
1505 if (!stmt
->isSingleDecl()) {
1510 decl
= stmt
->getSingleDecl();
1511 vd
= cast
<VarDecl
>(decl
);
1513 array
= extract_array(ctx
, vd
);
1515 array
->declared
= 1;
1516 scop_decl
= kill(stmt
, array
);
1517 scop_decl
= pet_scop_add_array(scop_decl
, array
);
1522 lhs
= extract_access_expr(vd
);
1523 rhs
= extract_expr(vd
->getInit());
1526 assign(lhs
, vd
->getInit());
1528 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, lhs
, rhs
);
1529 scop
= extract(stmt
, pe
);
1531 scop_decl
= pet_scop_prefix(scop_decl
, 0);
1532 scop
= pet_scop_prefix(scop
, 1);
1534 scop
= pet_scop_add_seq(ctx
, scop_decl
, scop
);
1539 /* Construct a pet_expr representing a conditional operation.
1541 * We first try to extract the condition as an affine expression.
1542 * If that fails, we construct a pet_expr tree representing the condition.
1544 struct pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1546 struct pet_expr
*cond
, *lhs
, *rhs
;
1549 pa
= try_extract_affine(expr
->getCond());
1551 isl_multi_pw_aff
*test
= isl_multi_pw_aff_from_pw_aff(pa
);
1552 test
= isl_multi_pw_aff_from_range(test
);
1553 cond
= pet_expr_from_index(test
);
1555 cond
= extract_expr(expr
->getCond());
1556 lhs
= extract_expr(expr
->getTrueExpr());
1557 rhs
= extract_expr(expr
->getFalseExpr());
1559 return pet_expr_new_ternary(ctx
, cond
, lhs
, rhs
);
1562 struct pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1564 return extract_expr(expr
->getSubExpr());
1567 /* Construct a pet_expr representing a floating point value.
1569 * If the floating point literal does not appear in a macro,
1570 * then we use the original representation in the source code
1571 * as the string representation. Otherwise, we use the pretty
1572 * printer to produce a string representation.
1574 struct pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1578 const LangOptions
&LO
= PP
.getLangOpts();
1579 SourceLocation loc
= expr
->getLocation();
1581 if (!loc
.isMacroID()) {
1582 SourceManager
&SM
= PP
.getSourceManager();
1583 unsigned len
= Lexer::MeasureTokenLength(loc
, SM
, LO
);
1584 s
= string(SM
.getCharacterData(loc
), len
);
1586 llvm::raw_string_ostream
S(s
);
1587 expr
->printPretty(S
, 0, PrintingPolicy(LO
));
1590 d
= expr
->getValueAsApproximateDouble();
1591 return pet_expr_new_double(ctx
, d
, s
.c_str());
1594 /* Extract an index expression from "expr" and then convert it into
1595 * an access pet_expr.
1597 struct pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1599 isl_multi_pw_aff
*index
;
1600 struct pet_expr
*pe
;
1603 index
= extract_index(expr
);
1604 depth
= extract_depth(index
);
1606 pe
= pet_expr_from_index_and_depth(index
, depth
);
1611 /* Extract an index expression from "decl" and then convert it into
1612 * an access pet_expr.
1614 struct pet_expr
*PetScan::extract_access_expr(ValueDecl
*decl
)
1616 isl_multi_pw_aff
*index
;
1617 struct pet_expr
*pe
;
1620 index
= extract_index(decl
);
1621 depth
= extract_depth(index
);
1623 pe
= pet_expr_from_index_and_depth(index
, depth
);
1628 struct pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1630 return extract_expr(expr
->getSubExpr());
1633 /* Construct a pet_expr representing a function call.
1635 * If we are passing along a pointer to an array element
1636 * or an entire row or even higher dimensional slice of an array,
1637 * then the function being called may write into the array.
1639 * We assume here that if the function is declared to take a pointer
1640 * to a const type, then the function will perform a read
1641 * and that otherwise, it will perform a write.
1643 struct pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1645 struct pet_expr
*res
= NULL
;
1649 fd
= expr
->getDirectCallee();
1655 name
= fd
->getDeclName().getAsString();
1656 res
= pet_expr_new_call(ctx
, name
.c_str(), expr
->getNumArgs());
1660 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
1661 Expr
*arg
= expr
->getArg(i
);
1665 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1666 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(arg
);
1667 arg
= ice
->getSubExpr();
1669 if (arg
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1670 UnaryOperator
*op
= cast
<UnaryOperator
>(arg
);
1671 if (op
->getOpcode() == UO_AddrOf
) {
1673 arg
= op
->getSubExpr();
1676 res
->args
[i
] = PetScan::extract_expr(arg
);
1677 main_arg
= res
->args
[i
];
1679 res
->args
[i
] = pet_expr_new_unary(ctx
,
1680 pet_op_address_of
, res
->args
[i
]);
1683 if (arg
->getStmtClass() == Stmt::ArraySubscriptExprClass
&&
1684 array_depth(arg
->getType().getTypePtr()) > 0)
1686 if (is_addr
&& main_arg
->type
== pet_expr_access
) {
1688 if (!fd
->hasPrototype()) {
1689 unsupported(expr
, "prototype required");
1692 parm
= fd
->getParamDecl(i
);
1693 if (!const_base(parm
->getType()))
1694 mark_write(main_arg
);
1704 /* Construct a pet_expr representing a (C style) cast.
1706 struct pet_expr
*PetScan::extract_expr(CStyleCastExpr
*expr
)
1708 struct pet_expr
*arg
;
1711 arg
= extract_expr(expr
->getSubExpr());
1715 type
= expr
->getTypeAsWritten();
1716 return pet_expr_new_cast(ctx
, type
.getAsString().c_str(), arg
);
1719 /* Try and onstruct a pet_expr representing "expr".
1721 struct pet_expr
*PetScan::extract_expr(Expr
*expr
)
1723 switch (expr
->getStmtClass()) {
1724 case Stmt::UnaryOperatorClass
:
1725 return extract_expr(cast
<UnaryOperator
>(expr
));
1726 case Stmt::CompoundAssignOperatorClass
:
1727 case Stmt::BinaryOperatorClass
:
1728 return extract_expr(cast
<BinaryOperator
>(expr
));
1729 case Stmt::ImplicitCastExprClass
:
1730 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1731 case Stmt::ArraySubscriptExprClass
:
1732 case Stmt::DeclRefExprClass
:
1733 case Stmt::IntegerLiteralClass
:
1734 return extract_access_expr(expr
);
1735 case Stmt::FloatingLiteralClass
:
1736 return extract_expr(cast
<FloatingLiteral
>(expr
));
1737 case Stmt::ParenExprClass
:
1738 return extract_expr(cast
<ParenExpr
>(expr
));
1739 case Stmt::ConditionalOperatorClass
:
1740 return extract_expr(cast
<ConditionalOperator
>(expr
));
1741 case Stmt::CallExprClass
:
1742 return extract_expr(cast
<CallExpr
>(expr
));
1743 case Stmt::CStyleCastExprClass
:
1744 return extract_expr(cast
<CStyleCastExpr
>(expr
));
1751 /* Check if the given initialization statement is an assignment.
1752 * If so, return that assignment. Otherwise return NULL.
1754 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1756 BinaryOperator
*ass
;
1758 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1761 ass
= cast
<BinaryOperator
>(init
);
1762 if (ass
->getOpcode() != BO_Assign
)
1768 /* Check if the given initialization statement is a declaration
1769 * of a single variable.
1770 * If so, return that declaration. Otherwise return NULL.
1772 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1776 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1779 decl
= cast
<DeclStmt
>(init
);
1781 if (!decl
->isSingleDecl())
1784 return decl
->getSingleDecl();
1787 /* Given the assignment operator in the initialization of a for loop,
1788 * extract the induction variable, i.e., the (integer)variable being
1791 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1798 lhs
= init
->getLHS();
1799 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1804 ref
= cast
<DeclRefExpr
>(lhs
);
1805 decl
= ref
->getDecl();
1806 type
= decl
->getType().getTypePtr();
1808 if (!type
->isIntegerType()) {
1816 /* Given the initialization statement of a for loop and the single
1817 * declaration in this initialization statement,
1818 * extract the induction variable, i.e., the (integer) variable being
1821 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1825 vd
= cast
<VarDecl
>(decl
);
1827 const QualType type
= vd
->getType();
1828 if (!type
->isIntegerType()) {
1833 if (!vd
->getInit()) {
1841 /* Check that op is of the form iv++ or iv--.
1842 * Return an affine expression "1" or "-1" accordingly.
1844 __isl_give isl_pw_aff
*PetScan::extract_unary_increment(
1845 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1852 if (!op
->isIncrementDecrementOp()) {
1857 sub
= op
->getSubExpr();
1858 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1863 ref
= cast
<DeclRefExpr
>(sub
);
1864 if (ref
->getDecl() != iv
) {
1869 space
= isl_space_params_alloc(ctx
, 0);
1870 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
1872 if (op
->isIncrementOp())
1873 aff
= isl_aff_add_constant_si(aff
, 1);
1875 aff
= isl_aff_add_constant_si(aff
, -1);
1877 return isl_pw_aff_from_aff(aff
);
1880 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1881 * has a single constant expression, then put this constant in *user.
1882 * The caller is assumed to have checked that this function will
1883 * be called exactly once.
1885 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
1888 isl_val
**inc
= (isl_val
**)user
;
1891 if (isl_aff_is_cst(aff
))
1892 *inc
= isl_aff_get_constant_val(aff
);
1902 /* Check if op is of the form
1906 * and return inc as an affine expression.
1908 * We extract an affine expression from the RHS, subtract iv and return
1911 __isl_give isl_pw_aff
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1912 clang::ValueDecl
*iv
)
1921 if (op
->getOpcode() != BO_Assign
) {
1927 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1932 ref
= cast
<DeclRefExpr
>(lhs
);
1933 if (ref
->getDecl() != iv
) {
1938 val
= extract_affine(op
->getRHS());
1940 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1942 dim
= isl_space_params_alloc(ctx
, 1);
1943 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1944 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1945 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1947 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
1952 /* Check that op is of the form iv += cst or iv -= cst
1953 * and return an affine expression corresponding oto cst or -cst accordingly.
1955 __isl_give isl_pw_aff
*PetScan::extract_compound_increment(
1956 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1962 BinaryOperatorKind opcode
;
1964 opcode
= op
->getOpcode();
1965 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1969 if (opcode
== BO_SubAssign
)
1973 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1978 ref
= cast
<DeclRefExpr
>(lhs
);
1979 if (ref
->getDecl() != iv
) {
1984 val
= extract_affine(op
->getRHS());
1986 val
= isl_pw_aff_neg(val
);
1991 /* Check that the increment of the given for loop increments
1992 * (or decrements) the induction variable "iv" and return
1993 * the increment as an affine expression if successful.
1995 __isl_give isl_pw_aff
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1998 Stmt
*inc
= stmt
->getInc();
2005 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
2006 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
2007 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
2008 return extract_compound_increment(
2009 cast
<CompoundAssignOperator
>(inc
), iv
);
2010 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
2011 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
2017 /* Embed the given iteration domain in an extra outer loop
2018 * with induction variable "var".
2019 * If this variable appeared as a parameter in the constraints,
2020 * it is replaced by the new outermost dimension.
2022 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
2023 __isl_take isl_id
*var
)
2027 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
2028 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
2030 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
2031 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2038 /* Return those elements in the space of "cond" that come after
2039 * (based on "sign") an element in "cond".
2041 static __isl_give isl_set
*after(__isl_take isl_set
*cond
, int sign
)
2043 isl_map
*previous_to_this
;
2046 previous_to_this
= isl_map_lex_lt(isl_set_get_space(cond
));
2048 previous_to_this
= isl_map_lex_gt(isl_set_get_space(cond
));
2050 cond
= isl_set_apply(cond
, previous_to_this
);
2055 /* Create the infinite iteration domain
2057 * { [id] : id >= 0 }
2059 * If "scop" has an affine skip of type pet_skip_later,
2060 * then remove those iterations i that have an earlier iteration
2061 * where the skip condition is satisfied, meaning that iteration i
2063 * Since we are dealing with a loop without loop iterator,
2064 * the skip condition cannot refer to the current loop iterator and
2065 * so effectively, the returned set is of the form
2067 * { [0]; [id] : id >= 1 and not skip }
2069 static __isl_give isl_set
*infinite_domain(__isl_take isl_id
*id
,
2070 struct pet_scop
*scop
)
2072 isl_ctx
*ctx
= isl_id_get_ctx(id
);
2076 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
2077 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, id
);
2079 if (!pet_scop_has_affine_skip(scop
, pet_skip_later
))
2082 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
2083 skip
= embed(skip
, isl_id_copy(id
));
2084 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2085 domain
= isl_set_subtract(domain
, after(skip
, 1));
2090 /* Create an identity affine expression on the space containing "domain",
2091 * which is assumed to be one-dimensional.
2093 static __isl_give isl_aff
*identity_aff(__isl_keep isl_set
*domain
)
2095 isl_local_space
*ls
;
2097 ls
= isl_local_space_from_space(isl_set_get_space(domain
));
2098 return isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
2101 /* Create an affine expression that maps elements
2102 * of a single-dimensional array "id_test" to the previous element
2103 * (according to "inc"), provided this element belongs to "domain".
2104 * That is, create the affine expression
2106 * { id[x] -> id[x - inc] : x - inc in domain }
2108 static __isl_give isl_multi_pw_aff
*map_to_previous(__isl_take isl_id
*id_test
,
2109 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2112 isl_local_space
*ls
;
2114 isl_multi_pw_aff
*prev
;
2116 space
= isl_set_get_space(domain
);
2117 ls
= isl_local_space_from_space(space
);
2118 aff
= isl_aff_var_on_domain(ls
, isl_dim_set
, 0);
2119 aff
= isl_aff_add_constant_val(aff
, isl_val_neg(inc
));
2120 prev
= isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
2121 domain
= isl_set_preimage_multi_pw_aff(domain
,
2122 isl_multi_pw_aff_copy(prev
));
2123 prev
= isl_multi_pw_aff_intersect_domain(prev
, domain
);
2124 prev
= isl_multi_pw_aff_set_tuple_id(prev
, isl_dim_out
, id_test
);
2129 /* Add an implication to "scop" expressing that if an element of
2130 * virtual array "id_test" has value "satisfied" then all previous elements
2131 * of this array also have that value. The set of previous elements
2132 * is bounded by "domain". If "sign" is negative then iterator
2133 * is decreasing and we express that all subsequent array elements
2134 * (but still defined previously) have the same value.
2136 static struct pet_scop
*add_implication(struct pet_scop
*scop
,
2137 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
, int sign
,
2143 domain
= isl_set_set_tuple_id(domain
, id_test
);
2144 space
= isl_set_get_space(domain
);
2146 map
= isl_map_lex_ge(space
);
2148 map
= isl_map_lex_le(space
);
2149 map
= isl_map_intersect_range(map
, domain
);
2150 scop
= pet_scop_add_implication(scop
, map
, satisfied
);
2155 /* Add a filter to "scop" that imposes that it is only executed
2156 * when the variable identified by "id_test" has a zero value
2157 * for all previous iterations of "domain".
2159 * In particular, add a filter that imposes that the array
2160 * has a zero value at the previous iteration of domain and
2161 * add an implication that implies that it then has that
2162 * value for all previous iterations.
2164 static struct pet_scop
*scop_add_break(struct pet_scop
*scop
,
2165 __isl_take isl_id
*id_test
, __isl_take isl_set
*domain
,
2166 __isl_take isl_val
*inc
)
2168 isl_multi_pw_aff
*prev
;
2169 int sign
= isl_val_sgn(inc
);
2171 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
2172 scop
= add_implication(scop
, id_test
, domain
, sign
, 0);
2173 scop
= pet_scop_filter(scop
, prev
, 0);
2178 /* Construct a pet_scop for an infinite loop around the given body.
2180 * We extract a pet_scop for the body and then embed it in a loop with
2189 * If the body contains any break, then it is taken into
2190 * account in infinite_domain (if the skip condition is affine)
2191 * or in scop_add_break (if the skip condition is not affine).
2193 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
2195 isl_id
*id
, *id_test
;
2198 struct pet_scop
*scop
;
2201 scop
= extract(body
);
2205 id
= isl_id_alloc(ctx
, "t", NULL
);
2206 domain
= infinite_domain(isl_id_copy(id
), scop
);
2207 ident
= identity_aff(domain
);
2209 has_var_break
= pet_scop_has_var_skip(scop
, pet_skip_later
);
2211 id_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
2213 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
2214 isl_map_from_aff(isl_aff_copy(ident
)), ident
, id
);
2216 scop
= scop_add_break(scop
, id_test
, domain
, isl_val_one(ctx
));
2218 isl_set_free(domain
);
2223 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2229 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
2231 return extract_infinite_loop(stmt
->getBody());
2234 /* Create an index expression for an access to a virtual array
2235 * representing the result of a condition.
2236 * Unlike other accessed data, the id of the array is NULL as
2237 * there is no ValueDecl in the program corresponding to the virtual
2239 * The array starts out as a scalar, but grows along with the
2240 * statement writing to the array in pet_scop_embed.
2242 static __isl_give isl_multi_pw_aff
*create_test_index(isl_ctx
*ctx
, int test_nr
)
2244 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, 0);
2248 snprintf(name
, sizeof(name
), "__pet_test_%d", test_nr
);
2249 id
= isl_id_alloc(ctx
, name
, NULL
);
2250 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
2251 return isl_multi_pw_aff_zero(dim
);
2254 /* Add an array with the given extent (range of "index") to the list
2255 * of arrays in "scop" and return the extended pet_scop.
2256 * The array is marked as attaining values 0 and 1 only and
2257 * as each element being assigned at most once.
2259 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2260 __isl_keep isl_multi_pw_aff
*index
, clang::ASTContext
&ast_ctx
)
2262 isl_ctx
*ctx
= isl_multi_pw_aff_get_ctx(index
);
2264 struct pet_array
*array
;
2272 array
= isl_calloc_type(ctx
, struct pet_array
);
2276 access
= isl_map_from_multi_pw_aff(isl_multi_pw_aff_copy(index
));
2277 array
->extent
= isl_map_range(access
);
2278 dim
= isl_space_params_alloc(ctx
, 0);
2279 array
->context
= isl_set_universe(dim
);
2280 dim
= isl_space_set_alloc(ctx
, 0, 1);
2281 array
->value_bounds
= isl_set_universe(dim
);
2282 array
->value_bounds
= isl_set_lower_bound_si(array
->value_bounds
,
2284 array
->value_bounds
= isl_set_upper_bound_si(array
->value_bounds
,
2286 array
->element_type
= strdup("int");
2287 array
->element_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
2288 array
->uniquely_defined
= 1;
2290 if (!array
->extent
|| !array
->context
)
2291 array
= pet_array_free(array
);
2293 scop
= pet_scop_add_array(scop
, array
);
2297 pet_scop_free(scop
);
2301 /* Construct a pet_scop for a while loop of the form
2306 * In particular, construct a scop for an infinite loop around body and
2307 * intersect the domain with the affine expression.
2308 * Note that this intersection may result in an empty loop.
2310 struct pet_scop
*PetScan::extract_affine_while(__isl_take isl_pw_aff
*pa
,
2313 struct pet_scop
*scop
;
2317 valid
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2318 dom
= isl_pw_aff_non_zero_set(pa
);
2319 scop
= extract_infinite_loop(body
);
2320 scop
= pet_scop_restrict(scop
, dom
);
2321 scop
= pet_scop_restrict_context(scop
, valid
);
2326 /* Construct a scop for a while, given the scops for the condition
2327 * and the body, the filter identifier and the iteration domain of
2330 * In particular, the scop for the condition is filtered to depend
2331 * on "id_test" evaluating to true for all previous iterations
2332 * of the loop, while the scop for the body is filtered to depend
2333 * on "id_test" evaluating to true for all iterations up to the
2334 * current iteration.
2335 * The actual filter only imposes that this virtual array has
2336 * value one on the previous or the current iteration.
2337 * The fact that this condition also applies to the previous
2338 * iterations is enforced by an implication.
2340 * These filtered scops are then combined into a single scop.
2342 * "sign" is positive if the iterator increases and negative
2345 static struct pet_scop
*scop_add_while(struct pet_scop
*scop_cond
,
2346 struct pet_scop
*scop_body
, __isl_take isl_id
*id_test
,
2347 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2349 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
2351 isl_multi_pw_aff
*test_index
;
2352 isl_multi_pw_aff
*prev
;
2353 int sign
= isl_val_sgn(inc
);
2354 struct pet_scop
*scop
;
2356 prev
= map_to_previous(isl_id_copy(id_test
), isl_set_copy(domain
), inc
);
2357 scop_cond
= pet_scop_filter(scop_cond
, prev
, 1);
2359 space
= isl_space_map_from_set(isl_set_get_space(domain
));
2360 test_index
= isl_multi_pw_aff_identity(space
);
2361 test_index
= isl_multi_pw_aff_set_tuple_id(test_index
, isl_dim_out
,
2362 isl_id_copy(id_test
));
2363 scop_body
= pet_scop_filter(scop_body
, test_index
, 1);
2365 scop
= pet_scop_add_seq(ctx
, scop_cond
, scop_body
);
2366 scop
= add_implication(scop
, id_test
, domain
, sign
, 1);
2371 /* Check if the while loop is of the form
2373 * while (affine expression)
2376 * If so, call extract_affine_while to construct a scop.
2378 * Otherwise, construct a generic while scop, with iteration domain
2379 * { [t] : t >= 0 }. The scop consists of two parts, one for
2380 * evaluating the condition and one for the body.
2381 * The schedule is adjusted to reflect that the condition is evaluated
2382 * before the body is executed and the body is filtered to depend
2383 * on the result of the condition evaluating to true on all iterations
2384 * up to the current iteration, while the evaluation the condition itself
2385 * is filtered to depend on the result of the condition evaluating to true
2386 * on all previous iterations.
2387 * The context of the scop representing the body is dropped
2388 * because we don't know how many times the body will be executed,
2391 * If the body contains any break, then it is taken into
2392 * account in infinite_domain (if the skip condition is affine)
2393 * or in scop_add_break (if the skip condition is not affine).
2395 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
2398 isl_id
*id
, *id_test
, *id_break_test
;
2399 isl_multi_pw_aff
*test_index
;
2403 struct pet_scop
*scop
, *scop_body
;
2406 cond
= stmt
->getCond();
2412 clear_assignments
clear(assigned_value
);
2413 clear
.TraverseStmt(stmt
->getBody());
2415 pa
= try_extract_affine_condition(cond
);
2417 return extract_affine_while(pa
, stmt
->getBody());
2419 if (!allow_nested
) {
2424 test_index
= create_test_index(ctx
, n_test
++);
2425 scop
= extract_non_affine_condition(cond
,
2426 isl_multi_pw_aff_copy(test_index
));
2427 scop
= scop_add_array(scop
, test_index
, ast_context
);
2428 id_test
= isl_multi_pw_aff_get_tuple_id(test_index
, isl_dim_out
);
2429 isl_multi_pw_aff_free(test_index
);
2430 scop_body
= extract(stmt
->getBody());
2432 id
= isl_id_alloc(ctx
, "t", NULL
);
2433 domain
= infinite_domain(isl_id_copy(id
), scop_body
);
2434 ident
= identity_aff(domain
);
2436 has_var_break
= pet_scop_has_var_skip(scop_body
, pet_skip_later
);
2438 id_break_test
= pet_scop_get_skip_id(scop_body
, pet_skip_later
);
2440 scop
= pet_scop_prefix(scop
, 0);
2441 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
2442 isl_map_from_aff(isl_aff_copy(ident
)),
2443 isl_aff_copy(ident
), isl_id_copy(id
));
2444 scop_body
= pet_scop_reset_context(scop_body
);
2445 scop_body
= pet_scop_prefix(scop_body
, 1);
2446 scop_body
= pet_scop_embed(scop_body
, isl_set_copy(domain
),
2447 isl_map_from_aff(isl_aff_copy(ident
)), ident
, id
);
2449 if (has_var_break
) {
2450 scop
= scop_add_break(scop
, isl_id_copy(id_break_test
),
2451 isl_set_copy(domain
), isl_val_one(ctx
));
2452 scop_body
= scop_add_break(scop_body
, id_break_test
,
2453 isl_set_copy(domain
), isl_val_one(ctx
));
2455 scop
= scop_add_while(scop
, scop_body
, id_test
, domain
,
2461 /* Check whether "cond" expresses a simple loop bound
2462 * on the only set dimension.
2463 * In particular, if "up" is set then "cond" should contain only
2464 * upper bounds on the set dimension.
2465 * Otherwise, it should contain only lower bounds.
2467 static bool is_simple_bound(__isl_keep isl_set
*cond
, __isl_keep isl_val
*inc
)
2469 if (isl_val_is_pos(inc
))
2470 return !isl_set_dim_has_any_lower_bound(cond
, isl_dim_set
, 0);
2472 return !isl_set_dim_has_any_upper_bound(cond
, isl_dim_set
, 0);
2475 /* Extend a condition on a given iteration of a loop to one that
2476 * imposes the same condition on all previous iterations.
2477 * "domain" expresses the lower [upper] bound on the iterations
2478 * when inc is positive [negative].
2480 * In particular, we construct the condition (when inc is positive)
2482 * forall i' : (domain(i') and i' <= i) => cond(i')
2484 * which is equivalent to
2486 * not exists i' : domain(i') and i' <= i and not cond(i')
2488 * We construct this set by negating cond, applying a map
2490 * { [i'] -> [i] : domain(i') and i' <= i }
2492 * and then negating the result again.
2494 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
2495 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2497 isl_map
*previous_to_this
;
2499 if (isl_val_is_pos(inc
))
2500 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
2502 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
2504 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
2506 cond
= isl_set_complement(cond
);
2507 cond
= isl_set_apply(cond
, previous_to_this
);
2508 cond
= isl_set_complement(cond
);
2515 /* Construct a domain of the form
2517 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2519 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
2520 __isl_take isl_pw_aff
*init
, __isl_take isl_val
*inc
)
2526 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
2527 dim
= isl_pw_aff_get_domain_space(init
);
2528 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2529 aff
= isl_aff_add_coefficient_val(aff
, isl_dim_in
, 0, inc
);
2530 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2532 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2533 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2534 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2535 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2537 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2539 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2541 return isl_set_params(set
);
2544 /* Assuming "cond" represents a bound on a loop where the loop
2545 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2548 * Under the given assumptions, wrapping is only possible if "cond" allows
2549 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2550 * increasing iterator and 0 in case of a decreasing iterator.
2552 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
,
2553 __isl_keep isl_val
*inc
)
2560 test
= isl_set_copy(cond
);
2562 ctx
= isl_set_get_ctx(test
);
2563 if (isl_val_is_neg(inc
))
2564 limit
= isl_val_zero(ctx
);
2566 limit
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2567 limit
= isl_val_2exp(limit
);
2568 limit
= isl_val_sub_ui(limit
, 1);
2571 test
= isl_set_fix_val(cond
, isl_dim_set
, 0, limit
);
2572 cw
= !isl_set_is_empty(test
);
2578 /* Given a one-dimensional space, construct the following affine expression
2581 * { [v] -> [v mod 2^width] }
2583 * where width is the number of bits used to represent the values
2584 * of the unsigned variable "iv".
2586 static __isl_give isl_aff
*compute_wrapping(__isl_take isl_space
*dim
,
2593 ctx
= isl_space_get_ctx(dim
);
2594 mod
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2595 mod
= isl_val_2exp(mod
);
2597 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2598 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2599 aff
= isl_aff_mod_val(aff
, mod
);
2604 /* Project out the parameter "id" from "set".
2606 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2607 __isl_keep isl_id
*id
)
2611 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2613 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2618 /* Compute the set of parameters for which "set1" is a subset of "set2".
2620 * set1 is a subset of set2 if
2622 * forall i in set1 : i in set2
2626 * not exists i in set1 and i not in set2
2630 * not exists i in set1 \ set2
2632 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2633 __isl_take isl_set
*set2
)
2635 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2638 /* Compute the set of parameter values for which "cond" holds
2639 * on the next iteration for each element of "dom".
2641 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2642 * and then compute the set of parameters for which the result is a subset
2645 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2646 __isl_take isl_set
*dom
, __isl_take isl_val
*inc
)
2652 space
= isl_set_get_space(dom
);
2653 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2654 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2655 aff
= isl_aff_add_constant_val(aff
, inc
);
2656 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2658 dom
= isl_set_apply(dom
, next
);
2660 return enforce_subset(dom
, cond
);
2663 /* Does "id" refer to a nested access?
2665 static bool is_nested_parameter(__isl_keep isl_id
*id
)
2667 return id
&& isl_id_get_user(id
) && !isl_id_get_name(id
);
2670 /* Does parameter "pos" of "space" refer to a nested access?
2672 static bool is_nested_parameter(__isl_keep isl_space
*space
, int pos
)
2677 id
= isl_space_get_dim_id(space
, isl_dim_param
, pos
);
2678 nested
= is_nested_parameter(id
);
2684 /* Does "space" involve any parameters that refer to nested
2685 * accesses, i.e., parameters with no name?
2687 static bool has_nested(__isl_keep isl_space
*space
)
2691 nparam
= isl_space_dim(space
, isl_dim_param
);
2692 for (int i
= 0; i
< nparam
; ++i
)
2693 if (is_nested_parameter(space
, i
))
2699 /* Does "pa" involve any parameters that refer to nested
2700 * accesses, i.e., parameters with no name?
2702 static bool has_nested(__isl_keep isl_pw_aff
*pa
)
2707 space
= isl_pw_aff_get_space(pa
);
2708 nested
= has_nested(space
);
2709 isl_space_free(space
);
2714 /* Construct a pet_scop for a for statement.
2715 * The for loop is required to be of the form
2717 * for (i = init; condition; ++i)
2721 * for (i = init; condition; --i)
2723 * The initialization of the for loop should either be an assignment
2724 * to an integer variable, or a declaration of such a variable with
2727 * The condition is allowed to contain nested accesses, provided
2728 * they are not being written to inside the body of the loop.
2729 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2730 * essentially treated as a while loop, with iteration domain
2731 * { [i] : i >= init }.
2733 * We extract a pet_scop for the body and then embed it in a loop with
2734 * iteration domain and schedule
2736 * { [i] : i >= init and condition' }
2741 * { [i] : i <= init and condition' }
2744 * Where condition' is equal to condition if the latter is
2745 * a simple upper [lower] bound and a condition that is extended
2746 * to apply to all previous iterations otherwise.
2748 * If the condition is non-affine, then we drop the condition from the
2749 * iteration domain and instead create a separate statement
2750 * for evaluating the condition. The body is then filtered to depend
2751 * on the result of the condition evaluating to true on all iterations
2752 * up to the current iteration, while the evaluation the condition itself
2753 * is filtered to depend on the result of the condition evaluating to true
2754 * on all previous iterations.
2755 * The context of the scop representing the body is dropped
2756 * because we don't know how many times the body will be executed,
2759 * If the stride of the loop is not 1, then "i >= init" is replaced by
2761 * (exists a: i = init + stride * a and a >= 0)
2763 * If the loop iterator i is unsigned, then wrapping may occur.
2764 * During the computation, we work with a virtual iterator that
2765 * does not wrap. However, the condition in the code applies
2766 * to the wrapped value, so we need to change condition(i)
2767 * into condition([i % 2^width]).
2768 * After computing the virtual domain and schedule, we apply
2769 * the function { [v] -> [v % 2^width] } to the domain and the domain
2770 * of the schedule. In order not to lose any information, we also
2771 * need to intersect the domain of the schedule with the virtual domain
2772 * first, since some iterations in the wrapped domain may be scheduled
2773 * several times, typically an infinite number of times.
2774 * Note that there may be no need to perform this final wrapping
2775 * if the loop condition (after wrapping) satisfies certain conditions.
2776 * However, the is_simple_bound condition is not enough since it doesn't
2777 * check if there even is an upper bound.
2779 * If the loop condition is non-affine, then we keep the virtual
2780 * iterator in the iteration domain and instead replace all accesses
2781 * to the original iterator by the wrapping of the virtual iterator.
2783 * Wrapping on unsigned iterators can be avoided entirely if
2784 * loop condition is simple, the loop iterator is incremented
2785 * [decremented] by one and the last value before wrapping cannot
2786 * possibly satisfy the loop condition.
2788 * Before extracting a pet_scop from the body we remove all
2789 * assignments in assigned_value to variables that are assigned
2790 * somewhere in the body of the loop.
2792 * Valid parameters for a for loop are those for which the initial
2793 * value itself, the increment on each domain iteration and
2794 * the condition on both the initial value and
2795 * the result of incrementing the iterator for each iteration of the domain
2797 * If the loop condition is non-affine, then we only consider validity
2798 * of the initial value.
2800 * If the body contains any break, then we keep track of it in "skip"
2801 * (if the skip condition is affine) or it is handled in scop_add_break
2802 * (if the skip condition is not affine).
2803 * Note that the affine break condition needs to be considered with
2804 * respect to previous iterations in the virtual domain (if any)
2805 * and that the domain needs to be kept virtual if there is a non-affine
2808 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2810 BinaryOperator
*ass
;
2818 isl_set
*cond
= NULL
;
2819 isl_set
*skip
= NULL
;
2820 isl_id
*id
, *id_test
= NULL
, *id_break_test
;
2821 struct pet_scop
*scop
, *scop_cond
= NULL
;
2822 assigned_value_cache
cache(assigned_value
);
2828 bool keep_virtual
= false;
2829 bool has_affine_break
;
2831 isl_aff
*wrap
= NULL
;
2832 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2833 isl_set
*valid_init
;
2834 isl_set
*valid_cond
;
2835 isl_set
*valid_cond_init
;
2836 isl_set
*valid_cond_next
;
2840 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2841 return extract_infinite_for(stmt
);
2843 init
= stmt
->getInit();
2848 if ((ass
= initialization_assignment(init
)) != NULL
) {
2849 iv
= extract_induction_variable(ass
);
2852 lhs
= ass
->getLHS();
2853 rhs
= ass
->getRHS();
2854 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2855 VarDecl
*var
= extract_induction_variable(init
, decl
);
2859 rhs
= var
->getInit();
2860 lhs
= create_DeclRefExpr(var
);
2862 unsupported(stmt
->getInit());
2866 pa_inc
= extract_increment(stmt
, iv
);
2871 if (isl_pw_aff_n_piece(pa_inc
) != 1 ||
2872 isl_pw_aff_foreach_piece(pa_inc
, &extract_cst
, &inc
) < 0) {
2873 isl_pw_aff_free(pa_inc
);
2874 unsupported(stmt
->getInc());
2878 valid_inc
= isl_pw_aff_domain(pa_inc
);
2880 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2882 assigned_value
.erase(iv
);
2883 clear_assignments
clear(assigned_value
);
2884 clear
.TraverseStmt(stmt
->getBody());
2886 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
2888 pa
= try_extract_nested_condition(stmt
->getCond());
2889 if (allow_nested
&& (!pa
|| has_nested(pa
)))
2892 scop
= extract(stmt
->getBody());
2894 has_affine_break
= scop
&&
2895 pet_scop_has_affine_skip(scop
, pet_skip_later
);
2896 if (has_affine_break
)
2897 skip
= pet_scop_get_affine_skip_domain(scop
, pet_skip_later
);
2898 has_var_break
= scop
&& pet_scop_has_var_skip(scop
, pet_skip_later
);
2899 if (has_var_break
) {
2900 id_break_test
= pet_scop_get_skip_id(scop
, pet_skip_later
);
2901 keep_virtual
= true;
2904 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2905 isl_pw_aff_free(pa
);
2909 if (!allow_nested
&& !pa
)
2910 pa
= try_extract_affine_condition(stmt
->getCond());
2911 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2912 cond
= isl_pw_aff_non_zero_set(pa
);
2913 if (allow_nested
&& !cond
) {
2914 isl_multi_pw_aff
*test_index
;
2915 int save_n_stmt
= n_stmt
;
2916 test_index
= create_test_index(ctx
, n_test
++);
2918 scop_cond
= extract_non_affine_condition(stmt
->getCond(),
2919 isl_multi_pw_aff_copy(test_index
));
2920 n_stmt
= save_n_stmt
;
2921 scop_cond
= scop_add_array(scop_cond
, test_index
, ast_context
);
2922 id_test
= isl_multi_pw_aff_get_tuple_id(test_index
,
2924 isl_multi_pw_aff_free(test_index
);
2925 scop_cond
= pet_scop_prefix(scop_cond
, 0);
2926 scop
= pet_scop_reset_context(scop
);
2927 scop
= pet_scop_prefix(scop
, 1);
2928 keep_virtual
= true;
2929 cond
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2932 cond
= embed(cond
, isl_id_copy(id
));
2933 skip
= embed(skip
, isl_id_copy(id
));
2934 valid_cond
= isl_set_coalesce(valid_cond
);
2935 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
2936 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
2937 is_one
= isl_val_is_one(inc
) || isl_val_is_negone(inc
);
2938 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2940 init_val
= extract_affine(rhs
);
2941 valid_cond_init
= enforce_subset(
2942 isl_set_from_pw_aff(isl_pw_aff_copy(init_val
)),
2943 isl_set_copy(valid_cond
));
2944 if (is_one
&& !is_virtual
) {
2945 isl_pw_aff_free(init_val
);
2946 pa
= extract_comparison(isl_val_is_pos(inc
) ? BO_GE
: BO_LE
,
2948 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2949 valid_init
= set_project_out_by_id(valid_init
, id
);
2950 domain
= isl_pw_aff_non_zero_set(pa
);
2952 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
2953 domain
= strided_domain(isl_id_copy(id
), init_val
,
2957 domain
= embed(domain
, isl_id_copy(id
));
2960 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2961 rev_wrap
= isl_map_from_aff(isl_aff_copy(wrap
));
2962 rev_wrap
= isl_map_reverse(rev_wrap
);
2963 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
2964 skip
= isl_set_apply(skip
, isl_map_copy(rev_wrap
));
2965 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
2966 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
2968 is_simple
= is_simple_bound(cond
, inc
);
2970 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2971 is_simple
= is_simple_bound(cond
, inc
);
2974 cond
= valid_for_each_iteration(cond
,
2975 isl_set_copy(domain
), isl_val_copy(inc
));
2976 domain
= isl_set_intersect(domain
, cond
);
2977 if (has_affine_break
) {
2978 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2979 skip
= after(skip
, isl_val_sgn(inc
));
2980 domain
= isl_set_subtract(domain
, skip
);
2982 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2983 space
= isl_space_from_domain(isl_set_get_space(domain
));
2984 space
= isl_space_add_dims(space
, isl_dim_out
, 1);
2985 sched
= isl_map_universe(space
);
2986 if (isl_val_is_pos(inc
))
2987 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2989 sched
= isl_map_oppose(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2991 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
),
2993 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
2995 if (is_virtual
&& !keep_virtual
) {
2996 isl_map
*wrap_map
= isl_map_from_aff(wrap
);
2997 wrap_map
= isl_map_set_dim_id(wrap_map
,
2998 isl_dim_out
, 0, isl_id_copy(id
));
2999 sched
= isl_map_intersect_domain(sched
, isl_set_copy(domain
));
3000 domain
= isl_set_apply(domain
, isl_map_copy(wrap_map
));
3001 sched
= isl_map_apply_domain(sched
, wrap_map
);
3003 if (!(is_virtual
&& keep_virtual
))
3004 wrap
= identity_aff(domain
);
3006 scop_cond
= pet_scop_embed(scop_cond
, isl_set_copy(domain
),
3007 isl_map_copy(sched
), isl_aff_copy(wrap
), isl_id_copy(id
));
3008 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), sched
, wrap
, id
);
3009 scop
= resolve_nested(scop
);
3011 scop
= scop_add_break(scop
, id_break_test
, isl_set_copy(domain
),
3014 scop
= scop_add_while(scop_cond
, scop
, id_test
, domain
,
3016 isl_set_free(valid_inc
);
3018 scop
= pet_scop_restrict_context(scop
, valid_inc
);
3019 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
3020 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
3021 isl_set_free(domain
);
3023 clear_assignment(assigned_value
, iv
);
3027 scop
= pet_scop_restrict_context(scop
, valid_init
);
3032 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
, bool skip_declarations
)
3034 return extract(stmt
->children(), true, skip_declarations
);
3037 /* Does parameter "pos" of "map" refer to a nested access?
3039 static bool is_nested_parameter(__isl_keep isl_map
*map
, int pos
)
3044 id
= isl_map_get_dim_id(map
, isl_dim_param
, pos
);
3045 nested
= is_nested_parameter(id
);
3051 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
3053 static int n_nested_parameter(__isl_keep isl_space
*space
)
3058 nparam
= isl_space_dim(space
, isl_dim_param
);
3059 for (int i
= 0; i
< nparam
; ++i
)
3060 if (is_nested_parameter(space
, i
))
3066 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
3068 static int n_nested_parameter(__isl_keep isl_map
*map
)
3073 space
= isl_map_get_space(map
);
3074 n
= n_nested_parameter(space
);
3075 isl_space_free(space
);
3080 /* For each nested access parameter in "space",
3081 * construct a corresponding pet_expr, place it in args and
3082 * record its position in "param2pos".
3083 * "n_arg" is the number of elements that are already in args.
3084 * The position recorded in "param2pos" takes this number into account.
3085 * If the pet_expr corresponding to a parameter is identical to
3086 * the pet_expr corresponding to an earlier parameter, then these two
3087 * parameters are made to refer to the same element in args.
3089 * Return the final number of elements in args or -1 if an error has occurred.
3091 int PetScan::extract_nested(__isl_keep isl_space
*space
,
3092 int n_arg
, struct pet_expr
**args
, std::map
<int,int> ¶m2pos
)
3096 nparam
= isl_space_dim(space
, isl_dim_param
);
3097 for (int i
= 0; i
< nparam
; ++i
) {
3099 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
3102 if (!is_nested_parameter(id
)) {
3107 nested
= (Expr
*) isl_id_get_user(id
);
3108 args
[n_arg
] = extract_expr(nested
);
3112 for (j
= 0; j
< n_arg
; ++j
)
3113 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
3117 pet_expr_free(args
[n_arg
]);
3121 param2pos
[i
] = n_arg
++;
3129 /* For each nested access parameter in the access relations in "expr",
3130 * construct a corresponding pet_expr, place it in expr->args and
3131 * record its position in "param2pos".
3132 * n is the number of nested access parameters.
3134 struct pet_expr
*PetScan::extract_nested(struct pet_expr
*expr
, int n
,
3135 std::map
<int,int> ¶m2pos
)
3139 expr
->args
= isl_calloc_array(ctx
, struct pet_expr
*, n
);
3144 space
= isl_map_get_space(expr
->acc
.access
);
3145 n
= extract_nested(space
, 0, expr
->args
, param2pos
);
3146 isl_space_free(space
);
3154 pet_expr_free(expr
);
3158 /* Look for parameters in any access relation in "expr" that
3159 * refer to nested accesses. In particular, these are
3160 * parameters with no name.
3162 * If there are any such parameters, then the domain of the index
3163 * expression and the access relation, which is still [] at this point,
3164 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
3165 * (after identifying identical nested accesses).
3167 * This transformation is performed in several steps.
3168 * We first extract the arguments in extract_nested.
3169 * param2pos maps the original parameter position to the position
3171 * Then we move these parameters to input dimension.
3172 * t2pos maps the positions of these temporary input dimensions
3173 * to the positions of the corresponding arguments.
3174 * Finally, we express there temporary dimensions in term of the domain
3175 * [[] -> [t_1,...,t_n]] and precompose index expression and access
3176 * relations with this function.
3178 struct pet_expr
*PetScan::resolve_nested(struct pet_expr
*expr
)
3183 isl_local_space
*ls
;
3186 std::map
<int,int> param2pos
;
3187 std::map
<int,int> t2pos
;
3192 for (int i
= 0; i
< expr
->n_arg
; ++i
) {
3193 expr
->args
[i
] = resolve_nested(expr
->args
[i
]);
3194 if (!expr
->args
[i
]) {
3195 pet_expr_free(expr
);
3200 if (expr
->type
!= pet_expr_access
)
3203 n
= n_nested_parameter(expr
->acc
.access
);
3207 expr
= extract_nested(expr
, n
, param2pos
);
3211 expr
= pet_expr_access_align_params(expr
);
3214 nparam
= isl_map_dim(expr
->acc
.access
, isl_dim_param
);
3217 for (int i
= nparam
- 1; i
>= 0; --i
) {
3218 isl_id
*id
= isl_map_get_dim_id(expr
->acc
.access
,
3220 if (!is_nested_parameter(id
)) {
3225 expr
->acc
.access
= isl_map_move_dims(expr
->acc
.access
,
3226 isl_dim_in
, n
, isl_dim_param
, i
, 1);
3227 expr
->acc
.index
= isl_multi_pw_aff_move_dims(expr
->acc
.index
,
3228 isl_dim_in
, n
, isl_dim_param
, i
, 1);
3229 t2pos
[n
] = param2pos
[i
];
3235 space
= isl_multi_pw_aff_get_space(expr
->acc
.index
);
3236 space
= isl_space_set_from_params(isl_space_params(space
));
3237 space
= isl_space_add_dims(space
, isl_dim_set
, expr
->n_arg
);
3238 space
= isl_space_wrap(isl_space_from_range(space
));
3239 ls
= isl_local_space_from_space(isl_space_copy(space
));
3240 space
= isl_space_from_domain(space
);
3241 space
= isl_space_add_dims(space
, isl_dim_out
, n
);
3242 ma
= isl_multi_aff_zero(space
);
3244 for (int i
= 0; i
< n
; ++i
) {
3245 aff
= isl_aff_var_on_domain(isl_local_space_copy(ls
),
3246 isl_dim_set
, t2pos
[i
]);
3247 ma
= isl_multi_aff_set_aff(ma
, i
, aff
);
3249 isl_local_space_free(ls
);
3251 expr
->acc
.access
= isl_map_preimage_domain_multi_aff(expr
->acc
.access
,
3252 isl_multi_aff_copy(ma
));
3253 expr
->acc
.index
= isl_multi_pw_aff_pullback_multi_aff(expr
->acc
.index
,
3259 /* Return the file offset of the expansion location of "Loc".
3261 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
3263 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
3266 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3268 /* Return a SourceLocation for the location after the first semicolon
3269 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3270 * call it and also skip trailing spaces and newline.
3272 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3273 const LangOptions
&LO
)
3275 return Lexer::findLocationAfterToken(loc
, tok::semi
, SM
, LO
, true);
3280 /* Return a SourceLocation for the location after the first semicolon
3281 * after "loc". If Lexer::findLocationAfterToken is not available,
3282 * we look in the underlying character data for the first semicolon.
3284 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3285 const LangOptions
&LO
)
3288 const char *s
= SM
.getCharacterData(loc
);
3290 semi
= strchr(s
, ';');
3292 return SourceLocation();
3293 return loc
.getFileLocWithOffset(semi
+ 1 - s
);
3298 /* If the token at "loc" is the first token on the line, then return
3299 * a location referring to the start of the line.
3300 * Otherwise, return "loc".
3302 * This function is used to extend a scop to the start of the line
3303 * if the first token of the scop is also the first token on the line.
3305 * We look for the first token on the line. If its location is equal to "loc",
3306 * then the latter is the location of the first token on the line.
3308 static SourceLocation
move_to_start_of_line_if_first_token(SourceLocation loc
,
3309 SourceManager
&SM
, const LangOptions
&LO
)
3311 std::pair
<FileID
, unsigned> file_offset_pair
;
3312 llvm::StringRef file
;
3315 SourceLocation token_loc
, line_loc
;
3318 loc
= SM
.getExpansionLoc(loc
);
3319 col
= SM
.getExpansionColumnNumber(loc
);
3320 line_loc
= loc
.getLocWithOffset(1 - col
);
3321 file_offset_pair
= SM
.getDecomposedLoc(line_loc
);
3322 file
= SM
.getBufferData(file_offset_pair
.first
, NULL
);
3323 pos
= file
.data() + file_offset_pair
.second
;
3325 Lexer
lexer(SM
.getLocForStartOfFile(file_offset_pair
.first
), LO
,
3326 file
.begin(), pos
, file
.end());
3327 lexer
.LexFromRawLexer(tok
);
3328 token_loc
= tok
.getLocation();
3330 if (token_loc
== loc
)
3336 /* Convert a top-level pet_expr to a pet_scop with one statement.
3337 * This mainly involves resolving nested expression parameters
3338 * and setting the name of the iteration space.
3339 * The name is given by "label" if it is non-NULL. Otherwise,
3340 * it is of the form S_<n_stmt>.
3341 * start and end of the pet_scop are derived from those of "stmt".
3343 struct pet_scop
*PetScan::extract(Stmt
*stmt
, struct pet_expr
*expr
,
3344 __isl_take isl_id
*label
)
3346 struct pet_stmt
*ps
;
3347 struct pet_scop
*scop
;
3348 SourceLocation loc
= stmt
->getLocStart();
3349 SourceManager
&SM
= PP
.getSourceManager();
3350 const LangOptions
&LO
= PP
.getLangOpts();
3351 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3352 unsigned start
, end
;
3354 expr
= resolve_nested(expr
);
3355 ps
= pet_stmt_from_pet_expr(ctx
, line
, label
, n_stmt
++, expr
);
3356 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3358 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
);
3359 start
= getExpansionOffset(SM
, loc
);
3360 loc
= stmt
->getLocEnd();
3361 loc
= location_after_semi(loc
, SM
, LO
);
3362 end
= getExpansionOffset(SM
, loc
);
3364 scop
= pet_scop_update_start_end(scop
, start
, end
);
3368 /* Check if we can extract an affine expression from "expr".
3369 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3370 * We turn on autodetection so that we won't generate any warnings
3371 * and turn off nesting, so that we won't accept any non-affine constructs.
3373 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
3376 int save_autodetect
= options
->autodetect
;
3377 bool save_nesting
= nesting_enabled
;
3379 options
->autodetect
= 1;
3380 nesting_enabled
= false;
3382 pwaff
= extract_affine(expr
);
3384 options
->autodetect
= save_autodetect
;
3385 nesting_enabled
= save_nesting
;
3390 /* Check whether "expr" is an affine expression.
3392 bool PetScan::is_affine(Expr
*expr
)
3396 pwaff
= try_extract_affine(expr
);
3397 isl_pw_aff_free(pwaff
);
3399 return pwaff
!= NULL
;
3402 /* Check if we can extract an affine constraint from "expr".
3403 * Return the constraint as an isl_set if we can and NULL otherwise.
3404 * We turn on autodetection so that we won't generate any warnings
3405 * and turn off nesting, so that we won't accept any non-affine constructs.
3407 __isl_give isl_pw_aff
*PetScan::try_extract_affine_condition(Expr
*expr
)
3410 int save_autodetect
= options
->autodetect
;
3411 bool save_nesting
= nesting_enabled
;
3413 options
->autodetect
= 1;
3414 nesting_enabled
= false;
3416 cond
= extract_condition(expr
);
3418 options
->autodetect
= save_autodetect
;
3419 nesting_enabled
= save_nesting
;
3424 /* Check whether "expr" is an affine constraint.
3426 bool PetScan::is_affine_condition(Expr
*expr
)
3430 cond
= try_extract_affine_condition(expr
);
3431 isl_pw_aff_free(cond
);
3433 return cond
!= NULL
;
3436 /* Check if we can extract a condition from "expr".
3437 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3438 * If allow_nested is set, then the condition may involve parameters
3439 * corresponding to nested accesses.
3440 * We turn on autodetection so that we won't generate any warnings.
3442 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
3445 int save_autodetect
= options
->autodetect
;
3446 bool save_nesting
= nesting_enabled
;
3448 options
->autodetect
= 1;
3449 nesting_enabled
= allow_nested
;
3450 cond
= extract_condition(expr
);
3452 options
->autodetect
= save_autodetect
;
3453 nesting_enabled
= save_nesting
;
3458 /* If the top-level expression of "stmt" is an assignment, then
3459 * return that assignment as a BinaryOperator.
3460 * Otherwise return NULL.
3462 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
3464 BinaryOperator
*ass
;
3468 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
3471 ass
= cast
<BinaryOperator
>(stmt
);
3472 if(ass
->getOpcode() != BO_Assign
)
3478 /* Check if the given if statement is a conditional assignement
3479 * with a non-affine condition. If so, construct a pet_scop
3480 * corresponding to this conditional assignment. Otherwise return NULL.
3482 * In particular we check if "stmt" is of the form
3489 * where a is some array or scalar access.
3490 * The constructed pet_scop then corresponds to the expression
3492 * a = condition ? f(...) : g(...)
3494 * All access relations in f(...) are intersected with condition
3495 * while all access relation in g(...) are intersected with the complement.
3497 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
3499 BinaryOperator
*ass_then
, *ass_else
;
3500 isl_multi_pw_aff
*write_then
, *write_else
;
3501 isl_set
*cond
, *comp
;
3502 isl_multi_pw_aff
*index
;
3505 struct pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
3506 bool save_nesting
= nesting_enabled
;
3508 if (!options
->detect_conditional_assignment
)
3511 ass_then
= top_assignment_or_null(stmt
->getThen());
3512 ass_else
= top_assignment_or_null(stmt
->getElse());
3514 if (!ass_then
|| !ass_else
)
3517 if (is_affine_condition(stmt
->getCond()))
3520 write_then
= extract_index(ass_then
->getLHS());
3521 write_else
= extract_index(ass_else
->getLHS());
3523 equal
= isl_multi_pw_aff_plain_is_equal(write_then
, write_else
);
3524 isl_multi_pw_aff_free(write_else
);
3525 if (equal
< 0 || !equal
) {
3526 isl_multi_pw_aff_free(write_then
);
3530 nesting_enabled
= allow_nested
;
3531 pa
= extract_condition(stmt
->getCond());
3532 nesting_enabled
= save_nesting
;
3533 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
3534 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
3535 index
= isl_multi_pw_aff_from_range(isl_multi_pw_aff_from_pw_aff(pa
));
3537 pe_cond
= pet_expr_from_index(index
);
3539 pe_then
= extract_expr(ass_then
->getRHS());
3540 pe_then
= pet_expr_restrict(pe_then
, cond
);
3541 pe_else
= extract_expr(ass_else
->getRHS());
3542 pe_else
= pet_expr_restrict(pe_else
, comp
);
3544 pe
= pet_expr_new_ternary(ctx
, pe_cond
, pe_then
, pe_else
);
3545 pe_write
= pet_expr_from_index_and_depth(write_then
,
3546 extract_depth(write_then
));
3548 pe_write
->acc
.write
= 1;
3549 pe_write
->acc
.read
= 0;
3551 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, pe_write
, pe
);
3552 return extract(stmt
, pe
);
3555 /* Create a pet_scop with a single statement evaluating "cond"
3556 * and writing the result to a virtual scalar, as expressed by
3559 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
,
3560 __isl_take isl_multi_pw_aff
*index
)
3562 struct pet_expr
*expr
, *write
;
3563 struct pet_stmt
*ps
;
3564 struct pet_scop
*scop
;
3565 SourceLocation loc
= cond
->getLocStart();
3566 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3568 write
= pet_expr_from_index(index
);
3570 write
->acc
.write
= 1;
3571 write
->acc
.read
= 0;
3573 expr
= extract_expr(cond
);
3574 expr
= resolve_nested(expr
);
3575 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, write
, expr
);
3576 ps
= pet_stmt_from_pet_expr(ctx
, line
, NULL
, n_stmt
++, expr
);
3577 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3578 scop
= resolve_nested(scop
);
3584 static struct pet_expr
*embed_access(struct pet_expr
*expr
, void *user
);
3587 /* Precompose the access relation and the index expression associated
3588 * to "expr" with the function pointed to by "user",
3589 * thereby embedding the access relation in the domain of this function.
3590 * The initial domain of the access relation and the index expression
3591 * is the zero-dimensional domain.
3593 static struct pet_expr
*embed_access(struct pet_expr
*expr
, void *user
)
3595 isl_multi_aff
*ma
= (isl_multi_aff
*) user
;
3597 expr
->acc
.access
= isl_map_preimage_domain_multi_aff(expr
->acc
.access
,
3598 isl_multi_aff_copy(ma
));
3599 expr
->acc
.index
= isl_multi_pw_aff_pullback_multi_aff(expr
->acc
.index
,
3600 isl_multi_aff_copy(ma
));
3601 if (!expr
->acc
.access
|| !expr
->acc
.index
)
3606 pet_expr_free(expr
);
3610 /* Precompose all access relations in "expr" with "ma", thereby
3611 * embedding them in the domain of "ma".
3613 static struct pet_expr
*embed(struct pet_expr
*expr
,
3614 __isl_keep isl_multi_aff
*ma
)
3616 return pet_expr_map_access(expr
, &embed_access
, ma
);
3619 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3621 static int n_nested_parameter(__isl_keep isl_set
*set
)
3626 space
= isl_set_get_space(set
);
3627 n
= n_nested_parameter(space
);
3628 isl_space_free(space
);
3633 /* Remove all parameters from "map" that refer to nested accesses.
3635 static __isl_give isl_map
*remove_nested_parameters(__isl_take isl_map
*map
)
3640 space
= isl_map_get_space(map
);
3641 nparam
= isl_space_dim(space
, isl_dim_param
);
3642 for (int i
= nparam
- 1; i
>= 0; --i
)
3643 if (is_nested_parameter(space
, i
))
3644 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3645 isl_space_free(space
);
3650 /* Remove all parameters from "mpa" that refer to nested accesses.
3652 static __isl_give isl_multi_pw_aff
*remove_nested_parameters(
3653 __isl_take isl_multi_pw_aff
*mpa
)
3658 space
= isl_multi_pw_aff_get_space(mpa
);
3659 nparam
= isl_space_dim(space
, isl_dim_param
);
3660 for (int i
= nparam
- 1; i
>= 0; --i
) {
3661 if (!is_nested_parameter(space
, i
))
3663 mpa
= isl_multi_pw_aff_drop_dims(mpa
, isl_dim_param
, i
, 1);
3665 isl_space_free(space
);
3670 /* Remove all parameters from the index expression and access relation of "expr"
3671 * that refer to nested accesses.
3673 static struct pet_expr
*remove_nested_parameters(struct pet_expr
*expr
)
3675 expr
->acc
.access
= remove_nested_parameters(expr
->acc
.access
);
3676 expr
->acc
.index
= remove_nested_parameters(expr
->acc
.index
);
3677 if (!expr
->acc
.access
|| !expr
->acc
.index
)
3682 pet_expr_free(expr
);
3687 static struct pet_expr
*expr_remove_nested_parameters(
3688 struct pet_expr
*expr
, void *user
);
3691 static struct pet_expr
*expr_remove_nested_parameters(
3692 struct pet_expr
*expr
, void *user
)
3694 return remove_nested_parameters(expr
);
3697 /* Remove all nested access parameters from the schedule and all
3698 * accesses of "stmt".
3699 * There is no need to remove them from the domain as these parameters
3700 * have already been removed from the domain when this function is called.
3702 static struct pet_stmt
*remove_nested_parameters(struct pet_stmt
*stmt
)
3706 stmt
->schedule
= remove_nested_parameters(stmt
->schedule
);
3707 stmt
->body
= pet_expr_map_access(stmt
->body
,
3708 &expr_remove_nested_parameters
, NULL
);
3709 if (!stmt
->schedule
|| !stmt
->body
)
3711 for (int i
= 0; i
< stmt
->n_arg
; ++i
) {
3712 stmt
->args
[i
] = pet_expr_map_access(stmt
->args
[i
],
3713 &expr_remove_nested_parameters
, NULL
);
3720 pet_stmt_free(stmt
);
3724 /* For each nested access parameter in the domain of "stmt",
3725 * construct a corresponding pet_expr, place it before the original
3726 * elements in stmt->args and record its position in "param2pos".
3727 * n is the number of nested access parameters.
3729 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
3730 std::map
<int,int> ¶m2pos
)
3735 struct pet_expr
**args
;
3737 n_arg
= stmt
->n_arg
;
3738 args
= isl_calloc_array(ctx
, struct pet_expr
*, n
+ n_arg
);
3742 space
= isl_set_get_space(stmt
->domain
);
3743 n_arg
= extract_nested(space
, 0, args
, param2pos
);
3744 isl_space_free(space
);
3749 for (i
= 0; i
< stmt
->n_arg
; ++i
)
3750 args
[n_arg
+ i
] = stmt
->args
[i
];
3753 stmt
->n_arg
+= n_arg
;
3758 for (i
= 0; i
< n
; ++i
)
3759 pet_expr_free(args
[i
]);
3762 pet_stmt_free(stmt
);
3766 /* Check whether any of the arguments i of "stmt" starting at position "n"
3767 * is equal to one of the first "n" arguments j.
3768 * If so, combine the constraints on arguments i and j and remove
3771 static struct pet_stmt
*remove_duplicate_arguments(struct pet_stmt
*stmt
, int n
)
3780 if (n
== stmt
->n_arg
)
3783 map
= isl_set_unwrap(stmt
->domain
);
3785 for (i
= stmt
->n_arg
- 1; i
>= n
; --i
) {
3786 for (j
= 0; j
< n
; ++j
)
3787 if (pet_expr_is_equal(stmt
->args
[i
], stmt
->args
[j
]))
3792 map
= isl_map_equate(map
, isl_dim_out
, i
, isl_dim_out
, j
);
3793 map
= isl_map_project_out(map
, isl_dim_out
, i
, 1);
3795 pet_expr_free(stmt
->args
[i
]);
3796 for (j
= i
; j
+ 1 < stmt
->n_arg
; ++j
)
3797 stmt
->args
[j
] = stmt
->args
[j
+ 1];
3801 stmt
->domain
= isl_map_wrap(map
);
3806 pet_stmt_free(stmt
);
3810 /* Look for parameters in the iteration domain of "stmt" that
3811 * refer to nested accesses. In particular, these are
3812 * parameters with no name.
3814 * If there are any such parameters, then as many extra variables
3815 * (after identifying identical nested accesses) are inserted in the
3816 * range of the map wrapped inside the domain, before the original variables.
3817 * If the original domain is not a wrapped map, then a new wrapped
3818 * map is created with zero output dimensions.
3819 * The parameters are then equated to the corresponding output dimensions
3820 * and subsequently projected out, from the iteration domain,
3821 * the schedule and the access relations.
3822 * For each of the output dimensions, a corresponding argument
3823 * expression is inserted. Initially they are created with
3824 * a zero-dimensional domain, so they have to be embedded
3825 * in the current iteration domain.
3826 * param2pos maps the position of the parameter to the position
3827 * of the corresponding output dimension in the wrapped map.
3829 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3837 std::map
<int,int> param2pos
;
3842 n
= n_nested_parameter(stmt
->domain
);
3846 n_arg
= stmt
->n_arg
;
3847 stmt
= extract_nested(stmt
, n
, param2pos
);
3851 n
= stmt
->n_arg
- n_arg
;
3852 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3853 if (isl_set_is_wrapping(stmt
->domain
))
3854 map
= isl_set_unwrap(stmt
->domain
);
3856 map
= isl_map_from_domain(stmt
->domain
);
3857 map
= isl_map_insert_dims(map
, isl_dim_out
, 0, n
);
3859 for (int i
= nparam
- 1; i
>= 0; --i
) {
3862 if (!is_nested_parameter(map
, i
))
3865 id
= pet_expr_access_get_id(stmt
->args
[param2pos
[i
]]);
3866 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3867 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3869 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3872 stmt
->domain
= isl_map_wrap(map
);
3874 space
= isl_space_unwrap(isl_set_get_space(stmt
->domain
));
3875 space
= isl_space_from_domain(isl_space_domain(space
));
3876 ma
= isl_multi_aff_zero(space
);
3877 for (int pos
= 0; pos
< n
; ++pos
)
3878 stmt
->args
[pos
] = embed(stmt
->args
[pos
], ma
);
3879 isl_multi_aff_free(ma
);
3881 stmt
= remove_nested_parameters(stmt
);
3882 stmt
= remove_duplicate_arguments(stmt
, n
);
3887 /* For each statement in "scop", move the parameters that correspond
3888 * to nested access into the ranges of the domains and create
3889 * corresponding argument expressions.
3891 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3896 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3897 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3898 if (!scop
->stmts
[i
])
3904 pet_scop_free(scop
);
3908 /* Given an access expression "expr", is the variable accessed by
3909 * "expr" assigned anywhere inside "scop"?
3911 static bool is_assigned(pet_expr
*expr
, pet_scop
*scop
)
3913 bool assigned
= false;
3916 id
= pet_expr_access_get_id(expr
);
3917 assigned
= pet_scop_writes(scop
, id
);
3923 /* Are all nested access parameters in "pa" allowed given "scop".
3924 * In particular, is none of them written by anywhere inside "scop".
3926 * If "scop" has any skip conditions, then no nested access parameters
3927 * are allowed. In particular, if there is any nested access in a guard
3928 * for a piece of code containing a "continue", then we want to introduce
3929 * a separate statement for evaluating this guard so that we can express
3930 * that the result is false for all previous iterations.
3932 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3939 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3940 for (int i
= 0; i
< nparam
; ++i
) {
3942 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3946 if (!is_nested_parameter(id
)) {
3951 if (pet_scop_has_skip(scop
, pet_skip_now
)) {
3956 nested
= (Expr
*) isl_id_get_user(id
);
3957 expr
= extract_expr(nested
);
3958 allowed
= expr
&& expr
->type
== pet_expr_access
&&
3959 !is_assigned(expr
, scop
);
3961 pet_expr_free(expr
);
3971 /* Do we need to construct a skip condition of the given type
3972 * on an if statement, given that the if condition is non-affine?
3974 * pet_scop_filter_skip can only handle the case where the if condition
3975 * holds (the then branch) and the skip condition is universal.
3976 * In any other case, we need to construct a new skip condition.
3978 static bool need_skip(struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3979 bool have_else
, enum pet_skip type
)
3981 if (have_else
&& scop_else
&& pet_scop_has_skip(scop_else
, type
))
3983 if (scop_then
&& pet_scop_has_skip(scop_then
, type
) &&
3984 !pet_scop_has_universal_skip(scop_then
, type
))
3989 /* Do we need to construct a skip condition of the given type
3990 * on an if statement, given that the if condition is affine?
3992 * There is no need to construct a new skip condition if all
3993 * the skip conditions are affine.
3995 static bool need_skip_aff(struct pet_scop
*scop_then
,
3996 struct pet_scop
*scop_else
, bool have_else
, enum pet_skip type
)
3998 if (scop_then
&& pet_scop_has_var_skip(scop_then
, type
))
4000 if (have_else
&& scop_else
&& pet_scop_has_var_skip(scop_else
, type
))
4005 /* Do we need to construct a skip condition of the given type
4006 * on an if statement?
4008 static bool need_skip(struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
4009 bool have_else
, enum pet_skip type
, bool affine
)
4012 return need_skip_aff(scop_then
, scop_else
, have_else
, type
);
4014 return need_skip(scop_then
, scop_else
, have_else
, type
);
4017 /* Construct an affine expression pet_expr that evaluates
4018 * to the constant "val".
4020 static struct pet_expr
*universally(isl_ctx
*ctx
, int val
)
4022 isl_local_space
*ls
;
4024 isl_multi_pw_aff
*mpa
;
4026 ls
= isl_local_space_from_space(isl_space_set_alloc(ctx
, 0, 0));
4027 aff
= isl_aff_val_on_domain(ls
, isl_val_int_from_si(ctx
, val
));
4028 mpa
= isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
4030 return pet_expr_from_index(mpa
);
4033 /* Construct an affine expression pet_expr that evaluates
4034 * to the constant 1.
4036 static struct pet_expr
*universally_true(isl_ctx
*ctx
)
4038 return universally(ctx
, 1);
4041 /* Construct an affine expression pet_expr that evaluates
4042 * to the constant 0.
4044 static struct pet_expr
*universally_false(isl_ctx
*ctx
)
4046 return universally(ctx
, 0);
4049 /* Given an index expression "test_index" for the if condition,
4050 * an index expression "skip_index" for the skip condition and
4051 * scops for the then and else branches, construct a scop for
4052 * computing "skip_index".
4054 * The computed scop contains a single statement that essentially does
4056 * skip_index = test_cond ? skip_cond_then : skip_cond_else
4058 * If the skip conditions of the then and/or else branch are not affine,
4059 * then they need to be filtered by test_index.
4060 * If they are missing, then this means the skip condition is false.
4062 * Since we are constructing a skip condition for the if statement,
4063 * the skip conditions on the then and else branches are removed.
4065 static struct pet_scop
*extract_skip(PetScan
*scan
,
4066 __isl_take isl_multi_pw_aff
*test_index
,
4067 __isl_take isl_multi_pw_aff
*skip_index
,
4068 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
, bool have_else
,
4071 struct pet_expr
*expr_then
, *expr_else
, *expr
, *expr_skip
;
4072 struct pet_stmt
*stmt
;
4073 struct pet_scop
*scop
;
4074 isl_ctx
*ctx
= scan
->ctx
;
4078 if (have_else
&& !scop_else
)
4081 if (pet_scop_has_skip(scop_then
, type
)) {
4082 expr_then
= pet_scop_get_skip_expr(scop_then
, type
);
4083 pet_scop_reset_skip(scop_then
, type
);
4084 if (!pet_expr_is_affine(expr_then
))
4085 expr_then
= pet_expr_filter(expr_then
,
4086 isl_multi_pw_aff_copy(test_index
), 1);
4088 expr_then
= universally_false(ctx
);
4090 if (have_else
&& pet_scop_has_skip(scop_else
, type
)) {
4091 expr_else
= pet_scop_get_skip_expr(scop_else
, type
);
4092 pet_scop_reset_skip(scop_else
, type
);
4093 if (!pet_expr_is_affine(expr_else
))
4094 expr_else
= pet_expr_filter(expr_else
,
4095 isl_multi_pw_aff_copy(test_index
), 0);
4097 expr_else
= universally_false(ctx
);
4099 expr
= pet_expr_from_index(test_index
);
4100 expr
= pet_expr_new_ternary(ctx
, expr
, expr_then
, expr_else
);
4101 expr_skip
= pet_expr_from_index(isl_multi_pw_aff_copy(skip_index
));
4103 expr_skip
->acc
.write
= 1;
4104 expr_skip
->acc
.read
= 0;
4106 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, expr_skip
, expr
);
4107 stmt
= pet_stmt_from_pet_expr(ctx
, -1, NULL
, scan
->n_stmt
++, expr
);
4109 scop
= pet_scop_from_pet_stmt(ctx
, stmt
);
4110 scop
= scop_add_array(scop
, skip_index
, scan
->ast_context
);
4111 isl_multi_pw_aff_free(skip_index
);
4115 isl_multi_pw_aff_free(test_index
);
4116 isl_multi_pw_aff_free(skip_index
);
4120 /* Is scop's skip_now condition equal to its skip_later condition?
4121 * In particular, this means that it either has no skip_now condition
4122 * or both a skip_now and a skip_later condition (that are equal to each other).
4124 static bool skip_equals_skip_later(struct pet_scop
*scop
)
4126 int has_skip_now
, has_skip_later
;
4128 isl_multi_pw_aff
*skip_now
, *skip_later
;
4132 has_skip_now
= pet_scop_has_skip(scop
, pet_skip_now
);
4133 has_skip_later
= pet_scop_has_skip(scop
, pet_skip_later
);
4134 if (has_skip_now
!= has_skip_later
)
4139 skip_now
= pet_scop_get_skip(scop
, pet_skip_now
);
4140 skip_later
= pet_scop_get_skip(scop
, pet_skip_later
);
4141 equal
= isl_multi_pw_aff_is_equal(skip_now
, skip_later
);
4142 isl_multi_pw_aff_free(skip_now
);
4143 isl_multi_pw_aff_free(skip_later
);
4148 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
4150 static void drop_skip_later(struct pet_scop
*scop1
, struct pet_scop
*scop2
)
4152 pet_scop_reset_skip(scop1
, pet_skip_later
);
4153 pet_scop_reset_skip(scop2
, pet_skip_later
);
4156 /* Structure that handles the construction of skip conditions.
4158 * scop_then and scop_else represent the then and else branches
4159 * of the if statement
4161 * skip[type] is true if we need to construct a skip condition of that type
4162 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
4163 * are equal to each other
4164 * index[type] is an index expression from a zero-dimension domain
4165 * to the virtual array representing the skip condition
4166 * scop[type] is a scop for computing the skip condition
4168 struct pet_skip_info
{
4173 isl_multi_pw_aff
*index
[2];
4174 struct pet_scop
*scop
[2];
4176 pet_skip_info(isl_ctx
*ctx
) : ctx(ctx
) {}
4178 operator bool() { return skip
[pet_skip_now
] || skip
[pet_skip_later
]; }
4181 /* Structure that handles the construction of skip conditions on if statements.
4183 * scop_then and scop_else represent the then and else branches
4184 * of the if statement
4186 struct pet_skip_info_if
: public pet_skip_info
{
4187 struct pet_scop
*scop_then
, *scop_else
;
4190 pet_skip_info_if(isl_ctx
*ctx
, struct pet_scop
*scop_then
,
4191 struct pet_scop
*scop_else
, bool have_else
, bool affine
);
4192 void extract(PetScan
*scan
, __isl_keep isl_multi_pw_aff
*index
,
4193 enum pet_skip type
);
4194 void extract(PetScan
*scan
, __isl_keep isl_multi_pw_aff
*index
);
4195 void extract(PetScan
*scan
, __isl_keep isl_pw_aff
*cond
);
4196 struct pet_scop
*add(struct pet_scop
*scop
, enum pet_skip type
,
4198 struct pet_scop
*add(struct pet_scop
*scop
, int offset
);
4201 /* Initialize a pet_skip_info_if structure based on the then and else branches
4202 * and based on whether the if condition is affine or not.
4204 pet_skip_info_if::pet_skip_info_if(isl_ctx
*ctx
, struct pet_scop
*scop_then
,
4205 struct pet_scop
*scop_else
, bool have_else
, bool affine
) :
4206 pet_skip_info(ctx
), scop_then(scop_then
), scop_else(scop_else
),
4207 have_else(have_else
)
4209 skip
[pet_skip_now
] =
4210 need_skip(scop_then
, scop_else
, have_else
, pet_skip_now
, affine
);
4211 equal
= skip
[pet_skip_now
] && skip_equals_skip_later(scop_then
) &&
4212 (!have_else
|| skip_equals_skip_later(scop_else
));
4213 skip
[pet_skip_later
] = skip
[pet_skip_now
] && !equal
&&
4214 need_skip(scop_then
, scop_else
, have_else
, pet_skip_later
, affine
);
4217 /* If we need to construct a skip condition of the given type,
4220 * "mpa" represents the if condition.
4222 void pet_skip_info_if::extract(PetScan
*scan
,
4223 __isl_keep isl_multi_pw_aff
*mpa
, enum pet_skip type
)
4230 ctx
= isl_multi_pw_aff_get_ctx(mpa
);
4231 index
[type
] = create_test_index(ctx
, scan
->n_test
++);
4232 scop
[type
] = extract_skip(scan
, isl_multi_pw_aff_copy(mpa
),
4233 isl_multi_pw_aff_copy(index
[type
]),
4234 scop_then
, scop_else
, have_else
, type
);
4237 /* Construct the required skip conditions, given the if condition "index".
4239 void pet_skip_info_if::extract(PetScan
*scan
,
4240 __isl_keep isl_multi_pw_aff
*index
)
4242 extract(scan
, index
, pet_skip_now
);
4243 extract(scan
, index
, pet_skip_later
);
4245 drop_skip_later(scop_then
, scop_else
);
4248 /* Construct the required skip conditions, given the if condition "cond".
4250 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_pw_aff
*cond
)
4252 isl_multi_pw_aff
*test
;
4254 if (!skip
[pet_skip_now
] && !skip
[pet_skip_later
])
4257 test
= isl_multi_pw_aff_from_pw_aff(isl_pw_aff_copy(cond
));
4258 test
= isl_multi_pw_aff_from_range(test
);
4259 extract(scan
, test
);
4260 isl_multi_pw_aff_free(test
);
4263 /* Add the computed skip condition of the give type to "main" and
4264 * add the scop for computing the condition at the given offset.
4266 * If equal is set, then we only computed a skip condition for pet_skip_now,
4267 * but we also need to set it as main's pet_skip_later.
4269 struct pet_scop
*pet_skip_info_if::add(struct pet_scop
*main
,
4270 enum pet_skip type
, int offset
)
4275 scop
[type
] = pet_scop_prefix(scop
[type
], offset
);
4276 main
= pet_scop_add_par(ctx
, main
, scop
[type
]);
4280 main
= pet_scop_set_skip(main
, pet_skip_later
,
4281 isl_multi_pw_aff_copy(index
[type
]));
4283 main
= pet_scop_set_skip(main
, type
, index
[type
]);
4289 /* Add the computed skip conditions to "main" and
4290 * add the scops for computing the conditions at the given offset.
4292 struct pet_scop
*pet_skip_info_if::add(struct pet_scop
*scop
, int offset
)
4294 scop
= add(scop
, pet_skip_now
, offset
);
4295 scop
= add(scop
, pet_skip_later
, offset
);
4300 /* Construct a pet_scop for a non-affine if statement.
4302 * We create a separate statement that writes the result
4303 * of the non-affine condition to a virtual scalar.
4304 * A constraint requiring the value of this virtual scalar to be one
4305 * is added to the iteration domains of the then branch.
4306 * Similarly, a constraint requiring the value of this virtual scalar
4307 * to be zero is added to the iteration domains of the else branch, if any.
4308 * We adjust the schedules to ensure that the virtual scalar is written
4309 * before it is read.
4311 * If there are any breaks or continues in the then and/or else
4312 * branches, then we may have to compute a new skip condition.
4313 * This is handled using a pet_skip_info_if object.
4314 * On initialization, the object checks if skip conditions need
4315 * to be computed. If so, it does so in "extract" and adds them in "add".
4317 struct pet_scop
*PetScan::extract_non_affine_if(Expr
*cond
,
4318 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
4319 bool have_else
, int stmt_id
)
4321 struct pet_scop
*scop
;
4322 isl_multi_pw_aff
*test_index
;
4323 int save_n_stmt
= n_stmt
;
4325 test_index
= create_test_index(ctx
, n_test
++);
4327 scop
= extract_non_affine_condition(cond
,
4328 isl_multi_pw_aff_copy(test_index
));
4329 n_stmt
= save_n_stmt
;
4330 scop
= scop_add_array(scop
, test_index
, ast_context
);
4332 pet_skip_info_if
skip(ctx
, scop_then
, scop_else
, have_else
, false);
4333 skip
.extract(this, test_index
);
4335 scop
= pet_scop_prefix(scop
, 0);
4336 scop_then
= pet_scop_prefix(scop_then
, 1);
4337 scop_then
= pet_scop_filter(scop_then
,
4338 isl_multi_pw_aff_copy(test_index
), 1);
4340 scop_else
= pet_scop_prefix(scop_else
, 1);
4341 scop_else
= pet_scop_filter(scop_else
, test_index
, 0);
4342 scop_then
= pet_scop_add_par(ctx
, scop_then
, scop_else
);
4344 isl_multi_pw_aff_free(test_index
);
4346 scop
= pet_scop_add_seq(ctx
, scop
, scop_then
);
4348 scop
= skip
.add(scop
, 2);
4353 /* Construct a pet_scop for an if statement.
4355 * If the condition fits the pattern of a conditional assignment,
4356 * then it is handled by extract_conditional_assignment.
4357 * Otherwise, we do the following.
4359 * If the condition is affine, then the condition is added
4360 * to the iteration domains of the then branch, while the
4361 * opposite of the condition in added to the iteration domains
4362 * of the else branch, if any.
4363 * We allow the condition to be dynamic, i.e., to refer to
4364 * scalars or array elements that may be written to outside
4365 * of the given if statement. These nested accesses are then represented
4366 * as output dimensions in the wrapping iteration domain.
4367 * If it also written _inside_ the then or else branch, then
4368 * we treat the condition as non-affine.
4369 * As explained in extract_non_affine_if, this will introduce
4370 * an extra statement.
4371 * For aesthetic reasons, we want this statement to have a statement
4372 * number that is lower than those of the then and else branches.
4373 * In order to evaluate if will need such a statement, however, we
4374 * first construct scops for the then and else branches.
4375 * We therefore reserve a statement number if we might have to
4376 * introduce such an extra statement.
4378 * If the condition is not affine, then the scop is created in
4379 * extract_non_affine_if.
4381 * If there are any breaks or continues in the then and/or else
4382 * branches, then we may have to compute a new skip condition.
4383 * This is handled using a pet_skip_info_if object.
4384 * On initialization, the object checks if skip conditions need
4385 * to be computed. If so, it does so in "extract" and adds them in "add".
4387 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
4389 struct pet_scop
*scop_then
, *scop_else
= NULL
, *scop
;
4395 scop
= extract_conditional_assignment(stmt
);
4399 cond
= try_extract_nested_condition(stmt
->getCond());
4400 if (allow_nested
&& (!cond
|| has_nested(cond
)))
4404 assigned_value_cache
cache(assigned_value
);
4405 scop_then
= extract(stmt
->getThen());
4408 if (stmt
->getElse()) {
4409 assigned_value_cache
cache(assigned_value
);
4410 scop_else
= extract(stmt
->getElse());
4411 if (options
->autodetect
) {
4412 if (scop_then
&& !scop_else
) {
4414 isl_pw_aff_free(cond
);
4417 if (!scop_then
&& scop_else
) {
4419 isl_pw_aff_free(cond
);
4426 (!is_nested_allowed(cond
, scop_then
) ||
4427 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
4428 isl_pw_aff_free(cond
);
4431 if (allow_nested
&& !cond
)
4432 return extract_non_affine_if(stmt
->getCond(), scop_then
,
4433 scop_else
, stmt
->getElse(), stmt_id
);
4436 cond
= extract_condition(stmt
->getCond());
4438 pet_skip_info_if
skip(ctx
, scop_then
, scop_else
, stmt
->getElse(), true);
4439 skip
.extract(this, cond
);
4441 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
4442 set
= isl_pw_aff_non_zero_set(cond
);
4443 scop
= pet_scop_restrict(scop_then
, isl_set_copy(set
));
4445 if (stmt
->getElse()) {
4446 set
= isl_set_subtract(isl_set_copy(valid
), set
);
4447 scop_else
= pet_scop_restrict(scop_else
, set
);
4448 scop
= pet_scop_add_par(ctx
, scop
, scop_else
);
4451 scop
= resolve_nested(scop
);
4452 scop
= pet_scop_restrict_context(scop
, valid
);
4455 scop
= pet_scop_prefix(scop
, 0);
4456 scop
= skip
.add(scop
, 1);
4461 /* Try and construct a pet_scop for a label statement.
4462 * We currently only allow labels on expression statements.
4464 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
4469 sub
= stmt
->getSubStmt();
4470 if (!isa
<Expr
>(sub
)) {
4475 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
4477 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
4480 /* Return a one-dimensional multi piecewise affine expression that is equal
4481 * to the constant 1 and is defined over a zero-dimensional domain.
4483 static __isl_give isl_multi_pw_aff
*one_mpa(isl_ctx
*ctx
)
4486 isl_local_space
*ls
;
4489 space
= isl_space_set_alloc(ctx
, 0, 0);
4490 ls
= isl_local_space_from_space(space
);
4491 aff
= isl_aff_zero_on_domain(ls
);
4492 aff
= isl_aff_set_constant_si(aff
, 1);
4494 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff
));
4497 /* Construct a pet_scop for a continue statement.
4499 * We simply create an empty scop with a universal pet_skip_now
4500 * skip condition. This skip condition will then be taken into
4501 * account by the enclosing loop construct, possibly after
4502 * being incorporated into outer skip conditions.
4504 struct pet_scop
*PetScan::extract(ContinueStmt
*stmt
)
4508 scop
= pet_scop_empty(ctx
);
4512 scop
= pet_scop_set_skip(scop
, pet_skip_now
, one_mpa(ctx
));
4517 /* Construct a pet_scop for a break statement.
4519 * We simply create an empty scop with both a universal pet_skip_now
4520 * skip condition and a universal pet_skip_later skip condition.
4521 * These skip conditions will then be taken into
4522 * account by the enclosing loop construct, possibly after
4523 * being incorporated into outer skip conditions.
4525 struct pet_scop
*PetScan::extract(BreakStmt
*stmt
)
4528 isl_multi_pw_aff
*skip
;
4530 scop
= pet_scop_empty(ctx
);
4534 skip
= one_mpa(ctx
);
4535 scop
= pet_scop_set_skip(scop
, pet_skip_now
,
4536 isl_multi_pw_aff_copy(skip
));
4537 scop
= pet_scop_set_skip(scop
, pet_skip_later
, skip
);
4542 /* Try and construct a pet_scop corresponding to "stmt".
4544 * If "stmt" is a compound statement, then "skip_declarations"
4545 * indicates whether we should skip initial declarations in the
4546 * compound statement.
4548 * If the constructed pet_scop is not a (possibly) partial representation
4549 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4550 * In particular, if skip_declarations, then we may have skipped declarations
4551 * inside "stmt" and so the pet_scop may not represent the entire "stmt".
4552 * Note that this function may be called with "stmt" referring to the entire
4553 * body of the function, including the outer braces. In such cases,
4554 * skip_declarations will be set and the braces will not be taken into
4555 * account in scop->start and scop->end.
4557 struct pet_scop
*PetScan::extract(Stmt
*stmt
, bool skip_declarations
)
4559 struct pet_scop
*scop
;
4560 unsigned start
, end
;
4562 SourceManager
&SM
= PP
.getSourceManager();
4563 const LangOptions
&LO
= PP
.getLangOpts();
4565 if (isa
<Expr
>(stmt
))
4566 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
4568 switch (stmt
->getStmtClass()) {
4569 case Stmt::WhileStmtClass
:
4570 scop
= extract(cast
<WhileStmt
>(stmt
));
4572 case Stmt::ForStmtClass
:
4573 scop
= extract_for(cast
<ForStmt
>(stmt
));
4575 case Stmt::IfStmtClass
:
4576 scop
= extract(cast
<IfStmt
>(stmt
));
4578 case Stmt::CompoundStmtClass
:
4579 scop
= extract(cast
<CompoundStmt
>(stmt
), skip_declarations
);
4581 case Stmt::LabelStmtClass
:
4582 scop
= extract(cast
<LabelStmt
>(stmt
));
4584 case Stmt::ContinueStmtClass
:
4585 scop
= extract(cast
<ContinueStmt
>(stmt
));
4587 case Stmt::BreakStmtClass
:
4588 scop
= extract(cast
<BreakStmt
>(stmt
));
4590 case Stmt::DeclStmtClass
:
4591 scop
= extract(cast
<DeclStmt
>(stmt
));
4598 if (partial
|| skip_declarations
)
4601 loc
= stmt
->getLocStart();
4602 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
);
4603 start
= getExpansionOffset(SM
, loc
);
4604 loc
= PP
.getLocForEndOfToken(stmt
->getLocEnd());
4605 end
= getExpansionOffset(SM
, loc
);
4606 scop
= pet_scop_update_start_end(scop
, start
, end
);
4611 /* Do we need to construct a skip condition of the given type
4612 * on a sequence of statements?
4614 * There is no need to construct a new skip condition if only
4615 * only of the two statements has a skip condition or if both
4616 * of their skip conditions are affine.
4618 * In principle we also don't need a new continuation variable if
4619 * the continuation of scop2 is affine, but then we would need
4620 * to allow more complicated forms of continuations.
4622 static bool need_skip_seq(struct pet_scop
*scop1
, struct pet_scop
*scop2
,
4625 if (!scop1
|| !pet_scop_has_skip(scop1
, type
))
4627 if (!scop2
|| !pet_scop_has_skip(scop2
, type
))
4629 if (pet_scop_has_affine_skip(scop1
, type
) &&
4630 pet_scop_has_affine_skip(scop2
, type
))
4635 /* Construct a scop for computing the skip condition of the given type and
4636 * with index expression "skip_index" for a sequence of two scops "scop1"
4639 * The computed scop contains a single statement that essentially does
4641 * skip_index = skip_cond_1 ? 1 : skip_cond_2
4643 * or, in other words, skip_cond1 || skip_cond2.
4644 * In this expression, skip_cond_2 is filtered to reflect that it is
4645 * only evaluated when skip_cond_1 is false.
4647 * The skip condition on scop1 is not removed because it still needs
4648 * to be applied to scop2 when these two scops are combined.
4650 static struct pet_scop
*extract_skip_seq(PetScan
*ps
,
4651 __isl_take isl_multi_pw_aff
*skip_index
,
4652 struct pet_scop
*scop1
, struct pet_scop
*scop2
, enum pet_skip type
)
4654 struct pet_expr
*expr1
, *expr2
, *expr
, *expr_skip
;
4655 struct pet_stmt
*stmt
;
4656 struct pet_scop
*scop
;
4657 isl_ctx
*ctx
= ps
->ctx
;
4659 if (!scop1
|| !scop2
)
4662 expr1
= pet_scop_get_skip_expr(scop1
, type
);
4663 expr2
= pet_scop_get_skip_expr(scop2
, type
);
4664 pet_scop_reset_skip(scop2
, type
);
4666 expr2
= pet_expr_filter(expr2
,
4667 isl_multi_pw_aff_copy(expr1
->acc
.index
), 0);
4669 expr
= universally_true(ctx
);
4670 expr
= pet_expr_new_ternary(ctx
, expr1
, expr
, expr2
);
4671 expr_skip
= pet_expr_from_index(isl_multi_pw_aff_copy(skip_index
));
4673 expr_skip
->acc
.write
= 1;
4674 expr_skip
->acc
.read
= 0;
4676 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, expr_skip
, expr
);
4677 stmt
= pet_stmt_from_pet_expr(ctx
, -1, NULL
, ps
->n_stmt
++, expr
);
4679 scop
= pet_scop_from_pet_stmt(ctx
, stmt
);
4680 scop
= scop_add_array(scop
, skip_index
, ps
->ast_context
);
4681 isl_multi_pw_aff_free(skip_index
);
4685 isl_multi_pw_aff_free(skip_index
);
4689 /* Structure that handles the construction of skip conditions
4690 * on sequences of statements.
4692 * scop1 and scop2 represent the two statements that are combined
4694 struct pet_skip_info_seq
: public pet_skip_info
{
4695 struct pet_scop
*scop1
, *scop2
;
4697 pet_skip_info_seq(isl_ctx
*ctx
, struct pet_scop
*scop1
,
4698 struct pet_scop
*scop2
);
4699 void extract(PetScan
*scan
, enum pet_skip type
);
4700 void extract(PetScan
*scan
);
4701 struct pet_scop
*add(struct pet_scop
*scop
, enum pet_skip type
,
4703 struct pet_scop
*add(struct pet_scop
*scop
, int offset
);
4706 /* Initialize a pet_skip_info_seq structure based on
4707 * on the two statements that are going to be combined.
4709 pet_skip_info_seq::pet_skip_info_seq(isl_ctx
*ctx
, struct pet_scop
*scop1
,
4710 struct pet_scop
*scop2
) : pet_skip_info(ctx
), scop1(scop1
), scop2(scop2
)
4712 skip
[pet_skip_now
] = need_skip_seq(scop1
, scop2
, pet_skip_now
);
4713 equal
= skip
[pet_skip_now
] && skip_equals_skip_later(scop1
) &&
4714 skip_equals_skip_later(scop2
);
4715 skip
[pet_skip_later
] = skip
[pet_skip_now
] && !equal
&&
4716 need_skip_seq(scop1
, scop2
, pet_skip_later
);
4719 /* If we need to construct a skip condition of the given type,
4722 void pet_skip_info_seq::extract(PetScan
*scan
, enum pet_skip type
)
4727 index
[type
] = create_test_index(ctx
, scan
->n_test
++);
4728 scop
[type
] = extract_skip_seq(scan
, isl_multi_pw_aff_copy(index
[type
]),
4729 scop1
, scop2
, type
);
4732 /* Construct the required skip conditions.
4734 void pet_skip_info_seq::extract(PetScan
*scan
)
4736 extract(scan
, pet_skip_now
);
4737 extract(scan
, pet_skip_later
);
4739 drop_skip_later(scop1
, scop2
);
4742 /* Add the computed skip condition of the given type to "main" and
4743 * add the scop for computing the condition at the given offset (the statement
4744 * number). Within this offset, the condition is computed at position 1
4745 * to ensure that it is computed after the corresponding statement.
4747 * If equal is set, then we only computed a skip condition for pet_skip_now,
4748 * but we also need to set it as main's pet_skip_later.
4750 struct pet_scop
*pet_skip_info_seq::add(struct pet_scop
*main
,
4751 enum pet_skip type
, int offset
)
4756 scop
[type
] = pet_scop_prefix(scop
[type
], 1);
4757 scop
[type
] = pet_scop_prefix(scop
[type
], offset
);
4758 main
= pet_scop_add_par(ctx
, main
, scop
[type
]);
4762 main
= pet_scop_set_skip(main
, pet_skip_later
,
4763 isl_multi_pw_aff_copy(index
[type
]));
4765 main
= pet_scop_set_skip(main
, type
, index
[type
]);
4771 /* Add the computed skip conditions to "main" and
4772 * add the scops for computing the conditions at the given offset.
4774 struct pet_scop
*pet_skip_info_seq::add(struct pet_scop
*scop
, int offset
)
4776 scop
= add(scop
, pet_skip_now
, offset
);
4777 scop
= add(scop
, pet_skip_later
, offset
);
4782 /* Extract a clone of the kill statement in "scop".
4783 * "scop" is expected to have been created from a DeclStmt
4784 * and should have the kill as its first statement.
4786 struct pet_stmt
*PetScan::extract_kill(struct pet_scop
*scop
)
4788 struct pet_expr
*kill
;
4789 struct pet_stmt
*stmt
;
4790 isl_multi_pw_aff
*index
;
4795 if (scop
->n_stmt
< 1)
4796 isl_die(ctx
, isl_error_internal
,
4797 "expecting at least one statement", return NULL
);
4798 stmt
= scop
->stmts
[0];
4799 if (stmt
->body
->type
!= pet_expr_unary
||
4800 stmt
->body
->op
!= pet_op_kill
)
4801 isl_die(ctx
, isl_error_internal
,
4802 "expecting kill statement", return NULL
);
4804 index
= isl_multi_pw_aff_copy(stmt
->body
->args
[0]->acc
.index
);
4805 access
= isl_map_copy(stmt
->body
->args
[0]->acc
.access
);
4806 index
= isl_multi_pw_aff_reset_tuple_id(index
, isl_dim_in
);
4807 access
= isl_map_reset_tuple_id(access
, isl_dim_in
);
4808 kill
= pet_expr_kill_from_access_and_index(access
, index
);
4809 return pet_stmt_from_pet_expr(ctx
, stmt
->line
, NULL
, n_stmt
++, kill
);
4812 /* Mark all arrays in "scop" as being exposed.
4814 static struct pet_scop
*mark_exposed(struct pet_scop
*scop
)
4818 for (int i
= 0; i
< scop
->n_array
; ++i
)
4819 scop
->arrays
[i
]->exposed
= 1;
4823 /* Try and construct a pet_scop corresponding to (part of)
4824 * a sequence of statements.
4826 * "block" is set if the sequence respresents the children of
4827 * a compound statement.
4828 * "skip_declarations" is set if we should skip initial declarations
4829 * in the sequence of statements.
4831 * If there are any breaks or continues in the individual statements,
4832 * then we may have to compute a new skip condition.
4833 * This is handled using a pet_skip_info_seq object.
4834 * On initialization, the object checks if skip conditions need
4835 * to be computed. If so, it does so in "extract" and adds them in "add".
4837 * If "block" is set, then we need to insert kill statements at
4838 * the end of the block for any array that has been declared by
4839 * one of the statements in the sequence. Each of these declarations
4840 * results in the construction of a kill statement at the place
4841 * of the declaration, so we simply collect duplicates of
4842 * those kill statements and append these duplicates to the constructed scop.
4844 * If "block" is not set, then any array declared by one of the statements
4845 * in the sequence is marked as being exposed.
4847 * If autodetect is set, then we allow the extraction of only a subrange
4848 * of the sequence of statements. However, if there is at least one statement
4849 * for which we could not construct a scop and the final range contains
4850 * either no statements or at least one kill, then we discard the entire
4853 struct pet_scop
*PetScan::extract(StmtRange stmt_range
, bool block
,
4854 bool skip_declarations
)
4859 bool partial_range
= false;
4860 set
<struct pet_stmt
*> kills
;
4861 set
<struct pet_stmt
*>::iterator it
;
4863 scop
= pet_scop_empty(ctx
);
4864 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
4866 struct pet_scop
*scop_i
;
4868 if (skip_declarations
&&
4869 child
->getStmtClass() == Stmt::DeclStmtClass
)
4872 scop_i
= extract(child
);
4873 if (scop
->n_stmt
!= 0 && partial
) {
4874 pet_scop_free(scop_i
);
4877 pet_skip_info_seq
skip(ctx
, scop
, scop_i
);
4880 scop_i
= pet_scop_prefix(scop_i
, 0);
4881 if (scop_i
&& child
->getStmtClass() == Stmt::DeclStmtClass
) {
4883 kills
.insert(extract_kill(scop_i
));
4885 scop_i
= mark_exposed(scop_i
);
4887 scop_i
= pet_scop_prefix(scop_i
, j
);
4888 if (options
->autodetect
) {
4890 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4892 partial_range
= true;
4893 if (scop
->n_stmt
!= 0 && !scop_i
)
4896 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4899 scop
= skip
.add(scop
, j
);
4901 if (partial
|| !scop
)
4905 for (it
= kills
.begin(); it
!= kills
.end(); ++it
) {
4907 scop_j
= pet_scop_from_pet_stmt(ctx
, *it
);
4908 scop_j
= pet_scop_prefix(scop_j
, j
);
4909 scop
= pet_scop_add_seq(ctx
, scop
, scop_j
);
4912 if (scop
&& partial_range
) {
4913 if (scop
->n_stmt
== 0 || kills
.size() != 0) {
4914 pet_scop_free(scop
);
4923 /* Check if the scop marked by the user is exactly this Stmt
4924 * or part of this Stmt.
4925 * If so, return a pet_scop corresponding to the marked region.
4926 * Otherwise, return NULL.
4928 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
4930 SourceManager
&SM
= PP
.getSourceManager();
4931 unsigned start_off
, end_off
;
4933 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
4934 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
4936 if (start_off
> loc
.end
)
4938 if (end_off
< loc
.start
)
4940 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
4941 return extract(stmt
);
4945 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
4946 Stmt
*child
= *start
;
4949 start_off
= getExpansionOffset(SM
, child
->getLocStart());
4950 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
4951 if (start_off
< loc
.start
&& end_off
>= loc
.end
)
4953 if (start_off
>= loc
.start
)
4958 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
4960 start_off
= SM
.getFileOffset(child
->getLocStart());
4961 if (start_off
>= loc
.end
)
4965 return extract(StmtRange(start
, end
), false, false);
4968 /* Set the size of index "pos" of "array" to "size".
4969 * In particular, add a constraint of the form
4973 * to array->extent and a constraint of the form
4977 * to array->context.
4979 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
4980 __isl_take isl_pw_aff
*size
)
4990 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
4991 array
->context
= isl_set_intersect(array
->context
, valid
);
4993 dim
= isl_set_get_space(array
->extent
);
4994 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
4995 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
4996 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
4997 index
= isl_pw_aff_alloc(univ
, aff
);
4999 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
5000 isl_set_dim(array
->extent
, isl_dim_set
));
5001 id
= isl_set_get_tuple_id(array
->extent
);
5002 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
5003 bound
= isl_pw_aff_lt_set(index
, size
);
5005 array
->extent
= isl_set_intersect(array
->extent
, bound
);
5007 if (!array
->context
|| !array
->extent
)
5012 pet_array_free(array
);
5016 /* Figure out the size of the array at position "pos" and all
5017 * subsequent positions from "type" and update "array" accordingly.
5019 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
5020 const Type
*type
, int pos
)
5022 const ArrayType
*atype
;
5028 if (type
->isPointerType()) {
5029 type
= type
->getPointeeType().getTypePtr();
5030 return set_upper_bounds(array
, type
, pos
+ 1);
5032 if (!type
->isArrayType())
5035 type
= type
->getCanonicalTypeInternal().getTypePtr();
5036 atype
= cast
<ArrayType
>(type
);
5038 if (type
->isConstantArrayType()) {
5039 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
5040 size
= extract_affine(ca
->getSize());
5041 array
= update_size(array
, pos
, size
);
5042 } else if (type
->isVariableArrayType()) {
5043 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
5044 size
= extract_affine(vla
->getSizeExpr());
5045 array
= update_size(array
, pos
, size
);
5048 type
= atype
->getElementType().getTypePtr();
5050 return set_upper_bounds(array
, type
, pos
+ 1);
5053 /* Is "T" the type of a variable length array with static size?
5055 static bool is_vla_with_static_size(QualType T
)
5057 const VariableArrayType
*vlatype
;
5059 if (!T
->isVariableArrayType())
5061 vlatype
= cast
<VariableArrayType
>(T
);
5062 return vlatype
->getSizeModifier() == VariableArrayType::Static
;
5065 /* Return the type of "decl" as an array.
5067 * In particular, if "decl" is a parameter declaration that
5068 * is a variable length array with a static size, then
5069 * return the original type (i.e., the variable length array).
5070 * Otherwise, return the type of decl.
5072 static QualType
get_array_type(ValueDecl
*decl
)
5077 parm
= dyn_cast
<ParmVarDecl
>(decl
);
5079 return decl
->getType();
5081 T
= parm
->getOriginalType();
5082 if (!is_vla_with_static_size(T
))
5083 return decl
->getType();
5087 /* Construct and return a pet_array corresponding to the variable "decl".
5088 * In particular, initialize array->extent to
5090 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
5092 * and then call set_upper_bounds to set the upper bounds on the indices
5093 * based on the type of the variable.
5095 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
)
5097 struct pet_array
*array
;
5098 QualType qt
= get_array_type(decl
);
5099 const Type
*type
= qt
.getTypePtr();
5100 int depth
= array_depth(type
);
5101 QualType base
= pet_clang_base_type(qt
);
5106 array
= isl_calloc_type(ctx
, struct pet_array
);
5110 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
5111 dim
= isl_space_set_alloc(ctx
, 0, depth
);
5112 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
5114 array
->extent
= isl_set_nat_universe(dim
);
5116 dim
= isl_space_params_alloc(ctx
, 0);
5117 array
->context
= isl_set_universe(dim
);
5119 array
= set_upper_bounds(array
, type
, 0);
5123 name
= base
.getAsString();
5124 array
->element_type
= strdup(name
.c_str());
5125 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
5130 /* Construct a list of pet_arrays, one for each array (or scalar)
5131 * accessed inside "scop", add this list to "scop" and return the result.
5133 * The context of "scop" is updated with the intersection of
5134 * the contexts of all arrays, i.e., constraints on the parameters
5135 * that ensure that the arrays have a valid (non-negative) size.
5137 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
5140 set
<ValueDecl
*> arrays
;
5141 set
<ValueDecl
*>::iterator it
;
5143 struct pet_array
**scop_arrays
;
5148 pet_scop_collect_arrays(scop
, arrays
);
5149 if (arrays
.size() == 0)
5152 n_array
= scop
->n_array
;
5154 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
5155 n_array
+ arrays
.size());
5158 scop
->arrays
= scop_arrays
;
5160 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
5161 struct pet_array
*array
;
5162 scop
->arrays
[n_array
+ i
] = array
= extract_array(ctx
, *it
);
5163 if (!scop
->arrays
[n_array
+ i
])
5166 scop
->context
= isl_set_intersect(scop
->context
,
5167 isl_set_copy(array
->context
));
5174 pet_scop_free(scop
);
5178 /* Bound all parameters in scop->context to the possible values
5179 * of the corresponding C variable.
5181 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
5188 n
= isl_set_dim(scop
->context
, isl_dim_param
);
5189 for (int i
= 0; i
< n
; ++i
) {
5193 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
5194 if (is_nested_parameter(id
)) {
5196 isl_die(isl_set_get_ctx(scop
->context
),
5198 "unresolved nested parameter", goto error
);
5200 decl
= (ValueDecl
*) isl_id_get_user(id
);
5203 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
5211 pet_scop_free(scop
);
5215 /* Construct a pet_scop from the given function.
5217 * If the scop was delimited by scop and endscop pragmas, then we override
5218 * the file offsets by those derived from the pragmas.
5220 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
5225 stmt
= fd
->getBody();
5227 if (options
->autodetect
)
5228 scop
= extract(stmt
, true);
5231 scop
= pet_scop_update_start_end(scop
, loc
.start
, loc
.end
);
5233 scop
= pet_scop_detect_parameter_accesses(scop
);
5234 scop
= scan_arrays(scop
);
5235 scop
= add_parameter_bounds(scop
);
5236 scop
= pet_scop_gist(scop
, value_bounds
);