2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012 Ecole Normale Superieure. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
39 #include <llvm/Support/raw_ostream.h>
40 #include <clang/AST/ASTContext.h>
41 #include <clang/AST/ASTDiagnostic.h>
42 #include <clang/AST/Expr.h>
43 #include <clang/AST/RecursiveASTVisitor.h>
46 #include <isl/space.h>
53 #include "scop_plus.h"
58 using namespace clang
;
60 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
61 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
63 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
64 SourceLocation(), var
, false, var
->getInnerLocStart(),
65 var
->getType(), VK_LValue
);
67 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
68 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
70 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
71 SourceLocation(), var
, var
->getInnerLocStart(), var
->getType(),
75 static DeclRefExpr
*create_DeclRefExpr(VarDecl
*var
)
77 return DeclRefExpr::Create(var
->getASTContext(), var
->getQualifierLoc(),
78 var
, var
->getInnerLocStart(), var
->getType(), VK_LValue
);
82 /* Check if the element type corresponding to the given array type
83 * has a const qualifier.
85 static bool const_base(QualType qt
)
87 const Type
*type
= qt
.getTypePtr();
89 if (type
->isPointerType())
90 return const_base(type
->getPointeeType());
91 if (type
->isArrayType()) {
92 const ArrayType
*atype
;
93 type
= type
->getCanonicalTypeInternal().getTypePtr();
94 atype
= cast
<ArrayType
>(type
);
95 return const_base(atype
->getElementType());
98 return qt
.isConstQualified();
101 /* Mark "decl" as having an unknown value in "assigned_value".
103 * If no (known or unknown) value was assigned to "decl" before,
104 * then it may have been treated as a parameter before and may
105 * therefore appear in a value assigned to another variable.
106 * If so, this assignment needs to be turned into an unknown value too.
108 static void clear_assignment(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
,
111 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
;
113 it
= assigned_value
.find(decl
);
115 assigned_value
[decl
] = NULL
;
117 if (it
== assigned_value
.end())
120 for (it
= assigned_value
.begin(); it
!= assigned_value
.end(); ++it
) {
121 isl_pw_aff
*pa
= it
->second
;
122 int nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
124 for (int i
= 0; i
< nparam
; ++i
) {
127 if (!isl_pw_aff_has_dim_id(pa
, isl_dim_param
, i
))
129 id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
130 if (isl_id_get_user(id
) == decl
)
137 /* Look for any assignments to scalar variables in part of the parse
138 * tree and set assigned_value to NULL for each of them.
139 * Also reset assigned_value if the address of a scalar variable
140 * is being taken. As an exception, if the address is passed to a function
141 * that is declared to receive a const pointer, then assigned_value is
144 * This ensures that we won't use any previously stored value
145 * in the current subtree and its parents.
147 struct clear_assignments
: RecursiveASTVisitor
<clear_assignments
> {
148 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
149 set
<UnaryOperator
*> skip
;
151 clear_assignments(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
152 assigned_value(assigned_value
) {}
154 /* Check for "address of" operators whose value is passed
155 * to a const pointer argument and add them to "skip", so that
156 * we can skip them in VisitUnaryOperator.
158 bool VisitCallExpr(CallExpr
*expr
) {
160 fd
= expr
->getDirectCallee();
163 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
164 Expr
*arg
= expr
->getArg(i
);
166 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
167 ImplicitCastExpr
*ice
;
168 ice
= cast
<ImplicitCastExpr
>(arg
);
169 arg
= ice
->getSubExpr();
171 if (arg
->getStmtClass() != Stmt::UnaryOperatorClass
)
173 op
= cast
<UnaryOperator
>(arg
);
174 if (op
->getOpcode() != UO_AddrOf
)
176 if (const_base(fd
->getParamDecl(i
)->getType()))
182 bool VisitUnaryOperator(UnaryOperator
*expr
) {
187 switch (expr
->getOpcode()) {
197 if (skip
.find(expr
) != skip
.end())
200 arg
= expr
->getSubExpr();
201 if (arg
->getStmtClass() != Stmt::DeclRefExprClass
)
203 ref
= cast
<DeclRefExpr
>(arg
);
204 decl
= ref
->getDecl();
205 clear_assignment(assigned_value
, decl
);
209 bool VisitBinaryOperator(BinaryOperator
*expr
) {
214 if (!expr
->isAssignmentOp())
216 lhs
= expr
->getLHS();
217 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
)
219 ref
= cast
<DeclRefExpr
>(lhs
);
220 decl
= ref
->getDecl();
221 clear_assignment(assigned_value
, decl
);
226 /* Keep a copy of the currently assigned values.
228 * Any variable that is assigned a value inside the current scope
229 * is removed again when we leave the scope (either because it wasn't
230 * stored in the cache or because it has a different value in the cache).
232 struct assigned_value_cache
{
233 map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
;
234 map
<ValueDecl
*, isl_pw_aff
*> cache
;
236 assigned_value_cache(map
<ValueDecl
*, isl_pw_aff
*> &assigned_value
) :
237 assigned_value(assigned_value
), cache(assigned_value
) {}
238 ~assigned_value_cache() {
239 map
<ValueDecl
*, isl_pw_aff
*>::iterator it
= cache
.begin();
240 for (it
= assigned_value
.begin(); it
!= assigned_value
.end();
243 (cache
.find(it
->first
) != cache
.end() &&
244 cache
[it
->first
] != it
->second
))
245 cache
[it
->first
] = NULL
;
247 assigned_value
= cache
;
251 /* Insert an expression into the collection of expressions,
252 * provided it is not already in there.
253 * The isl_pw_affs are freed in the destructor.
255 void PetScan::insert_expression(__isl_take isl_pw_aff
*expr
)
257 std::set
<isl_pw_aff
*>::iterator it
;
259 if (expressions
.find(expr
) == expressions
.end())
260 expressions
.insert(expr
);
262 isl_pw_aff_free(expr
);
267 std::set
<isl_pw_aff
*>::iterator it
;
269 for (it
= expressions
.begin(); it
!= expressions
.end(); ++it
)
270 isl_pw_aff_free(*it
);
272 isl_union_map_free(value_bounds
);
275 /* Called if we found something we (currently) cannot handle.
276 * We'll provide more informative warnings later.
278 * We only actually complain if autodetect is false.
280 void PetScan::unsupported(Stmt
*stmt
, const char *msg
)
282 if (options
->autodetect
)
285 SourceLocation loc
= stmt
->getLocStart();
286 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
287 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
288 msg
? msg
: "unsupported");
289 DiagnosticBuilder B
= diag
.Report(loc
, id
) << stmt
->getSourceRange();
292 /* Extract an integer from "expr".
294 __isl_give isl_val
*PetScan::extract_int(isl_ctx
*ctx
, IntegerLiteral
*expr
)
296 const Type
*type
= expr
->getType().getTypePtr();
297 int is_signed
= type
->hasSignedIntegerRepresentation();
300 int64_t i
= expr
->getValue().getSExtValue();
301 return isl_val_int_from_si(ctx
, i
);
303 uint64_t i
= expr
->getValue().getZExtValue();
304 return isl_val_int_from_ui(ctx
, i
);
308 /* Extract an integer from "expr".
309 * Return NULL if "expr" does not (obviously) represent an integer.
311 __isl_give isl_val
*PetScan::extract_int(clang::ParenExpr
*expr
)
313 return extract_int(expr
->getSubExpr());
316 /* Extract an integer from "expr".
317 * Return NULL if "expr" does not (obviously) represent an integer.
319 __isl_give isl_val
*PetScan::extract_int(clang::Expr
*expr
)
321 if (expr
->getStmtClass() == Stmt::IntegerLiteralClass
)
322 return extract_int(ctx
, cast
<IntegerLiteral
>(expr
));
323 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
324 return extract_int(cast
<ParenExpr
>(expr
));
330 /* Extract an affine expression from the IntegerLiteral "expr".
332 __isl_give isl_pw_aff
*PetScan::extract_affine(IntegerLiteral
*expr
)
334 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
335 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
336 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
337 isl_set
*dom
= isl_set_universe(dim
);
340 v
= extract_int(expr
);
341 aff
= isl_aff_add_constant_val(aff
, v
);
343 return isl_pw_aff_alloc(dom
, aff
);
346 /* Extract an affine expression from the APInt "val".
348 __isl_give isl_pw_aff
*PetScan::extract_affine(const llvm::APInt
&val
)
350 isl_space
*dim
= isl_space_params_alloc(ctx
, 0);
351 isl_local_space
*ls
= isl_local_space_from_space(isl_space_copy(dim
));
352 isl_aff
*aff
= isl_aff_zero_on_domain(ls
);
353 isl_set
*dom
= isl_set_universe(dim
);
356 v
= isl_val_int_from_ui(ctx
, val
.getZExtValue());
357 aff
= isl_aff_add_constant_val(aff
, v
);
359 return isl_pw_aff_alloc(dom
, aff
);
362 __isl_give isl_pw_aff
*PetScan::extract_affine(ImplicitCastExpr
*expr
)
364 return extract_affine(expr
->getSubExpr());
367 static unsigned get_type_size(ValueDecl
*decl
)
369 return decl
->getASTContext().getIntWidth(decl
->getType());
372 /* Bound parameter "pos" of "set" to the possible values of "decl".
374 static __isl_give isl_set
*set_parameter_bounds(__isl_take isl_set
*set
,
375 unsigned pos
, ValueDecl
*decl
)
381 ctx
= isl_set_get_ctx(set
);
382 width
= get_type_size(decl
);
383 if (decl
->getType()->isUnsignedIntegerType()) {
384 set
= isl_set_lower_bound_si(set
, isl_dim_param
, pos
, 0);
385 bound
= isl_val_int_from_ui(ctx
, width
);
386 bound
= isl_val_2exp(bound
);
387 bound
= isl_val_sub_ui(bound
, 1);
388 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
, bound
);
390 bound
= isl_val_int_from_ui(ctx
, width
- 1);
391 bound
= isl_val_2exp(bound
);
392 bound
= isl_val_sub_ui(bound
, 1);
393 set
= isl_set_upper_bound_val(set
, isl_dim_param
, pos
,
394 isl_val_copy(bound
));
395 bound
= isl_val_neg(bound
);
396 bound
= isl_val_sub_ui(bound
, 1);
397 set
= isl_set_lower_bound_val(set
, isl_dim_param
, pos
, bound
);
403 /* Extract an affine expression from the DeclRefExpr "expr".
405 * If the variable has been assigned a value, then we check whether
406 * we know what (affine) value was assigned.
407 * If so, we return this value. Otherwise we convert "expr"
408 * to an extra parameter (provided nesting_enabled is set).
410 * Otherwise, we simply return an expression that is equal
411 * to a parameter corresponding to the referenced variable.
413 __isl_give isl_pw_aff
*PetScan::extract_affine(DeclRefExpr
*expr
)
415 ValueDecl
*decl
= expr
->getDecl();
416 const Type
*type
= decl
->getType().getTypePtr();
422 if (!type
->isIntegerType()) {
427 if (assigned_value
.find(decl
) != assigned_value
.end()) {
428 if (assigned_value
[decl
])
429 return isl_pw_aff_copy(assigned_value
[decl
]);
431 return nested_access(expr
);
434 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
435 dim
= isl_space_params_alloc(ctx
, 1);
437 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
439 dom
= isl_set_universe(isl_space_copy(dim
));
440 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
441 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
443 return isl_pw_aff_alloc(dom
, aff
);
446 /* Extract an affine expression from an integer division operation.
447 * In particular, if "expr" is lhs/rhs, then return
449 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
451 * The second argument (rhs) is required to be a (positive) integer constant.
453 __isl_give isl_pw_aff
*PetScan::extract_affine_div(BinaryOperator
*expr
)
456 isl_pw_aff
*rhs
, *lhs
;
458 rhs
= extract_affine(expr
->getRHS());
459 is_cst
= isl_pw_aff_is_cst(rhs
);
460 if (is_cst
< 0 || !is_cst
) {
461 isl_pw_aff_free(rhs
);
467 lhs
= extract_affine(expr
->getLHS());
469 return isl_pw_aff_tdiv_q(lhs
, rhs
);
472 /* Extract an affine expression from a modulo operation.
473 * In particular, if "expr" is lhs/rhs, then return
475 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
477 * The second argument (rhs) is required to be a (positive) integer constant.
479 __isl_give isl_pw_aff
*PetScan::extract_affine_mod(BinaryOperator
*expr
)
482 isl_pw_aff
*rhs
, *lhs
;
484 rhs
= extract_affine(expr
->getRHS());
485 is_cst
= isl_pw_aff_is_cst(rhs
);
486 if (is_cst
< 0 || !is_cst
) {
487 isl_pw_aff_free(rhs
);
493 lhs
= extract_affine(expr
->getLHS());
495 return isl_pw_aff_tdiv_r(lhs
, rhs
);
498 /* Extract an affine expression from a multiplication operation.
499 * This is only allowed if at least one of the two arguments
500 * is a (piecewise) constant.
502 __isl_give isl_pw_aff
*PetScan::extract_affine_mul(BinaryOperator
*expr
)
507 lhs
= extract_affine(expr
->getLHS());
508 rhs
= extract_affine(expr
->getRHS());
510 if (!isl_pw_aff_is_cst(lhs
) && !isl_pw_aff_is_cst(rhs
)) {
511 isl_pw_aff_free(lhs
);
512 isl_pw_aff_free(rhs
);
517 return isl_pw_aff_mul(lhs
, rhs
);
520 /* Extract an affine expression from an addition or subtraction operation.
522 __isl_give isl_pw_aff
*PetScan::extract_affine_add(BinaryOperator
*expr
)
527 lhs
= extract_affine(expr
->getLHS());
528 rhs
= extract_affine(expr
->getRHS());
530 switch (expr
->getOpcode()) {
532 return isl_pw_aff_add(lhs
, rhs
);
534 return isl_pw_aff_sub(lhs
, rhs
);
536 isl_pw_aff_free(lhs
);
537 isl_pw_aff_free(rhs
);
547 static __isl_give isl_pw_aff
*wrap(__isl_take isl_pw_aff
*pwaff
,
553 ctx
= isl_pw_aff_get_ctx(pwaff
);
554 mod
= isl_val_int_from_ui(ctx
, width
);
555 mod
= isl_val_2exp(mod
);
557 pwaff
= isl_pw_aff_mod_val(pwaff
, mod
);
562 /* Limit the domain of "pwaff" to those elements where the function
565 * 2^{width-1} <= pwaff < 2^{width-1}
567 static __isl_give isl_pw_aff
*avoid_overflow(__isl_take isl_pw_aff
*pwaff
,
572 isl_space
*space
= isl_pw_aff_get_domain_space(pwaff
);
573 isl_local_space
*ls
= isl_local_space_from_space(space
);
578 ctx
= isl_pw_aff_get_ctx(pwaff
);
579 v
= isl_val_int_from_ui(ctx
, width
- 1);
582 bound
= isl_aff_zero_on_domain(ls
);
583 bound
= isl_aff_add_constant_val(bound
, v
);
584 b
= isl_pw_aff_from_aff(bound
);
586 dom
= isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff
), isl_pw_aff_copy(b
));
587 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
589 b
= isl_pw_aff_neg(b
);
590 dom
= isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff
), b
);
591 pwaff
= isl_pw_aff_intersect_domain(pwaff
, dom
);
596 /* Handle potential overflows on signed computations.
598 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
599 * the we adjust the domain of "pa" to avoid overflows.
601 __isl_give isl_pw_aff
*PetScan::signed_overflow(__isl_take isl_pw_aff
*pa
,
604 if (options
->signed_overflow
== PET_OVERFLOW_AVOID
)
605 pa
= avoid_overflow(pa
, width
);
610 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
612 static __isl_give isl_pw_aff
*indicator_function(__isl_take isl_set
*set
,
613 __isl_take isl_set
*dom
)
616 pa
= isl_set_indicator_function(set
);
617 pa
= isl_pw_aff_intersect_domain(pa
, dom
);
621 /* Extract an affine expression from some binary operations.
622 * If the result of the expression is unsigned, then we wrap it
623 * based on the size of the type. Otherwise, we ensure that
624 * no overflow occurs.
626 __isl_give isl_pw_aff
*PetScan::extract_affine(BinaryOperator
*expr
)
631 switch (expr
->getOpcode()) {
634 res
= extract_affine_add(expr
);
637 res
= extract_affine_div(expr
);
640 res
= extract_affine_mod(expr
);
643 res
= extract_affine_mul(expr
);
653 return extract_condition(expr
);
659 width
= ast_context
.getIntWidth(expr
->getType());
660 if (expr
->getType()->isUnsignedIntegerType())
661 res
= wrap(res
, width
);
663 res
= signed_overflow(res
, width
);
668 /* Extract an affine expression from a negation operation.
670 __isl_give isl_pw_aff
*PetScan::extract_affine(UnaryOperator
*expr
)
672 if (expr
->getOpcode() == UO_Minus
)
673 return isl_pw_aff_neg(extract_affine(expr
->getSubExpr()));
674 if (expr
->getOpcode() == UO_LNot
)
675 return extract_condition(expr
);
681 __isl_give isl_pw_aff
*PetScan::extract_affine(ParenExpr
*expr
)
683 return extract_affine(expr
->getSubExpr());
686 /* Extract an affine expression from some special function calls.
687 * In particular, we handle "min", "max", "ceild" and "floord".
688 * In case of the latter two, the second argument needs to be
689 * a (positive) integer constant.
691 __isl_give isl_pw_aff
*PetScan::extract_affine(CallExpr
*expr
)
695 isl_pw_aff
*aff1
, *aff2
;
697 fd
= expr
->getDirectCallee();
703 name
= fd
->getDeclName().getAsString();
704 if (!(expr
->getNumArgs() == 2 && name
== "min") &&
705 !(expr
->getNumArgs() == 2 && name
== "max") &&
706 !(expr
->getNumArgs() == 2 && name
== "floord") &&
707 !(expr
->getNumArgs() == 2 && name
== "ceild")) {
712 if (name
== "min" || name
== "max") {
713 aff1
= extract_affine(expr
->getArg(0));
714 aff2
= extract_affine(expr
->getArg(1));
717 aff1
= isl_pw_aff_min(aff1
, aff2
);
719 aff1
= isl_pw_aff_max(aff1
, aff2
);
720 } else if (name
== "floord" || name
== "ceild") {
722 Expr
*arg2
= expr
->getArg(1);
724 if (arg2
->getStmtClass() != Stmt::IntegerLiteralClass
) {
728 aff1
= extract_affine(expr
->getArg(0));
729 v
= extract_int(cast
<IntegerLiteral
>(arg2
));
730 aff1
= isl_pw_aff_scale_down_val(aff1
, v
);
731 if (name
== "floord")
732 aff1
= isl_pw_aff_floor(aff1
);
734 aff1
= isl_pw_aff_ceil(aff1
);
743 /* This method is called when we come across an access that is
744 * nested in what is supposed to be an affine expression.
745 * If nesting is allowed, we return a new parameter that corresponds
746 * to this nested access. Otherwise, we simply complain.
748 * Note that we currently don't allow nested accesses themselves
749 * to contain any nested accesses, so we check if we can extract
750 * the access without any nesting and complain if we can't.
752 * The new parameter is resolved in resolve_nested.
754 isl_pw_aff
*PetScan::nested_access(Expr
*expr
)
762 if (!nesting_enabled
) {
767 allow_nested
= false;
768 access
= extract_access(expr
);
774 isl_map_free(access
);
776 id
= isl_id_alloc(ctx
, NULL
, expr
);
777 dim
= isl_space_params_alloc(ctx
, 1);
779 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
781 dom
= isl_set_universe(isl_space_copy(dim
));
782 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
783 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
785 return isl_pw_aff_alloc(dom
, aff
);
788 /* Affine expressions are not supposed to contain array accesses,
789 * but if nesting is allowed, we return a parameter corresponding
790 * to the array access.
792 __isl_give isl_pw_aff
*PetScan::extract_affine(ArraySubscriptExpr
*expr
)
794 return nested_access(expr
);
797 /* Extract an affine expression from a conditional operation.
799 __isl_give isl_pw_aff
*PetScan::extract_affine(ConditionalOperator
*expr
)
801 isl_pw_aff
*cond
, *lhs
, *rhs
, *res
;
803 cond
= extract_condition(expr
->getCond());
804 lhs
= extract_affine(expr
->getTrueExpr());
805 rhs
= extract_affine(expr
->getFalseExpr());
807 return isl_pw_aff_cond(cond
, lhs
, rhs
);
810 /* Extract an affine expression, if possible, from "expr".
811 * Otherwise return NULL.
813 __isl_give isl_pw_aff
*PetScan::extract_affine(Expr
*expr
)
815 switch (expr
->getStmtClass()) {
816 case Stmt::ImplicitCastExprClass
:
817 return extract_affine(cast
<ImplicitCastExpr
>(expr
));
818 case Stmt::IntegerLiteralClass
:
819 return extract_affine(cast
<IntegerLiteral
>(expr
));
820 case Stmt::DeclRefExprClass
:
821 return extract_affine(cast
<DeclRefExpr
>(expr
));
822 case Stmt::BinaryOperatorClass
:
823 return extract_affine(cast
<BinaryOperator
>(expr
));
824 case Stmt::UnaryOperatorClass
:
825 return extract_affine(cast
<UnaryOperator
>(expr
));
826 case Stmt::ParenExprClass
:
827 return extract_affine(cast
<ParenExpr
>(expr
));
828 case Stmt::CallExprClass
:
829 return extract_affine(cast
<CallExpr
>(expr
));
830 case Stmt::ArraySubscriptExprClass
:
831 return extract_affine(cast
<ArraySubscriptExpr
>(expr
));
832 case Stmt::ConditionalOperatorClass
:
833 return extract_affine(cast
<ConditionalOperator
>(expr
));
840 __isl_give isl_map
*PetScan::extract_access(ImplicitCastExpr
*expr
)
842 return extract_access(expr
->getSubExpr());
845 /* Return the depth of an array of the given type.
847 static int array_depth(const Type
*type
)
849 if (type
->isPointerType())
850 return 1 + array_depth(type
->getPointeeType().getTypePtr());
851 if (type
->isArrayType()) {
852 const ArrayType
*atype
;
853 type
= type
->getCanonicalTypeInternal().getTypePtr();
854 atype
= cast
<ArrayType
>(type
);
855 return 1 + array_depth(atype
->getElementType().getTypePtr());
860 /* Return the element type of the given array type.
862 static QualType
base_type(QualType qt
)
864 const Type
*type
= qt
.getTypePtr();
866 if (type
->isPointerType())
867 return base_type(type
->getPointeeType());
868 if (type
->isArrayType()) {
869 const ArrayType
*atype
;
870 type
= type
->getCanonicalTypeInternal().getTypePtr();
871 atype
= cast
<ArrayType
>(type
);
872 return base_type(atype
->getElementType());
877 /* Extract an access relation from a reference to a variable.
878 * If the variable has name "A" and its type corresponds to an
879 * array of depth d, then the returned access relation is of the
882 * { [] -> A[i_1,...,i_d] }
884 __isl_give isl_map
*PetScan::extract_access(DeclRefExpr
*expr
)
886 return extract_access(expr
->getDecl());
889 /* Extract an access relation from a variable.
890 * If the variable has name "A" and its type corresponds to an
891 * array of depth d, then the returned access relation is of the
894 * { [] -> A[i_1,...,i_d] }
896 __isl_give isl_map
*PetScan::extract_access(ValueDecl
*decl
)
898 int depth
= array_depth(decl
->getType().getTypePtr());
899 isl_id
*id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
900 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, depth
);
903 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
905 access_rel
= isl_map_universe(dim
);
910 /* Extract an access relation from an integer contant.
911 * If the value of the constant is "v", then the returned access relation
916 __isl_give isl_map
*PetScan::extract_access(IntegerLiteral
*expr
)
918 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr
)));
921 /* Try and extract an access relation from the given Expr.
922 * Return NULL if it doesn't work out.
924 __isl_give isl_map
*PetScan::extract_access(Expr
*expr
)
926 switch (expr
->getStmtClass()) {
927 case Stmt::ImplicitCastExprClass
:
928 return extract_access(cast
<ImplicitCastExpr
>(expr
));
929 case Stmt::DeclRefExprClass
:
930 return extract_access(cast
<DeclRefExpr
>(expr
));
931 case Stmt::ArraySubscriptExprClass
:
932 return extract_access(cast
<ArraySubscriptExpr
>(expr
));
933 case Stmt::IntegerLiteralClass
:
934 return extract_access(cast
<IntegerLiteral
>(expr
));
941 /* Assign the affine expression "index" to the output dimension "pos" of "map",
942 * restrict the domain to those values that result in a non-negative index
943 * and return the result.
945 __isl_give isl_map
*set_index(__isl_take isl_map
*map
, int pos
,
946 __isl_take isl_pw_aff
*index
)
949 int len
= isl_map_dim(map
, isl_dim_out
);
953 domain
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(index
));
954 index
= isl_pw_aff_intersect_domain(index
, domain
);
955 index_map
= isl_map_from_range(isl_set_from_pw_aff(index
));
956 index_map
= isl_map_insert_dims(index_map
, isl_dim_out
, 0, pos
);
957 index_map
= isl_map_add_dims(index_map
, isl_dim_out
, len
- pos
- 1);
958 id
= isl_map_get_tuple_id(map
, isl_dim_out
);
959 index_map
= isl_map_set_tuple_id(index_map
, isl_dim_out
, id
);
961 map
= isl_map_intersect(map
, index_map
);
966 /* Extract an access relation from the given array subscript expression.
967 * If nesting is allowed in general, then we turn it on while
968 * examining the index expression.
970 * We first extract an access relation from the base.
971 * This will result in an access relation with a range that corresponds
972 * to the array being accessed and with earlier indices filled in already.
973 * We then extract the current index and fill that in as well.
974 * The position of the current index is based on the type of base.
975 * If base is the actual array variable, then the depth of this type
976 * will be the same as the depth of the array and we will fill in
977 * the first array index.
978 * Otherwise, the depth of the base type will be smaller and we will fill
981 __isl_give isl_map
*PetScan::extract_access(ArraySubscriptExpr
*expr
)
983 Expr
*base
= expr
->getBase();
984 Expr
*idx
= expr
->getIdx();
986 isl_map
*base_access
;
988 int depth
= array_depth(base
->getType().getTypePtr());
990 bool save_nesting
= nesting_enabled
;
992 nesting_enabled
= allow_nested
;
994 base_access
= extract_access(base
);
995 index
= extract_affine(idx
);
997 nesting_enabled
= save_nesting
;
999 pos
= isl_map_dim(base_access
, isl_dim_out
) - depth
;
1000 access
= set_index(base_access
, pos
, index
);
1005 /* Check if "expr" calls function "minmax" with two arguments and if so
1006 * make lhs and rhs refer to these two arguments.
1008 static bool is_minmax(Expr
*expr
, const char *minmax
, Expr
*&lhs
, Expr
*&rhs
)
1014 if (expr
->getStmtClass() != Stmt::CallExprClass
)
1017 call
= cast
<CallExpr
>(expr
);
1018 fd
= call
->getDirectCallee();
1022 if (call
->getNumArgs() != 2)
1025 name
= fd
->getDeclName().getAsString();
1029 lhs
= call
->getArg(0);
1030 rhs
= call
->getArg(1);
1035 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1036 * lhs and rhs refer to the two arguments.
1038 static bool is_min(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1040 return is_minmax(expr
, "min", lhs
, rhs
);
1043 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1044 * lhs and rhs refer to the two arguments.
1046 static bool is_max(Expr
*expr
, Expr
*&lhs
, Expr
*&rhs
)
1048 return is_minmax(expr
, "max", lhs
, rhs
);
1051 /* Return "lhs && rhs", defined on the shared definition domain.
1053 static __isl_give isl_pw_aff
*pw_aff_and(__isl_take isl_pw_aff
*lhs
,
1054 __isl_take isl_pw_aff
*rhs
)
1059 dom
= isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs
)),
1060 isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1061 cond
= isl_set_intersect(isl_pw_aff_non_zero_set(lhs
),
1062 isl_pw_aff_non_zero_set(rhs
));
1063 return indicator_function(cond
, dom
);
1066 /* Return "lhs && rhs", with shortcut semantics.
1067 * That is, if lhs is false, then the result is defined even if rhs is not.
1068 * In practice, we compute lhs ? rhs : lhs.
1070 static __isl_give isl_pw_aff
*pw_aff_and_then(__isl_take isl_pw_aff
*lhs
,
1071 __isl_take isl_pw_aff
*rhs
)
1073 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), rhs
, lhs
);
1076 /* Return "lhs || rhs", with shortcut semantics.
1077 * That is, if lhs is true, then the result is defined even if rhs is not.
1078 * In practice, we compute lhs ? lhs : rhs.
1080 static __isl_give isl_pw_aff
*pw_aff_or_else(__isl_take isl_pw_aff
*lhs
,
1081 __isl_take isl_pw_aff
*rhs
)
1083 return isl_pw_aff_cond(isl_pw_aff_copy(lhs
), lhs
, rhs
);
1086 /* Extract an affine expressions representing the comparison "LHS op RHS"
1087 * "comp" is the original statement that "LHS op RHS" is derived from
1088 * and is used for diagnostics.
1090 * If the comparison is of the form
1094 * then the expression is constructed as the conjunction of
1099 * A similar optimization is performed for max(a,b) <= c.
1100 * We do this because that will lead to simpler representations
1101 * of the expression.
1102 * If isl is ever enhanced to explicitly deal with min and max expressions,
1103 * this optimization can be removed.
1105 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperatorKind op
,
1106 Expr
*LHS
, Expr
*RHS
, Stmt
*comp
)
1115 return extract_comparison(BO_LT
, RHS
, LHS
, comp
);
1117 return extract_comparison(BO_LE
, RHS
, LHS
, comp
);
1119 if (op
== BO_LT
|| op
== BO_LE
) {
1120 Expr
*expr1
, *expr2
;
1121 if (is_min(RHS
, expr1
, expr2
)) {
1122 lhs
= extract_comparison(op
, LHS
, expr1
, comp
);
1123 rhs
= extract_comparison(op
, LHS
, expr2
, comp
);
1124 return pw_aff_and(lhs
, rhs
);
1126 if (is_max(LHS
, expr1
, expr2
)) {
1127 lhs
= extract_comparison(op
, expr1
, RHS
, comp
);
1128 rhs
= extract_comparison(op
, expr2
, RHS
, comp
);
1129 return pw_aff_and(lhs
, rhs
);
1133 lhs
= extract_affine(LHS
);
1134 rhs
= extract_affine(RHS
);
1136 dom
= isl_pw_aff_domain(isl_pw_aff_copy(lhs
));
1137 dom
= isl_set_intersect(dom
, isl_pw_aff_domain(isl_pw_aff_copy(rhs
)));
1141 cond
= isl_pw_aff_lt_set(lhs
, rhs
);
1144 cond
= isl_pw_aff_le_set(lhs
, rhs
);
1147 cond
= isl_pw_aff_eq_set(lhs
, rhs
);
1150 cond
= isl_pw_aff_ne_set(lhs
, rhs
);
1153 isl_pw_aff_free(lhs
);
1154 isl_pw_aff_free(rhs
);
1160 cond
= isl_set_coalesce(cond
);
1161 res
= indicator_function(cond
, dom
);
1166 __isl_give isl_pw_aff
*PetScan::extract_comparison(BinaryOperator
*comp
)
1168 return extract_comparison(comp
->getOpcode(), comp
->getLHS(),
1169 comp
->getRHS(), comp
);
1172 /* Extract an affine expression representing the negation (logical not)
1173 * of a subexpression.
1175 __isl_give isl_pw_aff
*PetScan::extract_boolean(UnaryOperator
*op
)
1177 isl_set
*set_cond
, *dom
;
1178 isl_pw_aff
*cond
, *res
;
1180 cond
= extract_condition(op
->getSubExpr());
1182 dom
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
1184 set_cond
= isl_pw_aff_zero_set(cond
);
1186 res
= indicator_function(set_cond
, dom
);
1191 /* Extract an affine expression representing the disjunction (logical or)
1192 * or conjunction (logical and) of two subexpressions.
1194 __isl_give isl_pw_aff
*PetScan::extract_boolean(BinaryOperator
*comp
)
1196 isl_pw_aff
*lhs
, *rhs
;
1198 lhs
= extract_condition(comp
->getLHS());
1199 rhs
= extract_condition(comp
->getRHS());
1201 switch (comp
->getOpcode()) {
1203 return pw_aff_and_then(lhs
, rhs
);
1205 return pw_aff_or_else(lhs
, rhs
);
1207 isl_pw_aff_free(lhs
);
1208 isl_pw_aff_free(rhs
);
1215 __isl_give isl_pw_aff
*PetScan::extract_condition(UnaryOperator
*expr
)
1217 switch (expr
->getOpcode()) {
1219 return extract_boolean(expr
);
1226 /* Extract the affine expression "expr != 0 ? 1 : 0".
1228 __isl_give isl_pw_aff
*PetScan::extract_implicit_condition(Expr
*expr
)
1233 res
= extract_affine(expr
);
1235 dom
= isl_pw_aff_domain(isl_pw_aff_copy(res
));
1236 set
= isl_pw_aff_non_zero_set(res
);
1238 res
= indicator_function(set
, dom
);
1243 /* Extract an affine expression from a boolean expression.
1244 * In particular, return the expression "expr ? 1 : 0".
1246 * If the expression doesn't look like a condition, we assume it
1247 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1249 __isl_give isl_pw_aff
*PetScan::extract_condition(Expr
*expr
)
1251 BinaryOperator
*comp
;
1254 isl_set
*u
= isl_set_universe(isl_space_params_alloc(ctx
, 0));
1255 return indicator_function(u
, isl_set_copy(u
));
1258 if (expr
->getStmtClass() == Stmt::ParenExprClass
)
1259 return extract_condition(cast
<ParenExpr
>(expr
)->getSubExpr());
1261 if (expr
->getStmtClass() == Stmt::UnaryOperatorClass
)
1262 return extract_condition(cast
<UnaryOperator
>(expr
));
1264 if (expr
->getStmtClass() != Stmt::BinaryOperatorClass
)
1265 return extract_implicit_condition(expr
);
1267 comp
= cast
<BinaryOperator
>(expr
);
1268 switch (comp
->getOpcode()) {
1275 return extract_comparison(comp
);
1278 return extract_boolean(comp
);
1280 return extract_implicit_condition(expr
);
1284 static enum pet_op_type
UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind
)
1288 return pet_op_minus
;
1290 return pet_op_post_inc
;
1292 return pet_op_post_dec
;
1294 return pet_op_pre_inc
;
1296 return pet_op_pre_dec
;
1302 static enum pet_op_type
BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind
)
1306 return pet_op_add_assign
;
1308 return pet_op_sub_assign
;
1310 return pet_op_mul_assign
;
1312 return pet_op_div_assign
;
1314 return pet_op_assign
;
1338 /* Construct a pet_expr representing a unary operator expression.
1340 struct pet_expr
*PetScan::extract_expr(UnaryOperator
*expr
)
1342 struct pet_expr
*arg
;
1343 enum pet_op_type op
;
1345 op
= UnaryOperatorKind2pet_op_type(expr
->getOpcode());
1346 if (op
== pet_op_last
) {
1351 arg
= extract_expr(expr
->getSubExpr());
1353 if (expr
->isIncrementDecrementOp() &&
1354 arg
&& arg
->type
== pet_expr_access
) {
1359 return pet_expr_new_unary(ctx
, op
, arg
);
1362 /* Mark the given access pet_expr as a write.
1363 * If a scalar is being accessed, then mark its value
1364 * as unknown in assigned_value.
1366 void PetScan::mark_write(struct pet_expr
*access
)
1374 access
->acc
.write
= 1;
1375 access
->acc
.read
= 0;
1377 if (isl_map_dim(access
->acc
.access
, isl_dim_out
) != 0)
1380 id
= isl_map_get_tuple_id(access
->acc
.access
, isl_dim_out
);
1381 decl
= (ValueDecl
*) isl_id_get_user(id
);
1382 clear_assignment(assigned_value
, decl
);
1386 /* Assign "rhs" to "lhs".
1388 * In particular, if "lhs" is a scalar variable, then mark
1389 * the variable as having been assigned. If, furthermore, "rhs"
1390 * is an affine expression, then keep track of this value in assigned_value
1391 * so that we can plug it in when we later come across the same variable.
1393 void PetScan::assign(struct pet_expr
*lhs
, Expr
*rhs
)
1401 if (lhs
->type
!= pet_expr_access
)
1403 if (isl_map_dim(lhs
->acc
.access
, isl_dim_out
) != 0)
1406 id
= isl_map_get_tuple_id(lhs
->acc
.access
, isl_dim_out
);
1407 decl
= (ValueDecl
*) isl_id_get_user(id
);
1410 pa
= try_extract_affine(rhs
);
1411 clear_assignment(assigned_value
, decl
);
1414 assigned_value
[decl
] = pa
;
1415 insert_expression(pa
);
1418 /* Construct a pet_expr representing a binary operator expression.
1420 * If the top level operator is an assignment and the LHS is an access,
1421 * then we mark that access as a write. If the operator is a compound
1422 * assignment, the access is marked as both a read and a write.
1424 * If "expr" assigns something to a scalar variable, then we mark
1425 * the variable as having been assigned. If, furthermore, the expression
1426 * is affine, then keep track of this value in assigned_value
1427 * so that we can plug it in when we later come across the same variable.
1429 struct pet_expr
*PetScan::extract_expr(BinaryOperator
*expr
)
1431 struct pet_expr
*lhs
, *rhs
;
1432 enum pet_op_type op
;
1434 op
= BinaryOperatorKind2pet_op_type(expr
->getOpcode());
1435 if (op
== pet_op_last
) {
1440 lhs
= extract_expr(expr
->getLHS());
1441 rhs
= extract_expr(expr
->getRHS());
1443 if (expr
->isAssignmentOp() && lhs
&& lhs
->type
== pet_expr_access
) {
1445 if (expr
->isCompoundAssignmentOp())
1449 if (expr
->getOpcode() == BO_Assign
)
1450 assign(lhs
, expr
->getRHS());
1452 return pet_expr_new_binary(ctx
, op
, lhs
, rhs
);
1455 /* Construct a pet_scop with a single statement killing the entire
1458 struct pet_scop
*PetScan::kill(Stmt
*stmt
, struct pet_array
*array
)
1461 struct pet_expr
*expr
;
1465 access
= isl_map_from_range(isl_set_copy(array
->extent
));
1466 expr
= pet_expr_kill_from_access(access
);
1467 return extract(stmt
, expr
);
1470 /* Construct a pet_scop for a (single) variable declaration.
1472 * The scop contains the variable being declared (as an array)
1473 * and a statement killing the array.
1475 * If the variable is initialized in the AST, then the scop
1476 * also contains an assignment to the variable.
1478 struct pet_scop
*PetScan::extract(DeclStmt
*stmt
)
1482 struct pet_expr
*lhs
, *rhs
, *pe
;
1483 struct pet_scop
*scop_decl
, *scop
;
1484 struct pet_array
*array
;
1486 if (!stmt
->isSingleDecl()) {
1491 decl
= stmt
->getSingleDecl();
1492 vd
= cast
<VarDecl
>(decl
);
1494 array
= extract_array(ctx
, vd
);
1496 array
->declared
= 1;
1497 scop_decl
= kill(stmt
, array
);
1498 scop_decl
= pet_scop_add_array(scop_decl
, array
);
1503 lhs
= pet_expr_from_access(extract_access(vd
));
1504 rhs
= extract_expr(vd
->getInit());
1507 assign(lhs
, vd
->getInit());
1509 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, lhs
, rhs
);
1510 scop
= extract(stmt
, pe
);
1512 scop_decl
= pet_scop_prefix(scop_decl
, 0);
1513 scop
= pet_scop_prefix(scop
, 1);
1515 scop
= pet_scop_add_seq(ctx
, scop_decl
, scop
);
1520 /* Construct a pet_expr representing a conditional operation.
1522 * We first try to extract the condition as an affine expression.
1523 * If that fails, we construct a pet_expr tree representing the condition.
1525 struct pet_expr
*PetScan::extract_expr(ConditionalOperator
*expr
)
1527 struct pet_expr
*cond
, *lhs
, *rhs
;
1530 pa
= try_extract_affine(expr
->getCond());
1532 isl_set
*test
= isl_set_from_pw_aff(pa
);
1533 cond
= pet_expr_from_access(isl_map_from_range(test
));
1535 cond
= extract_expr(expr
->getCond());
1536 lhs
= extract_expr(expr
->getTrueExpr());
1537 rhs
= extract_expr(expr
->getFalseExpr());
1539 return pet_expr_new_ternary(ctx
, cond
, lhs
, rhs
);
1542 struct pet_expr
*PetScan::extract_expr(ImplicitCastExpr
*expr
)
1544 return extract_expr(expr
->getSubExpr());
1547 /* Construct a pet_expr representing a floating point value.
1549 * If the floating point literal does not appear in a macro,
1550 * then we use the original representation in the source code
1551 * as the string representation. Otherwise, we use the pretty
1552 * printer to produce a string representation.
1554 struct pet_expr
*PetScan::extract_expr(FloatingLiteral
*expr
)
1558 const LangOptions
&LO
= PP
.getLangOpts();
1559 SourceLocation loc
= expr
->getLocation();
1561 if (!loc
.isMacroID()) {
1562 SourceManager
&SM
= PP
.getSourceManager();
1563 unsigned len
= Lexer::MeasureTokenLength(loc
, SM
, LO
);
1564 s
= string(SM
.getCharacterData(loc
), len
);
1566 llvm::raw_string_ostream
S(s
);
1567 expr
->printPretty(S
, 0, PrintingPolicy(LO
));
1570 d
= expr
->getValueAsApproximateDouble();
1571 return pet_expr_new_double(ctx
, d
, s
.c_str());
1574 /* Extract an access relation from "expr" and then convert it into
1577 struct pet_expr
*PetScan::extract_access_expr(Expr
*expr
)
1580 struct pet_expr
*pe
;
1582 access
= extract_access(expr
);
1584 pe
= pet_expr_from_access(access
);
1589 struct pet_expr
*PetScan::extract_expr(ParenExpr
*expr
)
1591 return extract_expr(expr
->getSubExpr());
1594 /* Construct a pet_expr representing a function call.
1596 * If we are passing along a pointer to an array element
1597 * or an entire row or even higher dimensional slice of an array,
1598 * then the function being called may write into the array.
1600 * We assume here that if the function is declared to take a pointer
1601 * to a const type, then the function will perform a read
1602 * and that otherwise, it will perform a write.
1604 struct pet_expr
*PetScan::extract_expr(CallExpr
*expr
)
1606 struct pet_expr
*res
= NULL
;
1610 fd
= expr
->getDirectCallee();
1616 name
= fd
->getDeclName().getAsString();
1617 res
= pet_expr_new_call(ctx
, name
.c_str(), expr
->getNumArgs());
1621 for (int i
= 0; i
< expr
->getNumArgs(); ++i
) {
1622 Expr
*arg
= expr
->getArg(i
);
1626 if (arg
->getStmtClass() == Stmt::ImplicitCastExprClass
) {
1627 ImplicitCastExpr
*ice
= cast
<ImplicitCastExpr
>(arg
);
1628 arg
= ice
->getSubExpr();
1630 if (arg
->getStmtClass() == Stmt::UnaryOperatorClass
) {
1631 UnaryOperator
*op
= cast
<UnaryOperator
>(arg
);
1632 if (op
->getOpcode() == UO_AddrOf
) {
1634 arg
= op
->getSubExpr();
1637 res
->args
[i
] = PetScan::extract_expr(arg
);
1638 main_arg
= res
->args
[i
];
1640 res
->args
[i
] = pet_expr_new_unary(ctx
,
1641 pet_op_address_of
, res
->args
[i
]);
1644 if (arg
->getStmtClass() == Stmt::ArraySubscriptExprClass
&&
1645 array_depth(arg
->getType().getTypePtr()) > 0)
1647 if (is_addr
&& main_arg
->type
== pet_expr_access
) {
1649 if (!fd
->hasPrototype()) {
1650 unsupported(expr
, "prototype required");
1653 parm
= fd
->getParamDecl(i
);
1654 if (!const_base(parm
->getType()))
1655 mark_write(main_arg
);
1665 /* Construct a pet_expr representing a (C style) cast.
1667 struct pet_expr
*PetScan::extract_expr(CStyleCastExpr
*expr
)
1669 struct pet_expr
*arg
;
1672 arg
= extract_expr(expr
->getSubExpr());
1676 type
= expr
->getTypeAsWritten();
1677 return pet_expr_new_cast(ctx
, type
.getAsString().c_str(), arg
);
1680 /* Try and onstruct a pet_expr representing "expr".
1682 struct pet_expr
*PetScan::extract_expr(Expr
*expr
)
1684 switch (expr
->getStmtClass()) {
1685 case Stmt::UnaryOperatorClass
:
1686 return extract_expr(cast
<UnaryOperator
>(expr
));
1687 case Stmt::CompoundAssignOperatorClass
:
1688 case Stmt::BinaryOperatorClass
:
1689 return extract_expr(cast
<BinaryOperator
>(expr
));
1690 case Stmt::ImplicitCastExprClass
:
1691 return extract_expr(cast
<ImplicitCastExpr
>(expr
));
1692 case Stmt::ArraySubscriptExprClass
:
1693 case Stmt::DeclRefExprClass
:
1694 case Stmt::IntegerLiteralClass
:
1695 return extract_access_expr(expr
);
1696 case Stmt::FloatingLiteralClass
:
1697 return extract_expr(cast
<FloatingLiteral
>(expr
));
1698 case Stmt::ParenExprClass
:
1699 return extract_expr(cast
<ParenExpr
>(expr
));
1700 case Stmt::ConditionalOperatorClass
:
1701 return extract_expr(cast
<ConditionalOperator
>(expr
));
1702 case Stmt::CallExprClass
:
1703 return extract_expr(cast
<CallExpr
>(expr
));
1704 case Stmt::CStyleCastExprClass
:
1705 return extract_expr(cast
<CStyleCastExpr
>(expr
));
1712 /* Check if the given initialization statement is an assignment.
1713 * If so, return that assignment. Otherwise return NULL.
1715 BinaryOperator
*PetScan::initialization_assignment(Stmt
*init
)
1717 BinaryOperator
*ass
;
1719 if (init
->getStmtClass() != Stmt::BinaryOperatorClass
)
1722 ass
= cast
<BinaryOperator
>(init
);
1723 if (ass
->getOpcode() != BO_Assign
)
1729 /* Check if the given initialization statement is a declaration
1730 * of a single variable.
1731 * If so, return that declaration. Otherwise return NULL.
1733 Decl
*PetScan::initialization_declaration(Stmt
*init
)
1737 if (init
->getStmtClass() != Stmt::DeclStmtClass
)
1740 decl
= cast
<DeclStmt
>(init
);
1742 if (!decl
->isSingleDecl())
1745 return decl
->getSingleDecl();
1748 /* Given the assignment operator in the initialization of a for loop,
1749 * extract the induction variable, i.e., the (integer)variable being
1752 ValueDecl
*PetScan::extract_induction_variable(BinaryOperator
*init
)
1759 lhs
= init
->getLHS();
1760 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1765 ref
= cast
<DeclRefExpr
>(lhs
);
1766 decl
= ref
->getDecl();
1767 type
= decl
->getType().getTypePtr();
1769 if (!type
->isIntegerType()) {
1777 /* Given the initialization statement of a for loop and the single
1778 * declaration in this initialization statement,
1779 * extract the induction variable, i.e., the (integer) variable being
1782 VarDecl
*PetScan::extract_induction_variable(Stmt
*init
, Decl
*decl
)
1786 vd
= cast
<VarDecl
>(decl
);
1788 const QualType type
= vd
->getType();
1789 if (!type
->isIntegerType()) {
1794 if (!vd
->getInit()) {
1802 /* Check that op is of the form iv++ or iv--.
1803 * Return an affine expression "1" or "-1" accordingly.
1805 __isl_give isl_pw_aff
*PetScan::extract_unary_increment(
1806 clang::UnaryOperator
*op
, clang::ValueDecl
*iv
)
1813 if (!op
->isIncrementDecrementOp()) {
1818 sub
= op
->getSubExpr();
1819 if (sub
->getStmtClass() != Stmt::DeclRefExprClass
) {
1824 ref
= cast
<DeclRefExpr
>(sub
);
1825 if (ref
->getDecl() != iv
) {
1830 space
= isl_space_params_alloc(ctx
, 0);
1831 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
1833 if (op
->isIncrementOp())
1834 aff
= isl_aff_add_constant_si(aff
, 1);
1836 aff
= isl_aff_add_constant_si(aff
, -1);
1838 return isl_pw_aff_from_aff(aff
);
1841 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1842 * has a single constant expression, then put this constant in *user.
1843 * The caller is assumed to have checked that this function will
1844 * be called exactly once.
1846 static int extract_cst(__isl_take isl_set
*set
, __isl_take isl_aff
*aff
,
1849 isl_val
**inc
= (isl_val
**)user
;
1852 if (isl_aff_is_cst(aff
))
1853 *inc
= isl_aff_get_constant_val(aff
);
1863 /* Check if op is of the form
1867 * and return inc as an affine expression.
1869 * We extract an affine expression from the RHS, subtract iv and return
1872 __isl_give isl_pw_aff
*PetScan::extract_binary_increment(BinaryOperator
*op
,
1873 clang::ValueDecl
*iv
)
1882 if (op
->getOpcode() != BO_Assign
) {
1888 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1893 ref
= cast
<DeclRefExpr
>(lhs
);
1894 if (ref
->getDecl() != iv
) {
1899 val
= extract_affine(op
->getRHS());
1901 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
1903 dim
= isl_space_params_alloc(ctx
, 1);
1904 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
1905 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
1906 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
1908 val
= isl_pw_aff_sub(val
, isl_pw_aff_from_aff(aff
));
1913 /* Check that op is of the form iv += cst or iv -= cst
1914 * and return an affine expression corresponding oto cst or -cst accordingly.
1916 __isl_give isl_pw_aff
*PetScan::extract_compound_increment(
1917 CompoundAssignOperator
*op
, clang::ValueDecl
*iv
)
1923 BinaryOperatorKind opcode
;
1925 opcode
= op
->getOpcode();
1926 if (opcode
!= BO_AddAssign
&& opcode
!= BO_SubAssign
) {
1930 if (opcode
== BO_SubAssign
)
1934 if (lhs
->getStmtClass() != Stmt::DeclRefExprClass
) {
1939 ref
= cast
<DeclRefExpr
>(lhs
);
1940 if (ref
->getDecl() != iv
) {
1945 val
= extract_affine(op
->getRHS());
1947 val
= isl_pw_aff_neg(val
);
1952 /* Check that the increment of the given for loop increments
1953 * (or decrements) the induction variable "iv" and return
1954 * the increment as an affine expression if successful.
1956 __isl_give isl_pw_aff
*PetScan::extract_increment(clang::ForStmt
*stmt
,
1959 Stmt
*inc
= stmt
->getInc();
1966 if (inc
->getStmtClass() == Stmt::UnaryOperatorClass
)
1967 return extract_unary_increment(cast
<UnaryOperator
>(inc
), iv
);
1968 if (inc
->getStmtClass() == Stmt::CompoundAssignOperatorClass
)
1969 return extract_compound_increment(
1970 cast
<CompoundAssignOperator
>(inc
), iv
);
1971 if (inc
->getStmtClass() == Stmt::BinaryOperatorClass
)
1972 return extract_binary_increment(cast
<BinaryOperator
>(inc
), iv
);
1978 /* Embed the given iteration domain in an extra outer loop
1979 * with induction variable "var".
1980 * If this variable appeared as a parameter in the constraints,
1981 * it is replaced by the new outermost dimension.
1983 static __isl_give isl_set
*embed(__isl_take isl_set
*set
,
1984 __isl_take isl_id
*var
)
1988 set
= isl_set_insert_dims(set
, isl_dim_set
, 0, 1);
1989 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, var
);
1991 set
= isl_set_equate(set
, isl_dim_param
, pos
, isl_dim_set
, 0);
1992 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
1999 /* Return those elements in the space of "cond" that come after
2000 * (based on "sign") an element in "cond".
2002 static __isl_give isl_set
*after(__isl_take isl_set
*cond
, int sign
)
2004 isl_map
*previous_to_this
;
2007 previous_to_this
= isl_map_lex_lt(isl_set_get_space(cond
));
2009 previous_to_this
= isl_map_lex_gt(isl_set_get_space(cond
));
2011 cond
= isl_set_apply(cond
, previous_to_this
);
2016 /* Create the infinite iteration domain
2018 * { [id] : id >= 0 }
2020 * If "scop" has an affine skip of type pet_skip_later,
2021 * then remove those iterations i that have an earlier iteration
2022 * where the skip condition is satisfied, meaning that iteration i
2024 * Since we are dealing with a loop without loop iterator,
2025 * the skip condition cannot refer to the current loop iterator and
2026 * so effectively, the returned set is of the form
2028 * { [0]; [id] : id >= 1 and not skip }
2030 static __isl_give isl_set
*infinite_domain(__isl_take isl_id
*id
,
2031 struct pet_scop
*scop
)
2033 isl_ctx
*ctx
= isl_id_get_ctx(id
);
2037 domain
= isl_set_nat_universe(isl_space_set_alloc(ctx
, 0, 1));
2038 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, id
);
2040 if (!pet_scop_has_affine_skip(scop
, pet_skip_later
))
2043 skip
= pet_scop_get_skip(scop
, pet_skip_later
);
2044 skip
= isl_set_fix_si(skip
, isl_dim_set
, 0, 1);
2045 skip
= isl_set_params(skip
);
2046 skip
= embed(skip
, isl_id_copy(id
));
2047 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2048 domain
= isl_set_subtract(domain
, after(skip
, 1));
2053 /* Create an identity mapping on the space containing "domain".
2055 static __isl_give isl_map
*identity_map(__isl_keep isl_set
*domain
)
2060 space
= isl_space_map_from_set(isl_set_get_space(domain
));
2061 id
= isl_map_identity(space
);
2066 /* Add a filter to "scop" that imposes that it is only executed
2067 * when "break_access" has a zero value for all previous iterations
2070 * The input "break_access" has a zero-dimensional domain and range.
2072 static struct pet_scop
*scop_add_break(struct pet_scop
*scop
,
2073 __isl_take isl_map
*break_access
, __isl_take isl_set
*domain
, int sign
)
2075 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
2079 id_test
= isl_map_get_tuple_id(break_access
, isl_dim_out
);
2080 break_access
= isl_map_add_dims(break_access
, isl_dim_in
, 1);
2081 break_access
= isl_map_add_dims(break_access
, isl_dim_out
, 1);
2082 break_access
= isl_map_intersect_range(break_access
, domain
);
2083 break_access
= isl_map_set_tuple_id(break_access
, isl_dim_out
, id_test
);
2085 prev
= isl_map_lex_gt_first(isl_map_get_space(break_access
), 1);
2087 prev
= isl_map_lex_lt_first(isl_map_get_space(break_access
), 1);
2088 break_access
= isl_map_intersect(break_access
, prev
);
2089 scop
= pet_scop_filter(scop
, break_access
, 0);
2090 scop
= pet_scop_merge_filters(scop
);
2095 /* Construct a pet_scop for an infinite loop around the given body.
2097 * We extract a pet_scop for the body and then embed it in a loop with
2106 * If the body contains any break, then it is taken into
2107 * account in infinite_domain (if the skip condition is affine)
2108 * or in scop_add_break (if the skip condition is not affine).
2110 struct pet_scop
*PetScan::extract_infinite_loop(Stmt
*body
)
2116 struct pet_scop
*scop
;
2119 scop
= extract(body
);
2123 id
= isl_id_alloc(ctx
, "t", NULL
);
2124 domain
= infinite_domain(isl_id_copy(id
), scop
);
2125 ident
= identity_map(domain
);
2127 has_var_break
= pet_scop_has_var_skip(scop
, pet_skip_later
);
2129 access
= pet_scop_get_skip_map(scop
, pet_skip_later
);
2131 scop
= pet_scop_embed(scop
, isl_set_copy(domain
),
2132 isl_map_copy(ident
), ident
, id
);
2134 scop
= scop_add_break(scop
, access
, domain
, 1);
2136 isl_set_free(domain
);
2141 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2147 struct pet_scop
*PetScan::extract_infinite_for(ForStmt
*stmt
)
2149 return extract_infinite_loop(stmt
->getBody());
2152 /* Create an access to a virtual array representing the result
2154 * Unlike other accessed data, the id of the array is NULL as
2155 * there is no ValueDecl in the program corresponding to the virtual
2157 * The array starts out as a scalar, but grows along with the
2158 * statement writing to the array in pet_scop_embed.
2160 static __isl_give isl_map
*create_test_access(isl_ctx
*ctx
, int test_nr
)
2162 isl_space
*dim
= isl_space_alloc(ctx
, 0, 0, 0);
2166 snprintf(name
, sizeof(name
), "__pet_test_%d", test_nr
);
2167 id
= isl_id_alloc(ctx
, name
, NULL
);
2168 dim
= isl_space_set_tuple_id(dim
, isl_dim_out
, id
);
2169 return isl_map_universe(dim
);
2172 /* Add an array with the given extent ("access") to the list
2173 * of arrays in "scop" and return the extended pet_scop.
2174 * The array is marked as attaining values 0 and 1 only and
2175 * as each element being assigned at most once.
2177 static struct pet_scop
*scop_add_array(struct pet_scop
*scop
,
2178 __isl_keep isl_map
*access
, clang::ASTContext
&ast_ctx
)
2180 isl_ctx
*ctx
= isl_map_get_ctx(access
);
2182 struct pet_array
*array
;
2189 array
= isl_calloc_type(ctx
, struct pet_array
);
2193 array
->extent
= isl_map_range(isl_map_copy(access
));
2194 dim
= isl_space_params_alloc(ctx
, 0);
2195 array
->context
= isl_set_universe(dim
);
2196 dim
= isl_space_set_alloc(ctx
, 0, 1);
2197 array
->value_bounds
= isl_set_universe(dim
);
2198 array
->value_bounds
= isl_set_lower_bound_si(array
->value_bounds
,
2200 array
->value_bounds
= isl_set_upper_bound_si(array
->value_bounds
,
2202 array
->element_type
= strdup("int");
2203 array
->element_size
= ast_ctx
.getTypeInfo(ast_ctx
.IntTy
).first
/ 8;
2204 array
->uniquely_defined
= 1;
2206 if (!array
->extent
|| !array
->context
)
2207 array
= pet_array_free(array
);
2209 scop
= pet_scop_add_array(scop
, array
);
2213 pet_scop_free(scop
);
2217 /* Construct a pet_scop for a while loop of the form
2222 * In particular, construct a scop for an infinite loop around body and
2223 * intersect the domain with the affine expression.
2224 * Note that this intersection may result in an empty loop.
2226 struct pet_scop
*PetScan::extract_affine_while(__isl_take isl_pw_aff
*pa
,
2229 struct pet_scop
*scop
;
2233 valid
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2234 dom
= isl_pw_aff_non_zero_set(pa
);
2235 scop
= extract_infinite_loop(body
);
2236 scop
= pet_scop_restrict(scop
, dom
);
2237 scop
= pet_scop_restrict_context(scop
, valid
);
2242 /* Construct a scop for a while, given the scops for the condition
2243 * and the body, the filter access and the iteration domain of
2246 * In particular, the scop for the condition is filtered to depend
2247 * on "test_access" evaluating to true for all previous iterations
2248 * of the loop, while the scop for the body is filtered to depend
2249 * on "test_access" evaluating to true for all iterations up to the
2250 * current iteration.
2252 * These filtered scops are then combined into a single scop.
2254 * "sign" is positive if the iterator increases and negative
2257 static struct pet_scop
*scop_add_while(struct pet_scop
*scop_cond
,
2258 struct pet_scop
*scop_body
, __isl_take isl_map
*test_access
,
2259 __isl_take isl_set
*domain
, int sign
)
2261 isl_ctx
*ctx
= isl_set_get_ctx(domain
);
2265 id_test
= isl_map_get_tuple_id(test_access
, isl_dim_out
);
2266 test_access
= isl_map_add_dims(test_access
, isl_dim_in
, 1);
2267 test_access
= isl_map_add_dims(test_access
, isl_dim_out
, 1);
2268 test_access
= isl_map_intersect_range(test_access
, domain
);
2269 test_access
= isl_map_set_tuple_id(test_access
, isl_dim_out
, id_test
);
2271 prev
= isl_map_lex_ge_first(isl_map_get_space(test_access
), 1);
2273 prev
= isl_map_lex_le_first(isl_map_get_space(test_access
), 1);
2274 test_access
= isl_map_intersect(test_access
, prev
);
2275 scop_body
= pet_scop_filter(scop_body
, isl_map_copy(test_access
), 1);
2277 prev
= isl_map_lex_gt_first(isl_map_get_space(test_access
), 1);
2279 prev
= isl_map_lex_lt_first(isl_map_get_space(test_access
), 1);
2280 test_access
= isl_map_intersect(test_access
, prev
);
2281 scop_cond
= pet_scop_filter(scop_cond
, test_access
, 1);
2283 return pet_scop_add_seq(ctx
, scop_cond
, scop_body
);
2286 /* Check if the while loop is of the form
2288 * while (affine expression)
2291 * If so, call extract_affine_while to construct a scop.
2293 * Otherwise, construct a generic while scop, with iteration domain
2294 * { [t] : t >= 0 }. The scop consists of two parts, one for
2295 * evaluating the condition and one for the body.
2296 * The schedule is adjusted to reflect that the condition is evaluated
2297 * before the body is executed and the body is filtered to depend
2298 * on the result of the condition evaluating to true on all iterations
2299 * up to the current iteration, while the evaluation the condition itself
2300 * is filtered to depend on the result of the condition evaluating to true
2301 * on all previous iterations.
2302 * The context of the scop representing the body is dropped
2303 * because we don't know how many times the body will be executed,
2306 * If the body contains any break, then it is taken into
2307 * account in infinite_domain (if the skip condition is affine)
2308 * or in scop_add_break (if the skip condition is not affine).
2310 struct pet_scop
*PetScan::extract(WhileStmt
*stmt
)
2314 isl_map
*test_access
;
2318 struct pet_scop
*scop
, *scop_body
;
2320 isl_map
*break_access
;
2322 cond
= stmt
->getCond();
2328 clear_assignments
clear(assigned_value
);
2329 clear
.TraverseStmt(stmt
->getBody());
2331 pa
= try_extract_affine_condition(cond
);
2333 return extract_affine_while(pa
, stmt
->getBody());
2335 if (!allow_nested
) {
2340 test_access
= create_test_access(ctx
, n_test
++);
2341 scop
= extract_non_affine_condition(cond
, isl_map_copy(test_access
));
2342 scop
= scop_add_array(scop
, test_access
, ast_context
);
2343 scop_body
= extract(stmt
->getBody());
2345 id
= isl_id_alloc(ctx
, "t", NULL
);
2346 domain
= infinite_domain(isl_id_copy(id
), scop_body
);
2347 ident
= identity_map(domain
);
2349 has_var_break
= pet_scop_has_var_skip(scop_body
, pet_skip_later
);
2351 break_access
= pet_scop_get_skip_map(scop_body
, pet_skip_later
);
2353 scop
= pet_scop_prefix(scop
, 0);
2354 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), isl_map_copy(ident
),
2355 isl_map_copy(ident
), isl_id_copy(id
));
2356 scop_body
= pet_scop_reset_context(scop_body
);
2357 scop_body
= pet_scop_prefix(scop_body
, 1);
2358 scop_body
= pet_scop_embed(scop_body
, isl_set_copy(domain
),
2359 isl_map_copy(ident
), ident
, id
);
2361 if (has_var_break
) {
2362 scop
= scop_add_break(scop
, isl_map_copy(break_access
),
2363 isl_set_copy(domain
), 1);
2364 scop_body
= scop_add_break(scop_body
, break_access
,
2365 isl_set_copy(domain
), 1);
2367 scop
= scop_add_while(scop
, scop_body
, test_access
, domain
, 1);
2372 /* Check whether "cond" expresses a simple loop bound
2373 * on the only set dimension.
2374 * In particular, if "up" is set then "cond" should contain only
2375 * upper bounds on the set dimension.
2376 * Otherwise, it should contain only lower bounds.
2378 static bool is_simple_bound(__isl_keep isl_set
*cond
, __isl_keep isl_val
*inc
)
2380 if (isl_val_is_pos(inc
))
2381 return !isl_set_dim_has_any_lower_bound(cond
, isl_dim_set
, 0);
2383 return !isl_set_dim_has_any_upper_bound(cond
, isl_dim_set
, 0);
2386 /* Extend a condition on a given iteration of a loop to one that
2387 * imposes the same condition on all previous iterations.
2388 * "domain" expresses the lower [upper] bound on the iterations
2389 * when inc is positive [negative].
2391 * In particular, we construct the condition (when inc is positive)
2393 * forall i' : (domain(i') and i' <= i) => cond(i')
2395 * which is equivalent to
2397 * not exists i' : domain(i') and i' <= i and not cond(i')
2399 * We construct this set by negating cond, applying a map
2401 * { [i'] -> [i] : domain(i') and i' <= i }
2403 * and then negating the result again.
2405 static __isl_give isl_set
*valid_for_each_iteration(__isl_take isl_set
*cond
,
2406 __isl_take isl_set
*domain
, __isl_take isl_val
*inc
)
2408 isl_map
*previous_to_this
;
2410 if (isl_val_is_pos(inc
))
2411 previous_to_this
= isl_map_lex_le(isl_set_get_space(domain
));
2413 previous_to_this
= isl_map_lex_ge(isl_set_get_space(domain
));
2415 previous_to_this
= isl_map_intersect_domain(previous_to_this
, domain
);
2417 cond
= isl_set_complement(cond
);
2418 cond
= isl_set_apply(cond
, previous_to_this
);
2419 cond
= isl_set_complement(cond
);
2426 /* Construct a domain of the form
2428 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2430 static __isl_give isl_set
*strided_domain(__isl_take isl_id
*id
,
2431 __isl_take isl_pw_aff
*init
, __isl_take isl_val
*inc
)
2437 init
= isl_pw_aff_insert_dims(init
, isl_dim_in
, 0, 1);
2438 dim
= isl_pw_aff_get_domain_space(init
);
2439 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2440 aff
= isl_aff_add_coefficient_val(aff
, isl_dim_in
, 0, inc
);
2441 init
= isl_pw_aff_add(init
, isl_pw_aff_from_aff(aff
));
2443 dim
= isl_space_set_alloc(isl_pw_aff_get_ctx(init
), 1, 1);
2444 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
2445 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2446 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_param
, 0, 1);
2448 set
= isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff
), init
);
2450 set
= isl_set_lower_bound_si(set
, isl_dim_set
, 0, 0);
2452 return isl_set_params(set
);
2455 /* Assuming "cond" represents a bound on a loop where the loop
2456 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2459 * Under the given assumptions, wrapping is only possible if "cond" allows
2460 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2461 * increasing iterator and 0 in case of a decreasing iterator.
2463 static bool can_wrap(__isl_keep isl_set
*cond
, ValueDecl
*iv
,
2464 __isl_keep isl_val
*inc
)
2471 test
= isl_set_copy(cond
);
2473 ctx
= isl_set_get_ctx(test
);
2474 if (isl_val_is_neg(inc
))
2475 limit
= isl_val_zero(ctx
);
2477 limit
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2478 limit
= isl_val_2exp(limit
);
2479 limit
= isl_val_sub_ui(limit
, 1);
2482 test
= isl_set_fix_val(cond
, isl_dim_set
, 0, limit
);
2483 cw
= !isl_set_is_empty(test
);
2489 /* Given a one-dimensional space, construct the following mapping on this
2492 * { [v] -> [v mod 2^width] }
2494 * where width is the number of bits used to represent the values
2495 * of the unsigned variable "iv".
2497 static __isl_give isl_map
*compute_wrapping(__isl_take isl_space
*dim
,
2505 ctx
= isl_space_get_ctx(dim
);
2506 mod
= isl_val_int_from_ui(ctx
, get_type_size(iv
));
2507 mod
= isl_val_2exp(mod
);
2509 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
2510 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2511 aff
= isl_aff_mod_val(aff
, mod
);
2513 return isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2514 map
= isl_map_reverse(map
);
2517 /* Project out the parameter "id" from "set".
2519 static __isl_give isl_set
*set_project_out_by_id(__isl_take isl_set
*set
,
2520 __isl_keep isl_id
*id
)
2524 pos
= isl_set_find_dim_by_id(set
, isl_dim_param
, id
);
2526 set
= isl_set_project_out(set
, isl_dim_param
, pos
, 1);
2531 /* Compute the set of parameters for which "set1" is a subset of "set2".
2533 * set1 is a subset of set2 if
2535 * forall i in set1 : i in set2
2539 * not exists i in set1 and i not in set2
2543 * not exists i in set1 \ set2
2545 static __isl_give isl_set
*enforce_subset(__isl_take isl_set
*set1
,
2546 __isl_take isl_set
*set2
)
2548 return isl_set_complement(isl_set_params(isl_set_subtract(set1
, set2
)));
2551 /* Compute the set of parameter values for which "cond" holds
2552 * on the next iteration for each element of "dom".
2554 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2555 * and then compute the set of parameters for which the result is a subset
2558 static __isl_give isl_set
*valid_on_next(__isl_take isl_set
*cond
,
2559 __isl_take isl_set
*dom
, __isl_take isl_val
*inc
)
2565 space
= isl_set_get_space(dom
);
2566 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(space
));
2567 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, 0, 1);
2568 aff
= isl_aff_add_constant_val(aff
, inc
);
2569 next
= isl_map_from_basic_map(isl_basic_map_from_aff(aff
));
2571 dom
= isl_set_apply(dom
, next
);
2573 return enforce_subset(dom
, cond
);
2576 /* Does "id" refer to a nested access?
2578 static bool is_nested_parameter(__isl_keep isl_id
*id
)
2580 return id
&& isl_id_get_user(id
) && !isl_id_get_name(id
);
2583 /* Does parameter "pos" of "space" refer to a nested access?
2585 static bool is_nested_parameter(__isl_keep isl_space
*space
, int pos
)
2590 id
= isl_space_get_dim_id(space
, isl_dim_param
, pos
);
2591 nested
= is_nested_parameter(id
);
2597 /* Does "space" involve any parameters that refer to nested
2598 * accesses, i.e., parameters with no name?
2600 static bool has_nested(__isl_keep isl_space
*space
)
2604 nparam
= isl_space_dim(space
, isl_dim_param
);
2605 for (int i
= 0; i
< nparam
; ++i
)
2606 if (is_nested_parameter(space
, i
))
2612 /* Does "pa" involve any parameters that refer to nested
2613 * accesses, i.e., parameters with no name?
2615 static bool has_nested(__isl_keep isl_pw_aff
*pa
)
2620 space
= isl_pw_aff_get_space(pa
);
2621 nested
= has_nested(space
);
2622 isl_space_free(space
);
2627 /* Construct a pet_scop for a for statement.
2628 * The for loop is required to be of the form
2630 * for (i = init; condition; ++i)
2634 * for (i = init; condition; --i)
2636 * The initialization of the for loop should either be an assignment
2637 * to an integer variable, or a declaration of such a variable with
2640 * The condition is allowed to contain nested accesses, provided
2641 * they are not being written to inside the body of the loop.
2642 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2643 * essentially treated as a while loop, with iteration domain
2644 * { [i] : i >= init }.
2646 * We extract a pet_scop for the body and then embed it in a loop with
2647 * iteration domain and schedule
2649 * { [i] : i >= init and condition' }
2654 * { [i] : i <= init and condition' }
2657 * Where condition' is equal to condition if the latter is
2658 * a simple upper [lower] bound and a condition that is extended
2659 * to apply to all previous iterations otherwise.
2661 * If the condition is non-affine, then we drop the condition from the
2662 * iteration domain and instead create a separate statement
2663 * for evaluating the condition. The body is then filtered to depend
2664 * on the result of the condition evaluating to true on all iterations
2665 * up to the current iteration, while the evaluation the condition itself
2666 * is filtered to depend on the result of the condition evaluating to true
2667 * on all previous iterations.
2668 * The context of the scop representing the body is dropped
2669 * because we don't know how many times the body will be executed,
2672 * If the stride of the loop is not 1, then "i >= init" is replaced by
2674 * (exists a: i = init + stride * a and a >= 0)
2676 * If the loop iterator i is unsigned, then wrapping may occur.
2677 * During the computation, we work with a virtual iterator that
2678 * does not wrap. However, the condition in the code applies
2679 * to the wrapped value, so we need to change condition(i)
2680 * into condition([i % 2^width]).
2681 * After computing the virtual domain and schedule, we apply
2682 * the function { [v] -> [v % 2^width] } to the domain and the domain
2683 * of the schedule. In order not to lose any information, we also
2684 * need to intersect the domain of the schedule with the virtual domain
2685 * first, since some iterations in the wrapped domain may be scheduled
2686 * several times, typically an infinite number of times.
2687 * Note that there may be no need to perform this final wrapping
2688 * if the loop condition (after wrapping) satisfies certain conditions.
2689 * However, the is_simple_bound condition is not enough since it doesn't
2690 * check if there even is an upper bound.
2692 * If the loop condition is non-affine, then we keep the virtual
2693 * iterator in the iteration domain and instead replace all accesses
2694 * to the original iterator by the wrapping of the virtual iterator.
2696 * Wrapping on unsigned iterators can be avoided entirely if
2697 * loop condition is simple, the loop iterator is incremented
2698 * [decremented] by one and the last value before wrapping cannot
2699 * possibly satisfy the loop condition.
2701 * Before extracting a pet_scop from the body we remove all
2702 * assignments in assigned_value to variables that are assigned
2703 * somewhere in the body of the loop.
2705 * Valid parameters for a for loop are those for which the initial
2706 * value itself, the increment on each domain iteration and
2707 * the condition on both the initial value and
2708 * the result of incrementing the iterator for each iteration of the domain
2710 * If the loop condition is non-affine, then we only consider validity
2711 * of the initial value.
2713 * If the body contains any break, then we keep track of it in "skip"
2714 * (if the skip condition is affine) or it is handled in scop_add_break
2715 * (if the skip condition is not affine).
2716 * Note that the affine break condition needs to be considered with
2717 * respect to previous iterations in the virtual domain (if any)
2718 * and that the domain needs to be kept virtual if there is a non-affine
2721 struct pet_scop
*PetScan::extract_for(ForStmt
*stmt
)
2723 BinaryOperator
*ass
;
2731 isl_set
*cond
= NULL
;
2732 isl_set
*skip
= NULL
;
2734 struct pet_scop
*scop
, *scop_cond
= NULL
;
2735 assigned_value_cache
cache(assigned_value
);
2741 bool keep_virtual
= false;
2742 bool has_affine_break
;
2744 isl_map
*wrap
= NULL
;
2745 isl_pw_aff
*pa
, *pa_inc
, *init_val
;
2746 isl_set
*valid_init
;
2747 isl_set
*valid_cond
;
2748 isl_set
*valid_cond_init
;
2749 isl_set
*valid_cond_next
;
2751 isl_map
*test_access
= NULL
, *break_access
= NULL
;
2754 if (!stmt
->getInit() && !stmt
->getCond() && !stmt
->getInc())
2755 return extract_infinite_for(stmt
);
2757 init
= stmt
->getInit();
2762 if ((ass
= initialization_assignment(init
)) != NULL
) {
2763 iv
= extract_induction_variable(ass
);
2766 lhs
= ass
->getLHS();
2767 rhs
= ass
->getRHS();
2768 } else if ((decl
= initialization_declaration(init
)) != NULL
) {
2769 VarDecl
*var
= extract_induction_variable(init
, decl
);
2773 rhs
= var
->getInit();
2774 lhs
= create_DeclRefExpr(var
);
2776 unsupported(stmt
->getInit());
2780 pa_inc
= extract_increment(stmt
, iv
);
2785 if (isl_pw_aff_n_piece(pa_inc
) != 1 ||
2786 isl_pw_aff_foreach_piece(pa_inc
, &extract_cst
, &inc
) < 0) {
2787 isl_pw_aff_free(pa_inc
);
2788 unsupported(stmt
->getInc());
2792 valid_inc
= isl_pw_aff_domain(pa_inc
);
2794 is_unsigned
= iv
->getType()->isUnsignedIntegerType();
2796 assigned_value
.erase(iv
);
2797 clear_assignments
clear(assigned_value
);
2798 clear
.TraverseStmt(stmt
->getBody());
2800 id
= isl_id_alloc(ctx
, iv
->getName().str().c_str(), iv
);
2802 pa
= try_extract_nested_condition(stmt
->getCond());
2803 if (allow_nested
&& (!pa
|| has_nested(pa
)))
2806 scop
= extract(stmt
->getBody());
2808 has_affine_break
= scop
&&
2809 pet_scop_has_affine_skip(scop
, pet_skip_later
);
2810 if (has_affine_break
) {
2811 skip
= pet_scop_get_skip(scop
, pet_skip_later
);
2812 skip
= isl_set_fix_si(skip
, isl_dim_set
, 0, 1);
2813 skip
= isl_set_params(skip
);
2815 has_var_break
= scop
&& pet_scop_has_var_skip(scop
, pet_skip_later
);
2816 if (has_var_break
) {
2817 break_access
= pet_scop_get_skip_map(scop
, pet_skip_later
);
2818 keep_virtual
= true;
2821 if (pa
&& !is_nested_allowed(pa
, scop
)) {
2822 isl_pw_aff_free(pa
);
2826 if (!allow_nested
&& !pa
)
2827 pa
= try_extract_affine_condition(stmt
->getCond());
2828 valid_cond
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2829 cond
= isl_pw_aff_non_zero_set(pa
);
2830 if (allow_nested
&& !cond
) {
2831 int save_n_stmt
= n_stmt
;
2832 test_access
= create_test_access(ctx
, n_test
++);
2834 scop_cond
= extract_non_affine_condition(stmt
->getCond(),
2835 isl_map_copy(test_access
));
2836 n_stmt
= save_n_stmt
;
2837 scop_cond
= scop_add_array(scop_cond
, test_access
, ast_context
);
2838 scop_cond
= pet_scop_prefix(scop_cond
, 0);
2839 scop
= pet_scop_reset_context(scop
);
2840 scop
= pet_scop_prefix(scop
, 1);
2841 keep_virtual
= true;
2842 cond
= isl_set_universe(isl_space_set_alloc(ctx
, 0, 0));
2845 cond
= embed(cond
, isl_id_copy(id
));
2846 skip
= embed(skip
, isl_id_copy(id
));
2847 valid_cond
= isl_set_coalesce(valid_cond
);
2848 valid_cond
= embed(valid_cond
, isl_id_copy(id
));
2849 valid_inc
= embed(valid_inc
, isl_id_copy(id
));
2850 is_one
= isl_val_is_one(inc
) || isl_val_is_negone(inc
);
2851 is_virtual
= is_unsigned
&& (!is_one
|| can_wrap(cond
, iv
, inc
));
2853 init_val
= extract_affine(rhs
);
2854 valid_cond_init
= enforce_subset(
2855 isl_set_from_pw_aff(isl_pw_aff_copy(init_val
)),
2856 isl_set_copy(valid_cond
));
2857 if (is_one
&& !is_virtual
) {
2858 isl_pw_aff_free(init_val
);
2859 pa
= extract_comparison(isl_val_is_pos(inc
) ? BO_GE
: BO_LE
,
2861 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(pa
));
2862 valid_init
= set_project_out_by_id(valid_init
, id
);
2863 domain
= isl_pw_aff_non_zero_set(pa
);
2865 valid_init
= isl_pw_aff_domain(isl_pw_aff_copy(init_val
));
2866 domain
= strided_domain(isl_id_copy(id
), init_val
,
2870 domain
= embed(domain
, isl_id_copy(id
));
2873 wrap
= compute_wrapping(isl_set_get_space(cond
), iv
);
2874 rev_wrap
= isl_map_reverse(isl_map_copy(wrap
));
2875 cond
= isl_set_apply(cond
, isl_map_copy(rev_wrap
));
2876 skip
= isl_set_apply(skip
, isl_map_copy(rev_wrap
));
2877 valid_cond
= isl_set_apply(valid_cond
, isl_map_copy(rev_wrap
));
2878 valid_inc
= isl_set_apply(valid_inc
, rev_wrap
);
2880 is_simple
= is_simple_bound(cond
, inc
);
2882 cond
= isl_set_gist(cond
, isl_set_copy(domain
));
2883 is_simple
= is_simple_bound(cond
, inc
);
2886 cond
= valid_for_each_iteration(cond
,
2887 isl_set_copy(domain
), isl_val_copy(inc
));
2888 domain
= isl_set_intersect(domain
, cond
);
2889 if (has_affine_break
) {
2890 skip
= isl_set_intersect(skip
, isl_set_copy(domain
));
2891 skip
= after(skip
, isl_val_sgn(inc
));
2892 domain
= isl_set_subtract(domain
, skip
);
2894 domain
= isl_set_set_dim_id(domain
, isl_dim_set
, 0, isl_id_copy(id
));
2895 space
= isl_space_from_domain(isl_set_get_space(domain
));
2896 space
= isl_space_add_dims(space
, isl_dim_out
, 1);
2897 sched
= isl_map_universe(space
);
2898 if (isl_val_is_pos(inc
))
2899 sched
= isl_map_equate(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2901 sched
= isl_map_oppose(sched
, isl_dim_in
, 0, isl_dim_out
, 0);
2903 valid_cond_next
= valid_on_next(valid_cond
, isl_set_copy(domain
),
2905 valid_inc
= enforce_subset(isl_set_copy(domain
), valid_inc
);
2907 if (is_virtual
&& !keep_virtual
) {
2908 wrap
= isl_map_set_dim_id(wrap
,
2909 isl_dim_out
, 0, isl_id_copy(id
));
2910 sched
= isl_map_intersect_domain(sched
, isl_set_copy(domain
));
2911 domain
= isl_set_apply(domain
, isl_map_copy(wrap
));
2912 sched
= isl_map_apply_domain(sched
, wrap
);
2914 if (!(is_virtual
&& keep_virtual
)) {
2915 space
= isl_set_get_space(domain
);
2916 wrap
= isl_map_identity(isl_space_map_from_set(space
));
2919 scop_cond
= pet_scop_embed(scop_cond
, isl_set_copy(domain
),
2920 isl_map_copy(sched
), isl_map_copy(wrap
), isl_id_copy(id
));
2921 scop
= pet_scop_embed(scop
, isl_set_copy(domain
), sched
, wrap
, id
);
2922 scop
= resolve_nested(scop
);
2924 scop
= scop_add_break(scop
, break_access
, isl_set_copy(domain
),
2927 scop
= scop_add_while(scop_cond
, scop
, test_access
, domain
,
2929 isl_set_free(valid_inc
);
2931 scop
= pet_scop_restrict_context(scop
, valid_inc
);
2932 scop
= pet_scop_restrict_context(scop
, valid_cond_next
);
2933 scop
= pet_scop_restrict_context(scop
, valid_cond_init
);
2934 isl_set_free(domain
);
2936 clear_assignment(assigned_value
, iv
);
2940 scop
= pet_scop_restrict_context(scop
, valid_init
);
2945 struct pet_scop
*PetScan::extract(CompoundStmt
*stmt
, bool skip_declarations
)
2947 return extract(stmt
->children(), true, skip_declarations
);
2950 /* Does parameter "pos" of "map" refer to a nested access?
2952 static bool is_nested_parameter(__isl_keep isl_map
*map
, int pos
)
2957 id
= isl_map_get_dim_id(map
, isl_dim_param
, pos
);
2958 nested
= is_nested_parameter(id
);
2964 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2966 static int n_nested_parameter(__isl_keep isl_space
*space
)
2971 nparam
= isl_space_dim(space
, isl_dim_param
);
2972 for (int i
= 0; i
< nparam
; ++i
)
2973 if (is_nested_parameter(space
, i
))
2979 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2981 static int n_nested_parameter(__isl_keep isl_map
*map
)
2986 space
= isl_map_get_space(map
);
2987 n
= n_nested_parameter(space
);
2988 isl_space_free(space
);
2993 /* For each nested access parameter in "space",
2994 * construct a corresponding pet_expr, place it in args and
2995 * record its position in "param2pos".
2996 * "n_arg" is the number of elements that are already in args.
2997 * The position recorded in "param2pos" takes this number into account.
2998 * If the pet_expr corresponding to a parameter is identical to
2999 * the pet_expr corresponding to an earlier parameter, then these two
3000 * parameters are made to refer to the same element in args.
3002 * Return the final number of elements in args or -1 if an error has occurred.
3004 int PetScan::extract_nested(__isl_keep isl_space
*space
,
3005 int n_arg
, struct pet_expr
**args
, std::map
<int,int> ¶m2pos
)
3009 nparam
= isl_space_dim(space
, isl_dim_param
);
3010 for (int i
= 0; i
< nparam
; ++i
) {
3012 isl_id
*id
= isl_space_get_dim_id(space
, isl_dim_param
, i
);
3015 if (!is_nested_parameter(id
)) {
3020 nested
= (Expr
*) isl_id_get_user(id
);
3021 args
[n_arg
] = extract_expr(nested
);
3025 for (j
= 0; j
< n_arg
; ++j
)
3026 if (pet_expr_is_equal(args
[j
], args
[n_arg
]))
3030 pet_expr_free(args
[n_arg
]);
3034 param2pos
[i
] = n_arg
++;
3042 /* For each nested access parameter in the access relations in "expr",
3043 * construct a corresponding pet_expr, place it in expr->args and
3044 * record its position in "param2pos".
3045 * n is the number of nested access parameters.
3047 struct pet_expr
*PetScan::extract_nested(struct pet_expr
*expr
, int n
,
3048 std::map
<int,int> ¶m2pos
)
3052 expr
->args
= isl_calloc_array(ctx
, struct pet_expr
*, n
);
3057 space
= isl_map_get_space(expr
->acc
.access
);
3058 n
= extract_nested(space
, 0, expr
->args
, param2pos
);
3059 isl_space_free(space
);
3067 pet_expr_free(expr
);
3071 /* Look for parameters in any access relation in "expr" that
3072 * refer to nested accesses. In particular, these are
3073 * parameters with no name.
3075 * If there are any such parameters, then the domain of the access
3076 * relation, which is still [] at this point, is replaced by
3077 * [[] -> [t_1,...,t_n]], with n the number of these parameters
3078 * (after identifying identical nested accesses).
3079 * The parameters are then equated to the corresponding t dimensions
3080 * and subsequently projected out.
3081 * param2pos maps the position of the parameter to the position
3082 * of the corresponding t dimension.
3084 struct pet_expr
*PetScan::resolve_nested(struct pet_expr
*expr
)
3091 std::map
<int,int> param2pos
;
3096 for (int i
= 0; i
< expr
->n_arg
; ++i
) {
3097 expr
->args
[i
] = resolve_nested(expr
->args
[i
]);
3098 if (!expr
->args
[i
]) {
3099 pet_expr_free(expr
);
3104 if (expr
->type
!= pet_expr_access
)
3107 n
= n_nested_parameter(expr
->acc
.access
);
3111 expr
= extract_nested(expr
, n
, param2pos
);
3116 nparam
= isl_map_dim(expr
->acc
.access
, isl_dim_param
);
3117 n_in
= isl_map_dim(expr
->acc
.access
, isl_dim_in
);
3118 dim
= isl_map_get_space(expr
->acc
.access
);
3119 dim
= isl_space_domain(dim
);
3120 dim
= isl_space_from_domain(dim
);
3121 dim
= isl_space_add_dims(dim
, isl_dim_out
, n
);
3122 map
= isl_map_universe(dim
);
3123 map
= isl_map_domain_map(map
);
3124 map
= isl_map_reverse(map
);
3125 expr
->acc
.access
= isl_map_apply_domain(expr
->acc
.access
, map
);
3127 for (int i
= nparam
- 1; i
>= 0; --i
) {
3128 isl_id
*id
= isl_map_get_dim_id(expr
->acc
.access
,
3130 if (!is_nested_parameter(id
)) {
3135 expr
->acc
.access
= isl_map_equate(expr
->acc
.access
,
3136 isl_dim_param
, i
, isl_dim_in
,
3137 n_in
+ param2pos
[i
]);
3138 expr
->acc
.access
= isl_map_project_out(expr
->acc
.access
,
3139 isl_dim_param
, i
, 1);
3146 pet_expr_free(expr
);
3150 /* Return the file offset of the expansion location of "Loc".
3152 static unsigned getExpansionOffset(SourceManager
&SM
, SourceLocation Loc
)
3154 return SM
.getFileOffset(SM
.getExpansionLoc(Loc
));
3157 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3159 /* Return a SourceLocation for the location after the first semicolon
3160 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3161 * call it and also skip trailing spaces and newline.
3163 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3164 const LangOptions
&LO
)
3166 return Lexer::findLocationAfterToken(loc
, tok::semi
, SM
, LO
, true);
3171 /* Return a SourceLocation for the location after the first semicolon
3172 * after "loc". If Lexer::findLocationAfterToken is not available,
3173 * we look in the underlying character data for the first semicolon.
3175 static SourceLocation
location_after_semi(SourceLocation loc
, SourceManager
&SM
,
3176 const LangOptions
&LO
)
3179 const char *s
= SM
.getCharacterData(loc
);
3181 semi
= strchr(s
, ';');
3183 return SourceLocation();
3184 return loc
.getFileLocWithOffset(semi
+ 1 - s
);
3189 /* If the token at "loc" is the first token on the line, then return
3190 * a location referring to the start of the line.
3191 * Otherwise, return "loc".
3193 * This function is used to extend a scop to the start of the line
3194 * if the first token of the scop is also the first token on the line.
3196 * We look for the first token on the line. If its location is equal to "loc",
3197 * then the latter is the location of the first token on the line.
3199 static SourceLocation
move_to_start_of_line_if_first_token(SourceLocation loc
,
3200 SourceManager
&SM
, const LangOptions
&LO
)
3202 std::pair
<FileID
, unsigned> file_offset_pair
;
3203 llvm::StringRef file
;
3206 SourceLocation token_loc
, line_loc
;
3209 loc
= SM
.getExpansionLoc(loc
);
3210 col
= SM
.getExpansionColumnNumber(loc
);
3211 line_loc
= loc
.getLocWithOffset(1 - col
);
3212 file_offset_pair
= SM
.getDecomposedLoc(line_loc
);
3213 file
= SM
.getBufferData(file_offset_pair
.first
, NULL
);
3214 pos
= file
.data() + file_offset_pair
.second
;
3216 Lexer
lexer(SM
.getLocForStartOfFile(file_offset_pair
.first
), LO
,
3217 file
.begin(), pos
, file
.end());
3218 lexer
.LexFromRawLexer(tok
);
3219 token_loc
= tok
.getLocation();
3221 if (token_loc
== loc
)
3227 /* Convert a top-level pet_expr to a pet_scop with one statement.
3228 * This mainly involves resolving nested expression parameters
3229 * and setting the name of the iteration space.
3230 * The name is given by "label" if it is non-NULL. Otherwise,
3231 * it is of the form S_<n_stmt>.
3232 * start and end of the pet_scop are derived from those of "stmt".
3234 struct pet_scop
*PetScan::extract(Stmt
*stmt
, struct pet_expr
*expr
,
3235 __isl_take isl_id
*label
)
3237 struct pet_stmt
*ps
;
3238 struct pet_scop
*scop
;
3239 SourceLocation loc
= stmt
->getLocStart();
3240 SourceManager
&SM
= PP
.getSourceManager();
3241 const LangOptions
&LO
= PP
.getLangOpts();
3242 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3243 unsigned start
, end
;
3245 expr
= resolve_nested(expr
);
3246 ps
= pet_stmt_from_pet_expr(ctx
, line
, label
, n_stmt
++, expr
);
3247 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3249 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
);
3250 start
= getExpansionOffset(SM
, loc
);
3251 loc
= stmt
->getLocEnd();
3252 loc
= location_after_semi(loc
, SM
, LO
);
3253 end
= getExpansionOffset(SM
, loc
);
3255 scop
= pet_scop_update_start_end(scop
, start
, end
);
3259 /* Check if we can extract an affine expression from "expr".
3260 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3261 * We turn on autodetection so that we won't generate any warnings
3262 * and turn off nesting, so that we won't accept any non-affine constructs.
3264 __isl_give isl_pw_aff
*PetScan::try_extract_affine(Expr
*expr
)
3267 int save_autodetect
= options
->autodetect
;
3268 bool save_nesting
= nesting_enabled
;
3270 options
->autodetect
= 1;
3271 nesting_enabled
= false;
3273 pwaff
= extract_affine(expr
);
3275 options
->autodetect
= save_autodetect
;
3276 nesting_enabled
= save_nesting
;
3281 /* Check whether "expr" is an affine expression.
3283 bool PetScan::is_affine(Expr
*expr
)
3287 pwaff
= try_extract_affine(expr
);
3288 isl_pw_aff_free(pwaff
);
3290 return pwaff
!= NULL
;
3293 /* Check if we can extract an affine constraint from "expr".
3294 * Return the constraint as an isl_set if we can and NULL otherwise.
3295 * We turn on autodetection so that we won't generate any warnings
3296 * and turn off nesting, so that we won't accept any non-affine constructs.
3298 __isl_give isl_pw_aff
*PetScan::try_extract_affine_condition(Expr
*expr
)
3301 int save_autodetect
= options
->autodetect
;
3302 bool save_nesting
= nesting_enabled
;
3304 options
->autodetect
= 1;
3305 nesting_enabled
= false;
3307 cond
= extract_condition(expr
);
3309 options
->autodetect
= save_autodetect
;
3310 nesting_enabled
= save_nesting
;
3315 /* Check whether "expr" is an affine constraint.
3317 bool PetScan::is_affine_condition(Expr
*expr
)
3321 cond
= try_extract_affine_condition(expr
);
3322 isl_pw_aff_free(cond
);
3324 return cond
!= NULL
;
3327 /* Check if we can extract a condition from "expr".
3328 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3329 * If allow_nested is set, then the condition may involve parameters
3330 * corresponding to nested accesses.
3331 * We turn on autodetection so that we won't generate any warnings.
3333 __isl_give isl_pw_aff
*PetScan::try_extract_nested_condition(Expr
*expr
)
3336 int save_autodetect
= options
->autodetect
;
3337 bool save_nesting
= nesting_enabled
;
3339 options
->autodetect
= 1;
3340 nesting_enabled
= allow_nested
;
3341 cond
= extract_condition(expr
);
3343 options
->autodetect
= save_autodetect
;
3344 nesting_enabled
= save_nesting
;
3349 /* If the top-level expression of "stmt" is an assignment, then
3350 * return that assignment as a BinaryOperator.
3351 * Otherwise return NULL.
3353 static BinaryOperator
*top_assignment_or_null(Stmt
*stmt
)
3355 BinaryOperator
*ass
;
3359 if (stmt
->getStmtClass() != Stmt::BinaryOperatorClass
)
3362 ass
= cast
<BinaryOperator
>(stmt
);
3363 if(ass
->getOpcode() != BO_Assign
)
3369 /* Check if the given if statement is a conditional assignement
3370 * with a non-affine condition. If so, construct a pet_scop
3371 * corresponding to this conditional assignment. Otherwise return NULL.
3373 * In particular we check if "stmt" is of the form
3380 * where a is some array or scalar access.
3381 * The constructed pet_scop then corresponds to the expression
3383 * a = condition ? f(...) : g(...)
3385 * All access relations in f(...) are intersected with condition
3386 * while all access relation in g(...) are intersected with the complement.
3388 struct pet_scop
*PetScan::extract_conditional_assignment(IfStmt
*stmt
)
3390 BinaryOperator
*ass_then
, *ass_else
;
3391 isl_map
*write_then
, *write_else
;
3392 isl_set
*cond
, *comp
;
3396 struct pet_expr
*pe_cond
, *pe_then
, *pe_else
, *pe
, *pe_write
;
3397 bool save_nesting
= nesting_enabled
;
3399 if (!options
->detect_conditional_assignment
)
3402 ass_then
= top_assignment_or_null(stmt
->getThen());
3403 ass_else
= top_assignment_or_null(stmt
->getElse());
3405 if (!ass_then
|| !ass_else
)
3408 if (is_affine_condition(stmt
->getCond()))
3411 write_then
= extract_access(ass_then
->getLHS());
3412 write_else
= extract_access(ass_else
->getLHS());
3414 equal
= isl_map_is_equal(write_then
, write_else
);
3415 isl_map_free(write_else
);
3416 if (equal
< 0 || !equal
) {
3417 isl_map_free(write_then
);
3421 nesting_enabled
= allow_nested
;
3422 pa
= extract_condition(stmt
->getCond());
3423 nesting_enabled
= save_nesting
;
3424 cond
= isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa
));
3425 comp
= isl_pw_aff_zero_set(isl_pw_aff_copy(pa
));
3426 map
= isl_map_from_range(isl_set_from_pw_aff(pa
));
3428 pe_cond
= pet_expr_from_access(map
);
3430 pe_then
= extract_expr(ass_then
->getRHS());
3431 pe_then
= pet_expr_restrict(pe_then
, cond
);
3432 pe_else
= extract_expr(ass_else
->getRHS());
3433 pe_else
= pet_expr_restrict(pe_else
, comp
);
3435 pe
= pet_expr_new_ternary(ctx
, pe_cond
, pe_then
, pe_else
);
3436 pe_write
= pet_expr_from_access(write_then
);
3438 pe_write
->acc
.write
= 1;
3439 pe_write
->acc
.read
= 0;
3441 pe
= pet_expr_new_binary(ctx
, pet_op_assign
, pe_write
, pe
);
3442 return extract(stmt
, pe
);
3445 /* Create a pet_scop with a single statement evaluating "cond"
3446 * and writing the result to a virtual scalar, as expressed by
3449 struct pet_scop
*PetScan::extract_non_affine_condition(Expr
*cond
,
3450 __isl_take isl_map
*access
)
3452 struct pet_expr
*expr
, *write
;
3453 struct pet_stmt
*ps
;
3454 struct pet_scop
*scop
;
3455 SourceLocation loc
= cond
->getLocStart();
3456 int line
= PP
.getSourceManager().getExpansionLineNumber(loc
);
3458 write
= pet_expr_from_access(access
);
3460 write
->acc
.write
= 1;
3461 write
->acc
.read
= 0;
3463 expr
= extract_expr(cond
);
3464 expr
= resolve_nested(expr
);
3465 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, write
, expr
);
3466 ps
= pet_stmt_from_pet_expr(ctx
, line
, NULL
, n_stmt
++, expr
);
3467 scop
= pet_scop_from_pet_stmt(ctx
, ps
);
3468 scop
= resolve_nested(scop
);
3474 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
,
3478 /* Apply the map pointed to by "user" to the domain of the access
3479 * relation, thereby embedding it in the range of the map.
3480 * The domain of both relations is the zero-dimensional domain.
3482 static __isl_give isl_map
*embed_access(__isl_take isl_map
*access
, void *user
)
3484 isl_map
*map
= (isl_map
*) user
;
3486 return isl_map_apply_domain(access
, isl_map_copy(map
));
3489 /* Apply "map" to all access relations in "expr".
3491 static struct pet_expr
*embed(struct pet_expr
*expr
, __isl_keep isl_map
*map
)
3493 return pet_expr_foreach_access(expr
, &embed_access
, map
);
3496 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3498 static int n_nested_parameter(__isl_keep isl_set
*set
)
3503 space
= isl_set_get_space(set
);
3504 n
= n_nested_parameter(space
);
3505 isl_space_free(space
);
3510 /* Remove all parameters from "map" that refer to nested accesses.
3512 static __isl_give isl_map
*remove_nested_parameters(__isl_take isl_map
*map
)
3517 space
= isl_map_get_space(map
);
3518 nparam
= isl_space_dim(space
, isl_dim_param
);
3519 for (int i
= nparam
- 1; i
>= 0; --i
)
3520 if (is_nested_parameter(space
, i
))
3521 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3522 isl_space_free(space
);
3528 static __isl_give isl_map
*access_remove_nested_parameters(
3529 __isl_take isl_map
*access
, void *user
);
3532 static __isl_give isl_map
*access_remove_nested_parameters(
3533 __isl_take isl_map
*access
, void *user
)
3535 return remove_nested_parameters(access
);
3538 /* Remove all nested access parameters from the schedule and all
3539 * accesses of "stmt".
3540 * There is no need to remove them from the domain as these parameters
3541 * have already been removed from the domain when this function is called.
3543 static struct pet_stmt
*remove_nested_parameters(struct pet_stmt
*stmt
)
3547 stmt
->schedule
= remove_nested_parameters(stmt
->schedule
);
3548 stmt
->body
= pet_expr_foreach_access(stmt
->body
,
3549 &access_remove_nested_parameters
, NULL
);
3550 if (!stmt
->schedule
|| !stmt
->body
)
3552 for (int i
= 0; i
< stmt
->n_arg
; ++i
) {
3553 stmt
->args
[i
] = pet_expr_foreach_access(stmt
->args
[i
],
3554 &access_remove_nested_parameters
, NULL
);
3561 pet_stmt_free(stmt
);
3565 /* For each nested access parameter in the domain of "stmt",
3566 * construct a corresponding pet_expr, place it before the original
3567 * elements in stmt->args and record its position in "param2pos".
3568 * n is the number of nested access parameters.
3570 struct pet_stmt
*PetScan::extract_nested(struct pet_stmt
*stmt
, int n
,
3571 std::map
<int,int> ¶m2pos
)
3576 struct pet_expr
**args
;
3578 n_arg
= stmt
->n_arg
;
3579 args
= isl_calloc_array(ctx
, struct pet_expr
*, n
+ n_arg
);
3583 space
= isl_set_get_space(stmt
->domain
);
3584 n_arg
= extract_nested(space
, 0, args
, param2pos
);
3585 isl_space_free(space
);
3590 for (i
= 0; i
< stmt
->n_arg
; ++i
)
3591 args
[n_arg
+ i
] = stmt
->args
[i
];
3594 stmt
->n_arg
+= n_arg
;
3599 for (i
= 0; i
< n
; ++i
)
3600 pet_expr_free(args
[i
]);
3603 pet_stmt_free(stmt
);
3607 /* Check whether any of the arguments i of "stmt" starting at position "n"
3608 * is equal to one of the first "n" arguments j.
3609 * If so, combine the constraints on arguments i and j and remove
3612 static struct pet_stmt
*remove_duplicate_arguments(struct pet_stmt
*stmt
, int n
)
3621 if (n
== stmt
->n_arg
)
3624 map
= isl_set_unwrap(stmt
->domain
);
3626 for (i
= stmt
->n_arg
- 1; i
>= n
; --i
) {
3627 for (j
= 0; j
< n
; ++j
)
3628 if (pet_expr_is_equal(stmt
->args
[i
], stmt
->args
[j
]))
3633 map
= isl_map_equate(map
, isl_dim_out
, i
, isl_dim_out
, j
);
3634 map
= isl_map_project_out(map
, isl_dim_out
, i
, 1);
3636 pet_expr_free(stmt
->args
[i
]);
3637 for (j
= i
; j
+ 1 < stmt
->n_arg
; ++j
)
3638 stmt
->args
[j
] = stmt
->args
[j
+ 1];
3642 stmt
->domain
= isl_map_wrap(map
);
3647 pet_stmt_free(stmt
);
3651 /* Look for parameters in the iteration domain of "stmt" that
3652 * refer to nested accesses. In particular, these are
3653 * parameters with no name.
3655 * If there are any such parameters, then as many extra variables
3656 * (after identifying identical nested accesses) are inserted in the
3657 * range of the map wrapped inside the domain, before the original variables.
3658 * If the original domain is not a wrapped map, then a new wrapped
3659 * map is created with zero output dimensions.
3660 * The parameters are then equated to the corresponding output dimensions
3661 * and subsequently projected out, from the iteration domain,
3662 * the schedule and the access relations.
3663 * For each of the output dimensions, a corresponding argument
3664 * expression is inserted. Initially they are created with
3665 * a zero-dimensional domain, so they have to be embedded
3666 * in the current iteration domain.
3667 * param2pos maps the position of the parameter to the position
3668 * of the corresponding output dimension in the wrapped map.
3670 struct pet_stmt
*PetScan::resolve_nested(struct pet_stmt
*stmt
)
3676 std::map
<int,int> param2pos
;
3681 n
= n_nested_parameter(stmt
->domain
);
3685 n_arg
= stmt
->n_arg
;
3686 stmt
= extract_nested(stmt
, n
, param2pos
);
3690 n
= stmt
->n_arg
- n_arg
;
3691 nparam
= isl_set_dim(stmt
->domain
, isl_dim_param
);
3692 if (isl_set_is_wrapping(stmt
->domain
))
3693 map
= isl_set_unwrap(stmt
->domain
);
3695 map
= isl_map_from_domain(stmt
->domain
);
3696 map
= isl_map_insert_dims(map
, isl_dim_out
, 0, n
);
3698 for (int i
= nparam
- 1; i
>= 0; --i
) {
3701 if (!is_nested_parameter(map
, i
))
3704 id
= isl_map_get_tuple_id(stmt
->args
[param2pos
[i
]]->acc
.access
,
3706 map
= isl_map_set_dim_id(map
, isl_dim_out
, param2pos
[i
], id
);
3707 map
= isl_map_equate(map
, isl_dim_param
, i
, isl_dim_out
,
3709 map
= isl_map_project_out(map
, isl_dim_param
, i
, 1);
3712 stmt
->domain
= isl_map_wrap(map
);
3714 map
= isl_set_unwrap(isl_set_copy(stmt
->domain
));
3715 map
= isl_map_from_range(isl_map_domain(map
));
3716 for (int pos
= 0; pos
< n
; ++pos
)
3717 stmt
->args
[pos
] = embed(stmt
->args
[pos
], map
);
3720 stmt
= remove_nested_parameters(stmt
);
3721 stmt
= remove_duplicate_arguments(stmt
, n
);
3725 pet_stmt_free(stmt
);
3729 /* For each statement in "scop", move the parameters that correspond
3730 * to nested access into the ranges of the domains and create
3731 * corresponding argument expressions.
3733 struct pet_scop
*PetScan::resolve_nested(struct pet_scop
*scop
)
3738 for (int i
= 0; i
< scop
->n_stmt
; ++i
) {
3739 scop
->stmts
[i
] = resolve_nested(scop
->stmts
[i
]);
3740 if (!scop
->stmts
[i
])
3746 pet_scop_free(scop
);
3750 /* Given an access expression "expr", is the variable accessed by
3751 * "expr" assigned anywhere inside "scop"?
3753 static bool is_assigned(pet_expr
*expr
, pet_scop
*scop
)
3755 bool assigned
= false;
3758 id
= isl_map_get_tuple_id(expr
->acc
.access
, isl_dim_out
);
3759 assigned
= pet_scop_writes(scop
, id
);
3765 /* Are all nested access parameters in "pa" allowed given "scop".
3766 * In particular, is none of them written by anywhere inside "scop".
3768 * If "scop" has any skip conditions, then no nested access parameters
3769 * are allowed. In particular, if there is any nested access in a guard
3770 * for a piece of code containing a "continue", then we want to introduce
3771 * a separate statement for evaluating this guard so that we can express
3772 * that the result is false for all previous iterations.
3774 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff
*pa
, pet_scop
*scop
)
3781 nparam
= isl_pw_aff_dim(pa
, isl_dim_param
);
3782 for (int i
= 0; i
< nparam
; ++i
) {
3784 isl_id
*id
= isl_pw_aff_get_dim_id(pa
, isl_dim_param
, i
);
3788 if (!is_nested_parameter(id
)) {
3793 if (pet_scop_has_skip(scop
, pet_skip_now
)) {
3798 nested
= (Expr
*) isl_id_get_user(id
);
3799 expr
= extract_expr(nested
);
3800 allowed
= expr
&& expr
->type
== pet_expr_access
&&
3801 !is_assigned(expr
, scop
);
3803 pet_expr_free(expr
);
3813 /* Do we need to construct a skip condition of the given type
3814 * on an if statement, given that the if condition is non-affine?
3816 * pet_scop_filter_skip can only handle the case where the if condition
3817 * holds (the then branch) and the skip condition is universal.
3818 * In any other case, we need to construct a new skip condition.
3820 static bool need_skip(struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3821 bool have_else
, enum pet_skip type
)
3823 if (have_else
&& scop_else
&& pet_scop_has_skip(scop_else
, type
))
3825 if (scop_then
&& pet_scop_has_skip(scop_then
, type
) &&
3826 !pet_scop_has_universal_skip(scop_then
, type
))
3831 /* Do we need to construct a skip condition of the given type
3832 * on an if statement, given that the if condition is affine?
3834 * There is no need to construct a new skip condition if all
3835 * the skip conditions are affine.
3837 static bool need_skip_aff(struct pet_scop
*scop_then
,
3838 struct pet_scop
*scop_else
, bool have_else
, enum pet_skip type
)
3840 if (scop_then
&& pet_scop_has_var_skip(scop_then
, type
))
3842 if (have_else
&& scop_else
&& pet_scop_has_var_skip(scop_else
, type
))
3847 /* Do we need to construct a skip condition of the given type
3848 * on an if statement?
3850 static bool need_skip(struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
3851 bool have_else
, enum pet_skip type
, bool affine
)
3854 return need_skip_aff(scop_then
, scop_else
, have_else
, type
);
3856 return need_skip(scop_then
, scop_else
, have_else
, type
);
3859 /* Construct an affine expression pet_expr that evaluates
3860 * to the constant "val".
3862 static struct pet_expr
*universally(isl_ctx
*ctx
, int val
)
3867 space
= isl_space_alloc(ctx
, 0, 0, 1);
3868 map
= isl_map_universe(space
);
3869 map
= isl_map_fix_si(map
, isl_dim_out
, 0, val
);
3871 return pet_expr_from_access(map
);
3874 /* Construct an affine expression pet_expr that evaluates
3875 * to the constant 1.
3877 static struct pet_expr
*universally_true(isl_ctx
*ctx
)
3879 return universally(ctx
, 1);
3882 /* Construct an affine expression pet_expr that evaluates
3883 * to the constant 0.
3885 static struct pet_expr
*universally_false(isl_ctx
*ctx
)
3887 return universally(ctx
, 0);
3890 /* Given an access relation "test_access" for the if condition,
3891 * an access relation "skip_access" for the skip condition and
3892 * scops for the then and else branches, construct a scop for
3893 * computing "skip_access".
3895 * The computed scop contains a single statement that essentially does
3897 * skip_cond = test_cond ? skip_cond_then : skip_cond_else
3899 * If the skip conditions of the then and/or else branch are not affine,
3900 * then they need to be filtered by test_access.
3901 * If they are missing, then this means the skip condition is false.
3903 * Since we are constructing a skip condition for the if statement,
3904 * the skip conditions on the then and else branches are removed.
3906 static struct pet_scop
*extract_skip(PetScan
*scan
,
3907 __isl_take isl_map
*test_access
, __isl_take isl_map
*skip_access
,
3908 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
, bool have_else
,
3911 struct pet_expr
*expr_then
, *expr_else
, *expr
, *expr_skip
;
3912 struct pet_stmt
*stmt
;
3913 struct pet_scop
*scop
;
3914 isl_ctx
*ctx
= scan
->ctx
;
3918 if (have_else
&& !scop_else
)
3921 if (pet_scop_has_skip(scop_then
, type
)) {
3922 expr_then
= pet_scop_get_skip_expr(scop_then
, type
);
3923 pet_scop_reset_skip(scop_then
, type
);
3924 if (!pet_expr_is_affine(expr_then
))
3925 expr_then
= pet_expr_filter(expr_then
,
3926 isl_map_copy(test_access
), 1);
3928 expr_then
= universally_false(ctx
);
3930 if (have_else
&& pet_scop_has_skip(scop_else
, type
)) {
3931 expr_else
= pet_scop_get_skip_expr(scop_else
, type
);
3932 pet_scop_reset_skip(scop_else
, type
);
3933 if (!pet_expr_is_affine(expr_else
))
3934 expr_else
= pet_expr_filter(expr_else
,
3935 isl_map_copy(test_access
), 0);
3937 expr_else
= universally_false(ctx
);
3939 expr
= pet_expr_from_access(test_access
);
3940 expr
= pet_expr_new_ternary(ctx
, expr
, expr_then
, expr_else
);
3941 expr_skip
= pet_expr_from_access(isl_map_copy(skip_access
));
3943 expr_skip
->acc
.write
= 1;
3944 expr_skip
->acc
.read
= 0;
3946 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, expr_skip
, expr
);
3947 stmt
= pet_stmt_from_pet_expr(ctx
, -1, NULL
, scan
->n_stmt
++, expr
);
3949 scop
= pet_scop_from_pet_stmt(ctx
, stmt
);
3950 scop
= scop_add_array(scop
, skip_access
, scan
->ast_context
);
3951 isl_map_free(skip_access
);
3955 isl_map_free(test_access
);
3956 isl_map_free(skip_access
);
3960 /* Is scop's skip_now condition equal to its skip_later condition?
3961 * In particular, this means that it either has no skip_now condition
3962 * or both a skip_now and a skip_later condition (that are equal to each other).
3964 static bool skip_equals_skip_later(struct pet_scop
*scop
)
3966 int has_skip_now
, has_skip_later
;
3968 isl_set
*skip_now
, *skip_later
;
3972 has_skip_now
= pet_scop_has_skip(scop
, pet_skip_now
);
3973 has_skip_later
= pet_scop_has_skip(scop
, pet_skip_later
);
3974 if (has_skip_now
!= has_skip_later
)
3979 skip_now
= pet_scop_get_skip(scop
, pet_skip_now
);
3980 skip_later
= pet_scop_get_skip(scop
, pet_skip_later
);
3981 equal
= isl_set_is_equal(skip_now
, skip_later
);
3982 isl_set_free(skip_now
);
3983 isl_set_free(skip_later
);
3988 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
3990 static void drop_skip_later(struct pet_scop
*scop1
, struct pet_scop
*scop2
)
3992 pet_scop_reset_skip(scop1
, pet_skip_later
);
3993 pet_scop_reset_skip(scop2
, pet_skip_later
);
3996 /* Structure that handles the construction of skip conditions.
3998 * scop_then and scop_else represent the then and else branches
3999 * of the if statement
4001 * skip[type] is true if we need to construct a skip condition of that type
4002 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
4003 * are equal to each other
4004 * access[type] is the virtual array representing the skip condition
4005 * scop[type] is a scop for computing the skip condition
4007 struct pet_skip_info
{
4013 struct pet_scop
*scop
[2];
4015 pet_skip_info(isl_ctx
*ctx
) : ctx(ctx
) {}
4017 operator bool() { return skip
[pet_skip_now
] || skip
[pet_skip_later
]; }
4020 /* Structure that handles the construction of skip conditions on if statements.
4022 * scop_then and scop_else represent the then and else branches
4023 * of the if statement
4025 struct pet_skip_info_if
: public pet_skip_info
{
4026 struct pet_scop
*scop_then
, *scop_else
;
4029 pet_skip_info_if(isl_ctx
*ctx
, struct pet_scop
*scop_then
,
4030 struct pet_scop
*scop_else
, bool have_else
, bool affine
);
4031 void extract(PetScan
*scan
, __isl_keep isl_map
*access
,
4032 enum pet_skip type
);
4033 void extract(PetScan
*scan
, __isl_keep isl_map
*access
);
4034 void extract(PetScan
*scan
, __isl_keep isl_pw_aff
*cond
);
4035 struct pet_scop
*add(struct pet_scop
*scop
, enum pet_skip type
,
4037 struct pet_scop
*add(struct pet_scop
*scop
, int offset
);
4040 /* Initialize a pet_skip_info_if structure based on the then and else branches
4041 * and based on whether the if condition is affine or not.
4043 pet_skip_info_if::pet_skip_info_if(isl_ctx
*ctx
, struct pet_scop
*scop_then
,
4044 struct pet_scop
*scop_else
, bool have_else
, bool affine
) :
4045 pet_skip_info(ctx
), scop_then(scop_then
), scop_else(scop_else
),
4046 have_else(have_else
)
4048 skip
[pet_skip_now
] =
4049 need_skip(scop_then
, scop_else
, have_else
, pet_skip_now
, affine
);
4050 equal
= skip
[pet_skip_now
] && skip_equals_skip_later(scop_then
) &&
4051 (!have_else
|| skip_equals_skip_later(scop_else
));
4052 skip
[pet_skip_later
] = skip
[pet_skip_now
] && !equal
&&
4053 need_skip(scop_then
, scop_else
, have_else
, pet_skip_later
, affine
);
4056 /* If we need to construct a skip condition of the given type,
4059 * "map" represents the if condition.
4061 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_map
*map
,
4067 access
[type
] = create_test_access(isl_map_get_ctx(map
), scan
->n_test
++);
4068 scop
[type
] = extract_skip(scan
, isl_map_copy(map
),
4069 isl_map_copy(access
[type
]),
4070 scop_then
, scop_else
, have_else
, type
);
4073 /* Construct the required skip conditions, given the if condition "map".
4075 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_map
*map
)
4077 extract(scan
, map
, pet_skip_now
);
4078 extract(scan
, map
, pet_skip_later
);
4080 drop_skip_later(scop_then
, scop_else
);
4083 /* Construct the required skip conditions, given the if condition "cond".
4085 void pet_skip_info_if::extract(PetScan
*scan
, __isl_keep isl_pw_aff
*cond
)
4090 if (!skip
[pet_skip_now
] && !skip
[pet_skip_later
])
4093 test_set
= isl_set_from_pw_aff(isl_pw_aff_copy(cond
));
4094 test
= isl_map_from_range(test_set
);
4095 extract(scan
, test
);
4099 /* Add the computed skip condition of the give type to "main" and
4100 * add the scop for computing the condition at the given offset.
4102 * If equal is set, then we only computed a skip condition for pet_skip_now,
4103 * but we also need to set it as main's pet_skip_later.
4105 struct pet_scop
*pet_skip_info_if::add(struct pet_scop
*main
,
4106 enum pet_skip type
, int offset
)
4113 skip_set
= isl_map_range(access
[type
]);
4114 access
[type
] = NULL
;
4115 scop
[type
] = pet_scop_prefix(scop
[type
], offset
);
4116 main
= pet_scop_add_par(ctx
, main
, scop
[type
]);
4120 main
= pet_scop_set_skip(main
, pet_skip_later
,
4121 isl_set_copy(skip_set
));
4123 main
= pet_scop_set_skip(main
, type
, skip_set
);
4128 /* Add the computed skip conditions to "main" and
4129 * add the scops for computing the conditions at the given offset.
4131 struct pet_scop
*pet_skip_info_if::add(struct pet_scop
*scop
, int offset
)
4133 scop
= add(scop
, pet_skip_now
, offset
);
4134 scop
= add(scop
, pet_skip_later
, offset
);
4139 /* Construct a pet_scop for a non-affine if statement.
4141 * We create a separate statement that writes the result
4142 * of the non-affine condition to a virtual scalar.
4143 * A constraint requiring the value of this virtual scalar to be one
4144 * is added to the iteration domains of the then branch.
4145 * Similarly, a constraint requiring the value of this virtual scalar
4146 * to be zero is added to the iteration domains of the else branch, if any.
4147 * We adjust the schedules to ensure that the virtual scalar is written
4148 * before it is read.
4150 * If there are any breaks or continues in the then and/or else
4151 * branches, then we may have to compute a new skip condition.
4152 * This is handled using a pet_skip_info_if object.
4153 * On initialization, the object checks if skip conditions need
4154 * to be computed. If so, it does so in "extract" and adds them in "add".
4156 struct pet_scop
*PetScan::extract_non_affine_if(Expr
*cond
,
4157 struct pet_scop
*scop_then
, struct pet_scop
*scop_else
,
4158 bool have_else
, int stmt_id
)
4160 struct pet_scop
*scop
;
4161 isl_map
*test_access
;
4162 int save_n_stmt
= n_stmt
;
4164 test_access
= create_test_access(ctx
, n_test
++);
4166 scop
= extract_non_affine_condition(cond
, isl_map_copy(test_access
));
4167 n_stmt
= save_n_stmt
;
4168 scop
= scop_add_array(scop
, test_access
, ast_context
);
4170 pet_skip_info_if
skip(ctx
, scop_then
, scop_else
, have_else
, false);
4171 skip
.extract(this, test_access
);
4173 scop
= pet_scop_prefix(scop
, 0);
4174 scop_then
= pet_scop_prefix(scop_then
, 1);
4175 scop_then
= pet_scop_filter(scop_then
, isl_map_copy(test_access
), 1);
4177 scop_else
= pet_scop_prefix(scop_else
, 1);
4178 scop_else
= pet_scop_filter(scop_else
, test_access
, 0);
4179 scop_then
= pet_scop_add_par(ctx
, scop_then
, scop_else
);
4181 isl_map_free(test_access
);
4183 scop
= pet_scop_add_seq(ctx
, scop
, scop_then
);
4185 scop
= skip
.add(scop
, 2);
4190 /* Construct a pet_scop for an if statement.
4192 * If the condition fits the pattern of a conditional assignment,
4193 * then it is handled by extract_conditional_assignment.
4194 * Otherwise, we do the following.
4196 * If the condition is affine, then the condition is added
4197 * to the iteration domains of the then branch, while the
4198 * opposite of the condition in added to the iteration domains
4199 * of the else branch, if any.
4200 * We allow the condition to be dynamic, i.e., to refer to
4201 * scalars or array elements that may be written to outside
4202 * of the given if statement. These nested accesses are then represented
4203 * as output dimensions in the wrapping iteration domain.
4204 * If it also written _inside_ the then or else branch, then
4205 * we treat the condition as non-affine.
4206 * As explained in extract_non_affine_if, this will introduce
4207 * an extra statement.
4208 * For aesthetic reasons, we want this statement to have a statement
4209 * number that is lower than those of the then and else branches.
4210 * In order to evaluate if will need such a statement, however, we
4211 * first construct scops for the then and else branches.
4212 * We therefore reserve a statement number if we might have to
4213 * introduce such an extra statement.
4215 * If the condition is not affine, then the scop is created in
4216 * extract_non_affine_if.
4218 * If there are any breaks or continues in the then and/or else
4219 * branches, then we may have to compute a new skip condition.
4220 * This is handled using a pet_skip_info_if object.
4221 * On initialization, the object checks if skip conditions need
4222 * to be computed. If so, it does so in "extract" and adds them in "add".
4224 struct pet_scop
*PetScan::extract(IfStmt
*stmt
)
4226 struct pet_scop
*scop_then
, *scop_else
= NULL
, *scop
;
4232 scop
= extract_conditional_assignment(stmt
);
4236 cond
= try_extract_nested_condition(stmt
->getCond());
4237 if (allow_nested
&& (!cond
|| has_nested(cond
)))
4241 assigned_value_cache
cache(assigned_value
);
4242 scop_then
= extract(stmt
->getThen());
4245 if (stmt
->getElse()) {
4246 assigned_value_cache
cache(assigned_value
);
4247 scop_else
= extract(stmt
->getElse());
4248 if (options
->autodetect
) {
4249 if (scop_then
&& !scop_else
) {
4251 isl_pw_aff_free(cond
);
4254 if (!scop_then
&& scop_else
) {
4256 isl_pw_aff_free(cond
);
4263 (!is_nested_allowed(cond
, scop_then
) ||
4264 (stmt
->getElse() && !is_nested_allowed(cond
, scop_else
)))) {
4265 isl_pw_aff_free(cond
);
4268 if (allow_nested
&& !cond
)
4269 return extract_non_affine_if(stmt
->getCond(), scop_then
,
4270 scop_else
, stmt
->getElse(), stmt_id
);
4273 cond
= extract_condition(stmt
->getCond());
4275 pet_skip_info_if
skip(ctx
, scop_then
, scop_else
, stmt
->getElse(), true);
4276 skip
.extract(this, cond
);
4278 valid
= isl_pw_aff_domain(isl_pw_aff_copy(cond
));
4279 set
= isl_pw_aff_non_zero_set(cond
);
4280 scop
= pet_scop_restrict(scop_then
, isl_set_copy(set
));
4282 if (stmt
->getElse()) {
4283 set
= isl_set_subtract(isl_set_copy(valid
), set
);
4284 scop_else
= pet_scop_restrict(scop_else
, set
);
4285 scop
= pet_scop_add_par(ctx
, scop
, scop_else
);
4288 scop
= resolve_nested(scop
);
4289 scop
= pet_scop_restrict_context(scop
, valid
);
4292 scop
= pet_scop_prefix(scop
, 0);
4293 scop
= skip
.add(scop
, 1);
4298 /* Try and construct a pet_scop for a label statement.
4299 * We currently only allow labels on expression statements.
4301 struct pet_scop
*PetScan::extract(LabelStmt
*stmt
)
4306 sub
= stmt
->getSubStmt();
4307 if (!isa
<Expr
>(sub
)) {
4312 label
= isl_id_alloc(ctx
, stmt
->getName(), NULL
);
4314 return extract(sub
, extract_expr(cast
<Expr
>(sub
)), label
);
4317 /* Construct a pet_scop for a continue statement.
4319 * We simply create an empty scop with a universal pet_skip_now
4320 * skip condition. This skip condition will then be taken into
4321 * account by the enclosing loop construct, possibly after
4322 * being incorporated into outer skip conditions.
4324 struct pet_scop
*PetScan::extract(ContinueStmt
*stmt
)
4330 scop
= pet_scop_empty(ctx
);
4334 space
= isl_space_set_alloc(ctx
, 0, 1);
4335 set
= isl_set_universe(space
);
4336 set
= isl_set_fix_si(set
, isl_dim_set
, 0, 1);
4337 scop
= pet_scop_set_skip(scop
, pet_skip_now
, set
);
4342 /* Construct a pet_scop for a break statement.
4344 * We simply create an empty scop with both a universal pet_skip_now
4345 * skip condition and a universal pet_skip_later skip condition.
4346 * These skip conditions will then be taken into
4347 * account by the enclosing loop construct, possibly after
4348 * being incorporated into outer skip conditions.
4350 struct pet_scop
*PetScan::extract(BreakStmt
*stmt
)
4356 scop
= pet_scop_empty(ctx
);
4360 space
= isl_space_set_alloc(ctx
, 0, 1);
4361 set
= isl_set_universe(space
);
4362 set
= isl_set_fix_si(set
, isl_dim_set
, 0, 1);
4363 scop
= pet_scop_set_skip(scop
, pet_skip_now
, isl_set_copy(set
));
4364 scop
= pet_scop_set_skip(scop
, pet_skip_later
, set
);
4369 /* Try and construct a pet_scop corresponding to "stmt".
4371 * If "stmt" is a compound statement, then "skip_declarations"
4372 * indicates whether we should skip initial declarations in the
4373 * compound statement.
4375 * If the constructed pet_scop is not a (possibly) partial representation
4376 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4377 * In particular, if skip_declarations, then we may have skipped declarations
4378 * inside "stmt" and so the pet_scop may not represent the entire "stmt".
4379 * Note that this function may be called with "stmt" referring to the entire
4380 * body of the function, including the outer braces. In such cases,
4381 * skip_declarations will be set and the braces will not be taken into
4382 * account in scop->start and scop->end.
4384 struct pet_scop
*PetScan::extract(Stmt
*stmt
, bool skip_declarations
)
4386 struct pet_scop
*scop
;
4387 unsigned start
, end
;
4389 SourceManager
&SM
= PP
.getSourceManager();
4390 const LangOptions
&LO
= PP
.getLangOpts();
4392 if (isa
<Expr
>(stmt
))
4393 return extract(stmt
, extract_expr(cast
<Expr
>(stmt
)));
4395 switch (stmt
->getStmtClass()) {
4396 case Stmt::WhileStmtClass
:
4397 scop
= extract(cast
<WhileStmt
>(stmt
));
4399 case Stmt::ForStmtClass
:
4400 scop
= extract_for(cast
<ForStmt
>(stmt
));
4402 case Stmt::IfStmtClass
:
4403 scop
= extract(cast
<IfStmt
>(stmt
));
4405 case Stmt::CompoundStmtClass
:
4406 scop
= extract(cast
<CompoundStmt
>(stmt
), skip_declarations
);
4408 case Stmt::LabelStmtClass
:
4409 scop
= extract(cast
<LabelStmt
>(stmt
));
4411 case Stmt::ContinueStmtClass
:
4412 scop
= extract(cast
<ContinueStmt
>(stmt
));
4414 case Stmt::BreakStmtClass
:
4415 scop
= extract(cast
<BreakStmt
>(stmt
));
4417 case Stmt::DeclStmtClass
:
4418 scop
= extract(cast
<DeclStmt
>(stmt
));
4425 if (partial
|| skip_declarations
)
4428 loc
= stmt
->getLocStart();
4429 loc
= move_to_start_of_line_if_first_token(loc
, SM
, LO
);
4430 start
= getExpansionOffset(SM
, loc
);
4431 loc
= PP
.getLocForEndOfToken(stmt
->getLocEnd());
4432 end
= getExpansionOffset(SM
, loc
);
4433 scop
= pet_scop_update_start_end(scop
, start
, end
);
4438 /* Do we need to construct a skip condition of the given type
4439 * on a sequence of statements?
4441 * There is no need to construct a new skip condition if only
4442 * only of the two statements has a skip condition or if both
4443 * of their skip conditions are affine.
4445 * In principle we also don't need a new continuation variable if
4446 * the continuation of scop2 is affine, but then we would need
4447 * to allow more complicated forms of continuations.
4449 static bool need_skip_seq(struct pet_scop
*scop1
, struct pet_scop
*scop2
,
4452 if (!scop1
|| !pet_scop_has_skip(scop1
, type
))
4454 if (!scop2
|| !pet_scop_has_skip(scop2
, type
))
4456 if (pet_scop_has_affine_skip(scop1
, type
) &&
4457 pet_scop_has_affine_skip(scop2
, type
))
4462 /* Construct a scop for computing the skip condition of the given type and
4463 * with access relation "skip_access" for a sequence of two scops "scop1"
4466 * The computed scop contains a single statement that essentially does
4468 * skip_cond = skip_cond_1 ? 1 : skip_cond_2
4470 * or, in other words, skip_cond1 || skip_cond2.
4471 * In this expression, skip_cond_2 is filtered to reflect that it is
4472 * only evaluated when skip_cond_1 is false.
4474 * The skip condition on scop1 is not removed because it still needs
4475 * to be applied to scop2 when these two scops are combined.
4477 static struct pet_scop
*extract_skip_seq(PetScan
*ps
,
4478 __isl_take isl_map
*skip_access
,
4479 struct pet_scop
*scop1
, struct pet_scop
*scop2
, enum pet_skip type
)
4482 struct pet_expr
*expr1
, *expr2
, *expr
, *expr_skip
;
4483 struct pet_stmt
*stmt
;
4484 struct pet_scop
*scop
;
4485 isl_ctx
*ctx
= ps
->ctx
;
4487 if (!scop1
|| !scop2
)
4490 expr1
= pet_scop_get_skip_expr(scop1
, type
);
4491 expr2
= pet_scop_get_skip_expr(scop2
, type
);
4492 pet_scop_reset_skip(scop2
, type
);
4494 expr2
= pet_expr_filter(expr2
, isl_map_copy(expr1
->acc
.access
), 0);
4496 expr
= universally_true(ctx
);
4497 expr
= pet_expr_new_ternary(ctx
, expr1
, expr
, expr2
);
4498 expr_skip
= pet_expr_from_access(isl_map_copy(skip_access
));
4500 expr_skip
->acc
.write
= 1;
4501 expr_skip
->acc
.read
= 0;
4503 expr
= pet_expr_new_binary(ctx
, pet_op_assign
, expr_skip
, expr
);
4504 stmt
= pet_stmt_from_pet_expr(ctx
, -1, NULL
, ps
->n_stmt
++, expr
);
4506 scop
= pet_scop_from_pet_stmt(ctx
, stmt
);
4507 scop
= scop_add_array(scop
, skip_access
, ps
->ast_context
);
4508 isl_map_free(skip_access
);
4512 isl_map_free(skip_access
);
4516 /* Structure that handles the construction of skip conditions
4517 * on sequences of statements.
4519 * scop1 and scop2 represent the two statements that are combined
4521 struct pet_skip_info_seq
: public pet_skip_info
{
4522 struct pet_scop
*scop1
, *scop2
;
4524 pet_skip_info_seq(isl_ctx
*ctx
, struct pet_scop
*scop1
,
4525 struct pet_scop
*scop2
);
4526 void extract(PetScan
*scan
, enum pet_skip type
);
4527 void extract(PetScan
*scan
);
4528 struct pet_scop
*add(struct pet_scop
*scop
, enum pet_skip type
,
4530 struct pet_scop
*add(struct pet_scop
*scop
, int offset
);
4533 /* Initialize a pet_skip_info_seq structure based on
4534 * on the two statements that are going to be combined.
4536 pet_skip_info_seq::pet_skip_info_seq(isl_ctx
*ctx
, struct pet_scop
*scop1
,
4537 struct pet_scop
*scop2
) : pet_skip_info(ctx
), scop1(scop1
), scop2(scop2
)
4539 skip
[pet_skip_now
] = need_skip_seq(scop1
, scop2
, pet_skip_now
);
4540 equal
= skip
[pet_skip_now
] && skip_equals_skip_later(scop1
) &&
4541 skip_equals_skip_later(scop2
);
4542 skip
[pet_skip_later
] = skip
[pet_skip_now
] && !equal
&&
4543 need_skip_seq(scop1
, scop2
, pet_skip_later
);
4546 /* If we need to construct a skip condition of the given type,
4549 void pet_skip_info_seq::extract(PetScan
*scan
, enum pet_skip type
)
4554 access
[type
] = create_test_access(ctx
, scan
->n_test
++);
4555 scop
[type
] = extract_skip_seq(scan
, isl_map_copy(access
[type
]),
4556 scop1
, scop2
, type
);
4559 /* Construct the required skip conditions.
4561 void pet_skip_info_seq::extract(PetScan
*scan
)
4563 extract(scan
, pet_skip_now
);
4564 extract(scan
, pet_skip_later
);
4566 drop_skip_later(scop1
, scop2
);
4569 /* Add the computed skip condition of the given type to "main" and
4570 * add the scop for computing the condition at the given offset (the statement
4571 * number). Within this offset, the condition is computed at position 1
4572 * to ensure that it is computed after the corresponding statement.
4574 * If equal is set, then we only computed a skip condition for pet_skip_now,
4575 * but we also need to set it as main's pet_skip_later.
4577 struct pet_scop
*pet_skip_info_seq::add(struct pet_scop
*main
,
4578 enum pet_skip type
, int offset
)
4585 skip_set
= isl_map_range(access
[type
]);
4586 access
[type
] = NULL
;
4587 scop
[type
] = pet_scop_prefix(scop
[type
], 1);
4588 scop
[type
] = pet_scop_prefix(scop
[type
], offset
);
4589 main
= pet_scop_add_par(ctx
, main
, scop
[type
]);
4593 main
= pet_scop_set_skip(main
, pet_skip_later
,
4594 isl_set_copy(skip_set
));
4596 main
= pet_scop_set_skip(main
, type
, skip_set
);
4601 /* Add the computed skip conditions to "main" and
4602 * add the scops for computing the conditions at the given offset.
4604 struct pet_scop
*pet_skip_info_seq::add(struct pet_scop
*scop
, int offset
)
4606 scop
= add(scop
, pet_skip_now
, offset
);
4607 scop
= add(scop
, pet_skip_later
, offset
);
4612 /* Extract a clone of the kill statement in "scop".
4613 * "scop" is expected to have been created from a DeclStmt
4614 * and should have the kill as its first statement.
4616 struct pet_stmt
*PetScan::extract_kill(struct pet_scop
*scop
)
4618 struct pet_expr
*kill
;
4619 struct pet_stmt
*stmt
;
4624 if (scop
->n_stmt
< 1)
4625 isl_die(ctx
, isl_error_internal
,
4626 "expecting at least one statement", return NULL
);
4627 stmt
= scop
->stmts
[0];
4628 if (stmt
->body
->type
!= pet_expr_unary
||
4629 stmt
->body
->op
!= pet_op_kill
)
4630 isl_die(ctx
, isl_error_internal
,
4631 "expecting kill statement", return NULL
);
4633 access
= isl_map_copy(stmt
->body
->args
[0]->acc
.access
);
4634 access
= isl_map_reset_tuple_id(access
, isl_dim_in
);
4635 kill
= pet_expr_kill_from_access(access
);
4636 return pet_stmt_from_pet_expr(ctx
, stmt
->line
, NULL
, n_stmt
++, kill
);
4639 /* Mark all arrays in "scop" as being exposed.
4641 static struct pet_scop
*mark_exposed(struct pet_scop
*scop
)
4645 for (int i
= 0; i
< scop
->n_array
; ++i
)
4646 scop
->arrays
[i
]->exposed
= 1;
4650 /* Try and construct a pet_scop corresponding to (part of)
4651 * a sequence of statements.
4653 * "block" is set if the sequence respresents the children of
4654 * a compound statement.
4655 * "skip_declarations" is set if we should skip initial declarations
4656 * in the sequence of statements.
4658 * If there are any breaks or continues in the individual statements,
4659 * then we may have to compute a new skip condition.
4660 * This is handled using a pet_skip_info_seq object.
4661 * On initialization, the object checks if skip conditions need
4662 * to be computed. If so, it does so in "extract" and adds them in "add".
4664 * If "block" is set, then we need to insert kill statements at
4665 * the end of the block for any array that has been declared by
4666 * one of the statements in the sequence. Each of these declarations
4667 * results in the construction of a kill statement at the place
4668 * of the declaration, so we simply collect duplicates of
4669 * those kill statements and append these duplicates to the constructed scop.
4671 * If "block" is not set, then any array declared by one of the statements
4672 * in the sequence is marked as being exposed.
4674 struct pet_scop
*PetScan::extract(StmtRange stmt_range
, bool block
,
4675 bool skip_declarations
)
4680 bool partial_range
= false;
4681 set
<struct pet_stmt
*> kills
;
4682 set
<struct pet_stmt
*>::iterator it
;
4684 scop
= pet_scop_empty(ctx
);
4685 for (i
= stmt_range
.first
, j
= 0; i
!= stmt_range
.second
; ++i
, ++j
) {
4687 struct pet_scop
*scop_i
;
4689 if (skip_declarations
&&
4690 child
->getStmtClass() == Stmt::DeclStmtClass
)
4693 scop_i
= extract(child
);
4694 if (scop
&& partial
) {
4695 pet_scop_free(scop_i
);
4698 pet_skip_info_seq
skip(ctx
, scop
, scop_i
);
4701 scop_i
= pet_scop_prefix(scop_i
, 0);
4702 if (scop_i
&& child
->getStmtClass() == Stmt::DeclStmtClass
) {
4704 kills
.insert(extract_kill(scop_i
));
4706 scop_i
= mark_exposed(scop_i
);
4708 scop_i
= pet_scop_prefix(scop_i
, j
);
4709 if (options
->autodetect
) {
4711 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4713 partial_range
= true;
4714 if (scop
->n_stmt
!= 0 && !scop_i
)
4717 scop
= pet_scop_add_seq(ctx
, scop
, scop_i
);
4720 scop
= skip
.add(scop
, j
);
4726 for (it
= kills
.begin(); it
!= kills
.end(); ++it
) {
4728 scop_j
= pet_scop_from_pet_stmt(ctx
, *it
);
4729 scop_j
= pet_scop_prefix(scop_j
, j
);
4730 scop
= pet_scop_add_seq(ctx
, scop
, scop_j
);
4733 if (scop
&& partial_range
)
4739 /* Check if the scop marked by the user is exactly this Stmt
4740 * or part of this Stmt.
4741 * If so, return a pet_scop corresponding to the marked region.
4742 * Otherwise, return NULL.
4744 struct pet_scop
*PetScan::scan(Stmt
*stmt
)
4746 SourceManager
&SM
= PP
.getSourceManager();
4747 unsigned start_off
, end_off
;
4749 start_off
= getExpansionOffset(SM
, stmt
->getLocStart());
4750 end_off
= getExpansionOffset(SM
, stmt
->getLocEnd());
4752 if (start_off
> loc
.end
)
4754 if (end_off
< loc
.start
)
4756 if (start_off
>= loc
.start
&& end_off
<= loc
.end
) {
4757 return extract(stmt
);
4761 for (start
= stmt
->child_begin(); start
!= stmt
->child_end(); ++start
) {
4762 Stmt
*child
= *start
;
4765 start_off
= getExpansionOffset(SM
, child
->getLocStart());
4766 end_off
= getExpansionOffset(SM
, child
->getLocEnd());
4767 if (start_off
< loc
.start
&& end_off
> loc
.end
)
4769 if (start_off
>= loc
.start
)
4774 for (end
= start
; end
!= stmt
->child_end(); ++end
) {
4776 start_off
= SM
.getFileOffset(child
->getLocStart());
4777 if (start_off
>= loc
.end
)
4781 return extract(StmtRange(start
, end
), false, false);
4784 /* Set the size of index "pos" of "array" to "size".
4785 * In particular, add a constraint of the form
4789 * to array->extent and a constraint of the form
4793 * to array->context.
4795 static struct pet_array
*update_size(struct pet_array
*array
, int pos
,
4796 __isl_take isl_pw_aff
*size
)
4806 valid
= isl_pw_aff_nonneg_set(isl_pw_aff_copy(size
));
4807 array
->context
= isl_set_intersect(array
->context
, valid
);
4809 dim
= isl_set_get_space(array
->extent
);
4810 aff
= isl_aff_zero_on_domain(isl_local_space_from_space(dim
));
4811 aff
= isl_aff_add_coefficient_si(aff
, isl_dim_in
, pos
, 1);
4812 univ
= isl_set_universe(isl_aff_get_domain_space(aff
));
4813 index
= isl_pw_aff_alloc(univ
, aff
);
4815 size
= isl_pw_aff_add_dims(size
, isl_dim_in
,
4816 isl_set_dim(array
->extent
, isl_dim_set
));
4817 id
= isl_set_get_tuple_id(array
->extent
);
4818 size
= isl_pw_aff_set_tuple_id(size
, isl_dim_in
, id
);
4819 bound
= isl_pw_aff_lt_set(index
, size
);
4821 array
->extent
= isl_set_intersect(array
->extent
, bound
);
4823 if (!array
->context
|| !array
->extent
)
4828 pet_array_free(array
);
4832 /* Figure out the size of the array at position "pos" and all
4833 * subsequent positions from "type" and update "array" accordingly.
4835 struct pet_array
*PetScan::set_upper_bounds(struct pet_array
*array
,
4836 const Type
*type
, int pos
)
4838 const ArrayType
*atype
;
4844 if (type
->isPointerType()) {
4845 type
= type
->getPointeeType().getTypePtr();
4846 return set_upper_bounds(array
, type
, pos
+ 1);
4848 if (!type
->isArrayType())
4851 type
= type
->getCanonicalTypeInternal().getTypePtr();
4852 atype
= cast
<ArrayType
>(type
);
4854 if (type
->isConstantArrayType()) {
4855 const ConstantArrayType
*ca
= cast
<ConstantArrayType
>(atype
);
4856 size
= extract_affine(ca
->getSize());
4857 array
= update_size(array
, pos
, size
);
4858 } else if (type
->isVariableArrayType()) {
4859 const VariableArrayType
*vla
= cast
<VariableArrayType
>(atype
);
4860 size
= extract_affine(vla
->getSizeExpr());
4861 array
= update_size(array
, pos
, size
);
4864 type
= atype
->getElementType().getTypePtr();
4866 return set_upper_bounds(array
, type
, pos
+ 1);
4869 /* Is "T" the type of a variable length array with static size?
4871 static bool is_vla_with_static_size(QualType T
)
4873 const VariableArrayType
*vlatype
;
4875 if (!T
->isVariableArrayType())
4877 vlatype
= cast
<VariableArrayType
>(T
);
4878 return vlatype
->getSizeModifier() == VariableArrayType::Static
;
4881 /* Return the type of "decl" as an array.
4883 * In particular, if "decl" is a parameter declaration that
4884 * is a variable length array with a static size, then
4885 * return the original type (i.e., the variable length array).
4886 * Otherwise, return the type of decl.
4888 static QualType
get_array_type(ValueDecl
*decl
)
4893 parm
= dyn_cast
<ParmVarDecl
>(decl
);
4895 return decl
->getType();
4897 T
= parm
->getOriginalType();
4898 if (!is_vla_with_static_size(T
))
4899 return decl
->getType();
4903 /* Construct and return a pet_array corresponding to the variable "decl".
4904 * In particular, initialize array->extent to
4906 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4908 * and then call set_upper_bounds to set the upper bounds on the indices
4909 * based on the type of the variable.
4911 struct pet_array
*PetScan::extract_array(isl_ctx
*ctx
, ValueDecl
*decl
)
4913 struct pet_array
*array
;
4914 QualType qt
= get_array_type(decl
);
4915 const Type
*type
= qt
.getTypePtr();
4916 int depth
= array_depth(type
);
4917 QualType base
= base_type(qt
);
4922 array
= isl_calloc_type(ctx
, struct pet_array
);
4926 id
= isl_id_alloc(ctx
, decl
->getName().str().c_str(), decl
);
4927 dim
= isl_space_set_alloc(ctx
, 0, depth
);
4928 dim
= isl_space_set_tuple_id(dim
, isl_dim_set
, id
);
4930 array
->extent
= isl_set_nat_universe(dim
);
4932 dim
= isl_space_params_alloc(ctx
, 0);
4933 array
->context
= isl_set_universe(dim
);
4935 array
= set_upper_bounds(array
, type
, 0);
4939 name
= base
.getAsString();
4940 array
->element_type
= strdup(name
.c_str());
4941 array
->element_size
= decl
->getASTContext().getTypeInfo(base
).first
/ 8;
4946 /* Construct a list of pet_arrays, one for each array (or scalar)
4947 * accessed inside "scop", add this list to "scop" and return the result.
4949 * The context of "scop" is updated with the intersection of
4950 * the contexts of all arrays, i.e., constraints on the parameters
4951 * that ensure that the arrays have a valid (non-negative) size.
4953 struct pet_scop
*PetScan::scan_arrays(struct pet_scop
*scop
)
4956 set
<ValueDecl
*> arrays
;
4957 set
<ValueDecl
*>::iterator it
;
4959 struct pet_array
**scop_arrays
;
4964 pet_scop_collect_arrays(scop
, arrays
);
4965 if (arrays
.size() == 0)
4968 n_array
= scop
->n_array
;
4970 scop_arrays
= isl_realloc_array(ctx
, scop
->arrays
, struct pet_array
*,
4971 n_array
+ arrays
.size());
4974 scop
->arrays
= scop_arrays
;
4976 for (it
= arrays
.begin(), i
= 0; it
!= arrays
.end(); ++it
, ++i
) {
4977 struct pet_array
*array
;
4978 scop
->arrays
[n_array
+ i
] = array
= extract_array(ctx
, *it
);
4979 if (!scop
->arrays
[n_array
+ i
])
4982 scop
->context
= isl_set_intersect(scop
->context
,
4983 isl_set_copy(array
->context
));
4990 pet_scop_free(scop
);
4994 /* Bound all parameters in scop->context to the possible values
4995 * of the corresponding C variable.
4997 static struct pet_scop
*add_parameter_bounds(struct pet_scop
*scop
)
5004 n
= isl_set_dim(scop
->context
, isl_dim_param
);
5005 for (int i
= 0; i
< n
; ++i
) {
5009 id
= isl_set_get_dim_id(scop
->context
, isl_dim_param
, i
);
5010 if (is_nested_parameter(id
)) {
5012 isl_die(isl_set_get_ctx(scop
->context
),
5014 "unresolved nested parameter", goto error
);
5016 decl
= (ValueDecl
*) isl_id_get_user(id
);
5019 scop
->context
= set_parameter_bounds(scop
->context
, i
, decl
);
5027 pet_scop_free(scop
);
5031 /* Construct a pet_scop from the given function.
5033 * If the scop was delimited by scop and endscop pragmas, then we override
5034 * the file offsets by those derived from the pragmas.
5036 struct pet_scop
*PetScan::scan(FunctionDecl
*fd
)
5041 stmt
= fd
->getBody();
5043 if (options
->autodetect
)
5044 scop
= extract(stmt
, true);
5047 scop
= pet_scop_update_start_end(scop
, loc
.start
, loc
.end
);
5049 scop
= pet_scop_detect_parameter_accesses(scop
);
5050 scop
= scan_arrays(scop
);
5051 scop
= add_parameter_bounds(scop
);
5052 scop
= pet_scop_gist(scop
, value_bounds
);