extract out PetScan::assign
[pet.git] / scan.cc
blob3935b039442c80f8c9de01e56cce57066dfaa7bf
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012 Ecole Normale Superieure. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
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
32 * Leiden University.
33 */
35 #include <set>
36 #include <map>
37 #include <iostream>
38 #include <clang/AST/ASTContext.h>
39 #include <clang/AST/ASTDiagnostic.h>
40 #include <clang/AST/Expr.h>
41 #include <clang/AST/RecursiveASTVisitor.h>
43 #include <isl/id.h>
44 #include <isl/space.h>
45 #include <isl/aff.h>
46 #include <isl/set.h>
48 #include "options.h"
49 #include "scan.h"
50 #include "scop.h"
51 #include "scop_plus.h"
53 #include "config.h"
55 using namespace std;
56 using namespace clang;
58 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
59 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
61 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
62 SourceLocation(), var, false, var->getInnerLocStart(),
63 var->getType(), VK_LValue);
65 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
66 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
68 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
69 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
70 VK_LValue);
72 #else
73 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
75 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
76 var, var->getInnerLocStart(), var->getType(), VK_LValue);
78 #endif
80 /* Check if the element type corresponding to the given array type
81 * has a const qualifier.
83 static bool const_base(QualType qt)
85 const Type *type = qt.getTypePtr();
87 if (type->isPointerType())
88 return const_base(type->getPointeeType());
89 if (type->isArrayType()) {
90 const ArrayType *atype;
91 type = type->getCanonicalTypeInternal().getTypePtr();
92 atype = cast<ArrayType>(type);
93 return const_base(atype->getElementType());
96 return qt.isConstQualified();
99 /* Mark "decl" as having an unknown value in "assigned_value".
101 * If no (known or unknown) value was assigned to "decl" before,
102 * then it may have been treated as a parameter before and may
103 * therefore appear in a value assigned to another variable.
104 * If so, this assignment needs to be turned into an unknown value too.
106 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
107 ValueDecl *decl)
109 map<ValueDecl *, isl_pw_aff *>::iterator it;
111 it = assigned_value.find(decl);
113 assigned_value[decl] = NULL;
115 if (it == assigned_value.end())
116 return;
118 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
119 isl_pw_aff *pa = it->second;
120 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
122 for (int i = 0; i < nparam; ++i) {
123 isl_id *id;
125 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
126 continue;
127 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
128 if (isl_id_get_user(id) == decl)
129 it->second = NULL;
130 isl_id_free(id);
135 /* Look for any assignments to scalar variables in part of the parse
136 * tree and set assigned_value to NULL for each of them.
137 * Also reset assigned_value if the address of a scalar variable
138 * is being taken. As an exception, if the address is passed to a function
139 * that is declared to receive a const pointer, then assigned_value is
140 * not reset.
142 * This ensures that we won't use any previously stored value
143 * in the current subtree and its parents.
145 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
146 map<ValueDecl *, isl_pw_aff *> &assigned_value;
147 set<UnaryOperator *> skip;
149 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
150 assigned_value(assigned_value) {}
152 /* Check for "address of" operators whose value is passed
153 * to a const pointer argument and add them to "skip", so that
154 * we can skip them in VisitUnaryOperator.
156 bool VisitCallExpr(CallExpr *expr) {
157 FunctionDecl *fd;
158 fd = expr->getDirectCallee();
159 if (!fd)
160 return true;
161 for (int i = 0; i < expr->getNumArgs(); ++i) {
162 Expr *arg = expr->getArg(i);
163 UnaryOperator *op;
164 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
165 ImplicitCastExpr *ice;
166 ice = cast<ImplicitCastExpr>(arg);
167 arg = ice->getSubExpr();
169 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
170 continue;
171 op = cast<UnaryOperator>(arg);
172 if (op->getOpcode() != UO_AddrOf)
173 continue;
174 if (const_base(fd->getParamDecl(i)->getType()))
175 skip.insert(op);
177 return true;
180 bool VisitUnaryOperator(UnaryOperator *expr) {
181 Expr *arg;
182 DeclRefExpr *ref;
183 ValueDecl *decl;
185 switch (expr->getOpcode()) {
186 case UO_AddrOf:
187 case UO_PostInc:
188 case UO_PostDec:
189 case UO_PreInc:
190 case UO_PreDec:
191 break;
192 default:
193 return true;
195 if (skip.find(expr) != skip.end())
196 return true;
198 arg = expr->getSubExpr();
199 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
200 return true;
201 ref = cast<DeclRefExpr>(arg);
202 decl = ref->getDecl();
203 clear_assignment(assigned_value, decl);
204 return true;
207 bool VisitBinaryOperator(BinaryOperator *expr) {
208 Expr *lhs;
209 DeclRefExpr *ref;
210 ValueDecl *decl;
212 if (!expr->isAssignmentOp())
213 return true;
214 lhs = expr->getLHS();
215 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
216 return true;
217 ref = cast<DeclRefExpr>(lhs);
218 decl = ref->getDecl();
219 clear_assignment(assigned_value, decl);
220 return true;
224 /* Keep a copy of the currently assigned values.
226 * Any variable that is assigned a value inside the current scope
227 * is removed again when we leave the scope (either because it wasn't
228 * stored in the cache or because it has a different value in the cache).
230 struct assigned_value_cache {
231 map<ValueDecl *, isl_pw_aff *> &assigned_value;
232 map<ValueDecl *, isl_pw_aff *> cache;
234 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
235 assigned_value(assigned_value), cache(assigned_value) {}
236 ~assigned_value_cache() {
237 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
238 for (it = assigned_value.begin(); it != assigned_value.end();
239 ++it) {
240 if (!it->second ||
241 (cache.find(it->first) != cache.end() &&
242 cache[it->first] != it->second))
243 cache[it->first] = NULL;
245 assigned_value = cache;
249 /* Insert an expression into the collection of expressions,
250 * provided it is not already in there.
251 * The isl_pw_affs are freed in the destructor.
253 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
255 std::set<isl_pw_aff *>::iterator it;
257 if (expressions.find(expr) == expressions.end())
258 expressions.insert(expr);
259 else
260 isl_pw_aff_free(expr);
263 PetScan::~PetScan()
265 std::set<isl_pw_aff *>::iterator it;
267 for (it = expressions.begin(); it != expressions.end(); ++it)
268 isl_pw_aff_free(*it);
270 isl_union_map_free(value_bounds);
273 /* Called if we found something we (currently) cannot handle.
274 * We'll provide more informative warnings later.
276 * We only actually complain if autodetect is false.
278 void PetScan::unsupported(Stmt *stmt, const char *msg)
280 if (options->autodetect)
281 return;
283 SourceLocation loc = stmt->getLocStart();
284 DiagnosticsEngine &diag = PP.getDiagnostics();
285 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
286 msg ? msg : "unsupported");
287 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
290 /* Extract an integer from "expr" and store it in "v".
292 int PetScan::extract_int(IntegerLiteral *expr, isl_int *v)
294 const Type *type = expr->getType().getTypePtr();
295 int is_signed = type->hasSignedIntegerRepresentation();
297 if (is_signed) {
298 int64_t i = expr->getValue().getSExtValue();
299 isl_int_set_si(*v, i);
300 } else {
301 uint64_t i = expr->getValue().getZExtValue();
302 isl_int_set_ui(*v, i);
305 return 0;
308 /* Extract an integer from "expr" and store it in "v".
309 * Return -1 if "expr" does not (obviously) represent an integer.
311 int PetScan::extract_int(clang::ParenExpr *expr, isl_int *v)
313 return extract_int(expr->getSubExpr(), v);
316 /* Extract an integer from "expr" and store it in "v".
317 * Return -1 if "expr" does not (obviously) represent an integer.
319 int PetScan::extract_int(clang::Expr *expr, isl_int *v)
321 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
322 return extract_int(cast<IntegerLiteral>(expr), v);
323 if (expr->getStmtClass() == Stmt::ParenExprClass)
324 return extract_int(cast<ParenExpr>(expr), v);
326 unsupported(expr);
327 return -1;
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);
338 isl_int v;
340 isl_int_init(v);
341 extract_int(expr, &v);
342 aff = isl_aff_add_constant(aff, v);
343 isl_int_clear(v);
345 return isl_pw_aff_alloc(dom, aff);
348 /* Extract an affine expression from the APInt "val".
350 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
352 isl_space *dim = isl_space_params_alloc(ctx, 0);
353 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
354 isl_aff *aff = isl_aff_zero_on_domain(ls);
355 isl_set *dom = isl_set_universe(dim);
356 isl_int v;
358 isl_int_init(v);
359 isl_int_set_ui(v, val.getZExtValue());
360 aff = isl_aff_add_constant(aff, v);
361 isl_int_clear(v);
363 return isl_pw_aff_alloc(dom, aff);
366 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
368 return extract_affine(expr->getSubExpr());
371 static unsigned get_type_size(ValueDecl *decl)
373 return decl->getASTContext().getIntWidth(decl->getType());
376 /* Bound parameter "pos" of "set" to the possible values of "decl".
378 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
379 unsigned pos, ValueDecl *decl)
381 unsigned width;
382 isl_int v;
384 isl_int_init(v);
386 width = get_type_size(decl);
387 if (decl->getType()->isUnsignedIntegerType()) {
388 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
389 isl_int_set_si(v, 1);
390 isl_int_mul_2exp(v, v, width);
391 isl_int_sub_ui(v, v, 1);
392 set = isl_set_upper_bound(set, isl_dim_param, pos, v);
393 } else {
394 isl_int_set_si(v, 1);
395 isl_int_mul_2exp(v, v, width - 1);
396 isl_int_sub_ui(v, v, 1);
397 set = isl_set_upper_bound(set, isl_dim_param, pos, v);
398 isl_int_neg(v, v);
399 isl_int_sub_ui(v, v, 1);
400 set = isl_set_lower_bound(set, isl_dim_param, pos, v);
403 isl_int_clear(v);
405 return set;
408 /* Extract an affine expression from the DeclRefExpr "expr".
410 * If the variable has been assigned a value, then we check whether
411 * we know what (affine) value was assigned.
412 * If so, we return this value. Otherwise we convert "expr"
413 * to an extra parameter (provided nesting_enabled is set).
415 * Otherwise, we simply return an expression that is equal
416 * to a parameter corresponding to the referenced variable.
418 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
420 ValueDecl *decl = expr->getDecl();
421 const Type *type = decl->getType().getTypePtr();
422 isl_id *id;
423 isl_space *dim;
424 isl_aff *aff;
425 isl_set *dom;
427 if (!type->isIntegerType()) {
428 unsupported(expr);
429 return NULL;
432 if (assigned_value.find(decl) != assigned_value.end()) {
433 if (assigned_value[decl])
434 return isl_pw_aff_copy(assigned_value[decl]);
435 else
436 return nested_access(expr);
439 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
440 dim = isl_space_params_alloc(ctx, 1);
442 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
444 dom = isl_set_universe(isl_space_copy(dim));
445 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
446 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
448 return isl_pw_aff_alloc(dom, aff);
451 /* Extract an affine expression from an integer division operation.
452 * In particular, if "expr" is lhs/rhs, then return
454 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
456 * The second argument (rhs) is required to be a (positive) integer constant.
458 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
460 int is_cst;
461 isl_pw_aff *rhs, *lhs;
463 rhs = extract_affine(expr->getRHS());
464 is_cst = isl_pw_aff_is_cst(rhs);
465 if (is_cst < 0 || !is_cst) {
466 isl_pw_aff_free(rhs);
467 if (!is_cst)
468 unsupported(expr);
469 return NULL;
472 lhs = extract_affine(expr->getLHS());
474 return isl_pw_aff_tdiv_q(lhs, rhs);
477 /* Extract an affine expression from a modulo operation.
478 * In particular, if "expr" is lhs/rhs, then return
480 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
482 * The second argument (rhs) is required to be a (positive) integer constant.
484 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
486 int is_cst;
487 isl_pw_aff *rhs, *lhs;
489 rhs = extract_affine(expr->getRHS());
490 is_cst = isl_pw_aff_is_cst(rhs);
491 if (is_cst < 0 || !is_cst) {
492 isl_pw_aff_free(rhs);
493 if (!is_cst)
494 unsupported(expr);
495 return NULL;
498 lhs = extract_affine(expr->getLHS());
500 return isl_pw_aff_tdiv_r(lhs, rhs);
503 /* Extract an affine expression from a multiplication operation.
504 * This is only allowed if at least one of the two arguments
505 * is a (piecewise) constant.
507 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
509 isl_pw_aff *lhs;
510 isl_pw_aff *rhs;
512 lhs = extract_affine(expr->getLHS());
513 rhs = extract_affine(expr->getRHS());
515 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
516 isl_pw_aff_free(lhs);
517 isl_pw_aff_free(rhs);
518 unsupported(expr);
519 return NULL;
522 return isl_pw_aff_mul(lhs, rhs);
525 /* Extract an affine expression from an addition or subtraction operation.
527 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
529 isl_pw_aff *lhs;
530 isl_pw_aff *rhs;
532 lhs = extract_affine(expr->getLHS());
533 rhs = extract_affine(expr->getRHS());
535 switch (expr->getOpcode()) {
536 case BO_Add:
537 return isl_pw_aff_add(lhs, rhs);
538 case BO_Sub:
539 return isl_pw_aff_sub(lhs, rhs);
540 default:
541 isl_pw_aff_free(lhs);
542 isl_pw_aff_free(rhs);
543 return NULL;
548 /* Compute
550 * pwaff mod 2^width
552 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
553 unsigned width)
555 isl_int mod;
557 isl_int_init(mod);
558 isl_int_set_si(mod, 1);
559 isl_int_mul_2exp(mod, mod, width);
561 pwaff = isl_pw_aff_mod(pwaff, mod);
563 isl_int_clear(mod);
565 return pwaff;
568 /* Limit the domain of "pwaff" to those elements where the function
569 * value satisfies
571 * 2^{width-1} <= pwaff < 2^{width-1}
573 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
574 unsigned width)
576 isl_int v;
577 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
578 isl_local_space *ls = isl_local_space_from_space(space);
579 isl_aff *bound;
580 isl_set *dom;
581 isl_pw_aff *b;
583 isl_int_init(v);
584 isl_int_set_si(v, 1);
585 isl_int_mul_2exp(v, v, width - 1);
587 bound = isl_aff_zero_on_domain(ls);
588 bound = isl_aff_add_constant(bound, v);
589 b = isl_pw_aff_from_aff(bound);
591 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
592 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
594 b = isl_pw_aff_neg(b);
595 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
596 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
598 isl_int_clear(v);
600 return pwaff;
603 /* Handle potential overflows on signed computations.
605 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
606 * the we adjust the domain of "pa" to avoid overflows.
608 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
609 unsigned width)
611 if (options->signed_overflow == PET_OVERFLOW_AVOID)
612 pa = avoid_overflow(pa, width);
614 return pa;
617 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
619 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
620 __isl_take isl_set *dom)
622 isl_pw_aff *pa;
623 pa = isl_set_indicator_function(set);
624 pa = isl_pw_aff_intersect_domain(pa, dom);
625 return pa;
628 /* Extract an affine expression from some binary operations.
629 * If the result of the expression is unsigned, then we wrap it
630 * based on the size of the type. Otherwise, we ensure that
631 * no overflow occurs.
633 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
635 isl_pw_aff *res;
636 unsigned width;
638 switch (expr->getOpcode()) {
639 case BO_Add:
640 case BO_Sub:
641 res = extract_affine_add(expr);
642 break;
643 case BO_Div:
644 res = extract_affine_div(expr);
645 break;
646 case BO_Rem:
647 res = extract_affine_mod(expr);
648 break;
649 case BO_Mul:
650 res = extract_affine_mul(expr);
651 break;
652 case BO_LT:
653 case BO_LE:
654 case BO_GT:
655 case BO_GE:
656 case BO_EQ:
657 case BO_NE:
658 case BO_LAnd:
659 case BO_LOr:
660 return extract_condition(expr);
661 default:
662 unsupported(expr);
663 return NULL;
666 width = ast_context.getIntWidth(expr->getType());
667 if (expr->getType()->isUnsignedIntegerType())
668 res = wrap(res, width);
669 else
670 res = signed_overflow(res, width);
672 return res;
675 /* Extract an affine expression from a negation operation.
677 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
679 if (expr->getOpcode() == UO_Minus)
680 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
681 if (expr->getOpcode() == UO_LNot)
682 return extract_condition(expr);
684 unsupported(expr);
685 return NULL;
688 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
690 return extract_affine(expr->getSubExpr());
693 /* Extract an affine expression from some special function calls.
694 * In particular, we handle "min", "max", "ceild" and "floord".
695 * In case of the latter two, the second argument needs to be
696 * a (positive) integer constant.
698 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
700 FunctionDecl *fd;
701 string name;
702 isl_pw_aff *aff1, *aff2;
704 fd = expr->getDirectCallee();
705 if (!fd) {
706 unsupported(expr);
707 return NULL;
710 name = fd->getDeclName().getAsString();
711 if (!(expr->getNumArgs() == 2 && name == "min") &&
712 !(expr->getNumArgs() == 2 && name == "max") &&
713 !(expr->getNumArgs() == 2 && name == "floord") &&
714 !(expr->getNumArgs() == 2 && name == "ceild")) {
715 unsupported(expr);
716 return NULL;
719 if (name == "min" || name == "max") {
720 aff1 = extract_affine(expr->getArg(0));
721 aff2 = extract_affine(expr->getArg(1));
723 if (name == "min")
724 aff1 = isl_pw_aff_min(aff1, aff2);
725 else
726 aff1 = isl_pw_aff_max(aff1, aff2);
727 } else if (name == "floord" || name == "ceild") {
728 isl_int v;
729 Expr *arg2 = expr->getArg(1);
731 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
732 unsupported(expr);
733 return NULL;
735 aff1 = extract_affine(expr->getArg(0));
736 isl_int_init(v);
737 extract_int(cast<IntegerLiteral>(arg2), &v);
738 aff1 = isl_pw_aff_scale_down(aff1, v);
739 isl_int_clear(v);
740 if (name == "floord")
741 aff1 = isl_pw_aff_floor(aff1);
742 else
743 aff1 = isl_pw_aff_ceil(aff1);
744 } else {
745 unsupported(expr);
746 return NULL;
749 return aff1;
752 /* This method is called when we come across an access that is
753 * nested in what is supposed to be an affine expression.
754 * If nesting is allowed, we return a new parameter that corresponds
755 * to this nested access. Otherwise, we simply complain.
757 * Note that we currently don't allow nested accesses themselves
758 * to contain any nested accesses, so we check if we can extract
759 * the access without any nesting and complain if we can't.
761 * The new parameter is resolved in resolve_nested.
763 isl_pw_aff *PetScan::nested_access(Expr *expr)
765 isl_id *id;
766 isl_space *dim;
767 isl_aff *aff;
768 isl_set *dom;
769 isl_map *access;
771 if (!nesting_enabled) {
772 unsupported(expr);
773 return NULL;
776 allow_nested = false;
777 access = extract_access(expr);
778 allow_nested = true;
779 if (!access) {
780 unsupported(expr);
781 return NULL;
783 isl_map_free(access);
785 id = isl_id_alloc(ctx, NULL, expr);
786 dim = isl_space_params_alloc(ctx, 1);
788 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
790 dom = isl_set_universe(isl_space_copy(dim));
791 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
792 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
794 return isl_pw_aff_alloc(dom, aff);
797 /* Affine expressions are not supposed to contain array accesses,
798 * but if nesting is allowed, we return a parameter corresponding
799 * to the array access.
801 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
803 return nested_access(expr);
806 /* Extract an affine expression from a conditional operation.
808 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
810 isl_pw_aff *cond, *lhs, *rhs, *res;
812 cond = extract_condition(expr->getCond());
813 lhs = extract_affine(expr->getTrueExpr());
814 rhs = extract_affine(expr->getFalseExpr());
816 return isl_pw_aff_cond(cond, lhs, rhs);
819 /* Extract an affine expression, if possible, from "expr".
820 * Otherwise return NULL.
822 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
824 switch (expr->getStmtClass()) {
825 case Stmt::ImplicitCastExprClass:
826 return extract_affine(cast<ImplicitCastExpr>(expr));
827 case Stmt::IntegerLiteralClass:
828 return extract_affine(cast<IntegerLiteral>(expr));
829 case Stmt::DeclRefExprClass:
830 return extract_affine(cast<DeclRefExpr>(expr));
831 case Stmt::BinaryOperatorClass:
832 return extract_affine(cast<BinaryOperator>(expr));
833 case Stmt::UnaryOperatorClass:
834 return extract_affine(cast<UnaryOperator>(expr));
835 case Stmt::ParenExprClass:
836 return extract_affine(cast<ParenExpr>(expr));
837 case Stmt::CallExprClass:
838 return extract_affine(cast<CallExpr>(expr));
839 case Stmt::ArraySubscriptExprClass:
840 return extract_affine(cast<ArraySubscriptExpr>(expr));
841 case Stmt::ConditionalOperatorClass:
842 return extract_affine(cast<ConditionalOperator>(expr));
843 default:
844 unsupported(expr);
846 return NULL;
849 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
851 return extract_access(expr->getSubExpr());
854 /* Return the depth of an array of the given type.
856 static int array_depth(const Type *type)
858 if (type->isPointerType())
859 return 1 + array_depth(type->getPointeeType().getTypePtr());
860 if (type->isArrayType()) {
861 const ArrayType *atype;
862 type = type->getCanonicalTypeInternal().getTypePtr();
863 atype = cast<ArrayType>(type);
864 return 1 + array_depth(atype->getElementType().getTypePtr());
866 return 0;
869 /* Return the element type of the given array type.
871 static QualType base_type(QualType qt)
873 const Type *type = qt.getTypePtr();
875 if (type->isPointerType())
876 return base_type(type->getPointeeType());
877 if (type->isArrayType()) {
878 const ArrayType *atype;
879 type = type->getCanonicalTypeInternal().getTypePtr();
880 atype = cast<ArrayType>(type);
881 return base_type(atype->getElementType());
883 return qt;
886 /* Extract an access relation from a reference to a variable.
887 * If the variable has name "A" and its type corresponds to an
888 * array of depth d, then the returned access relation is of the
889 * form
891 * { [] -> A[i_1,...,i_d] }
893 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
895 ValueDecl *decl = expr->getDecl();
896 int depth = array_depth(decl->getType().getTypePtr());
897 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
898 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
899 isl_map *access_rel;
901 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
903 access_rel = isl_map_universe(dim);
905 return access_rel;
908 /* Extract an access relation from an integer contant.
909 * If the value of the constant is "v", then the returned access relation
910 * is
912 * { [] -> [v] }
914 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
916 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
919 /* Try and extract an access relation from the given Expr.
920 * Return NULL if it doesn't work out.
922 __isl_give isl_map *PetScan::extract_access(Expr *expr)
924 switch (expr->getStmtClass()) {
925 case Stmt::ImplicitCastExprClass:
926 return extract_access(cast<ImplicitCastExpr>(expr));
927 case Stmt::DeclRefExprClass:
928 return extract_access(cast<DeclRefExpr>(expr));
929 case Stmt::ArraySubscriptExprClass:
930 return extract_access(cast<ArraySubscriptExpr>(expr));
931 case Stmt::IntegerLiteralClass:
932 return extract_access(cast<IntegerLiteral>(expr));
933 default:
934 unsupported(expr);
936 return NULL;
939 /* Assign the affine expression "index" to the output dimension "pos" of "map",
940 * restrict the domain to those values that result in a non-negative index
941 * and return the result.
943 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
944 __isl_take isl_pw_aff *index)
946 isl_map *index_map;
947 int len = isl_map_dim(map, isl_dim_out);
948 isl_id *id;
949 isl_set *domain;
951 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
952 index = isl_pw_aff_intersect_domain(index, domain);
953 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
954 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
955 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
956 id = isl_map_get_tuple_id(map, isl_dim_out);
957 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
959 map = isl_map_intersect(map, index_map);
961 return map;
964 /* Extract an access relation from the given array subscript expression.
965 * If nesting is allowed in general, then we turn it on while
966 * examining the index expression.
968 * We first extract an access relation from the base.
969 * This will result in an access relation with a range that corresponds
970 * to the array being accessed and with earlier indices filled in already.
971 * We then extract the current index and fill that in as well.
972 * The position of the current index is based on the type of base.
973 * If base is the actual array variable, then the depth of this type
974 * will be the same as the depth of the array and we will fill in
975 * the first array index.
976 * Otherwise, the depth of the base type will be smaller and we will fill
977 * in a later index.
979 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
981 Expr *base = expr->getBase();
982 Expr *idx = expr->getIdx();
983 isl_pw_aff *index;
984 isl_map *base_access;
985 isl_map *access;
986 int depth = array_depth(base->getType().getTypePtr());
987 int pos;
988 bool save_nesting = nesting_enabled;
990 nesting_enabled = allow_nested;
992 base_access = extract_access(base);
993 index = extract_affine(idx);
995 nesting_enabled = save_nesting;
997 pos = isl_map_dim(base_access, isl_dim_out) - depth;
998 access = set_index(base_access, pos, index);
1000 return access;
1003 /* Check if "expr" calls function "minmax" with two arguments and if so
1004 * make lhs and rhs refer to these two arguments.
1006 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1008 CallExpr *call;
1009 FunctionDecl *fd;
1010 string name;
1012 if (expr->getStmtClass() != Stmt::CallExprClass)
1013 return false;
1015 call = cast<CallExpr>(expr);
1016 fd = call->getDirectCallee();
1017 if (!fd)
1018 return false;
1020 if (call->getNumArgs() != 2)
1021 return false;
1023 name = fd->getDeclName().getAsString();
1024 if (name != minmax)
1025 return false;
1027 lhs = call->getArg(0);
1028 rhs = call->getArg(1);
1030 return true;
1033 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1034 * lhs and rhs refer to the two arguments.
1036 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1038 return is_minmax(expr, "min", lhs, rhs);
1041 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1042 * lhs and rhs refer to the two arguments.
1044 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1046 return is_minmax(expr, "max", lhs, rhs);
1049 /* Return "lhs && rhs", defined on the shared definition domain.
1051 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1052 __isl_take isl_pw_aff *rhs)
1054 isl_set *cond;
1055 isl_set *dom;
1057 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1058 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1059 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1060 isl_pw_aff_non_zero_set(rhs));
1061 return indicator_function(cond, dom);
1064 /* Return "lhs && rhs", with shortcut semantics.
1065 * That is, if lhs is false, then the result is defined even if rhs is not.
1066 * In practice, we compute lhs ? rhs : lhs.
1068 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1069 __isl_take isl_pw_aff *rhs)
1071 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1074 /* Return "lhs || rhs", with shortcut semantics.
1075 * That is, if lhs is true, then the result is defined even if rhs is not.
1076 * In practice, we compute lhs ? lhs : rhs.
1078 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1079 __isl_take isl_pw_aff *rhs)
1081 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1084 /* Extract an affine expressions representing the comparison "LHS op RHS"
1085 * "comp" is the original statement that "LHS op RHS" is derived from
1086 * and is used for diagnostics.
1088 * If the comparison is of the form
1090 * a <= min(b,c)
1092 * then the expression is constructed as the conjunction of
1093 * the comparisons
1095 * a <= b and a <= c
1097 * A similar optimization is performed for max(a,b) <= c.
1098 * We do this because that will lead to simpler representations
1099 * of the expression.
1100 * If isl is ever enhanced to explicitly deal with min and max expressions,
1101 * this optimization can be removed.
1103 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1104 Expr *LHS, Expr *RHS, Stmt *comp)
1106 isl_pw_aff *lhs;
1107 isl_pw_aff *rhs;
1108 isl_pw_aff *res;
1109 isl_set *cond;
1110 isl_set *dom;
1112 if (op == BO_GT)
1113 return extract_comparison(BO_LT, RHS, LHS, comp);
1114 if (op == BO_GE)
1115 return extract_comparison(BO_LE, RHS, LHS, comp);
1117 if (op == BO_LT || op == BO_LE) {
1118 Expr *expr1, *expr2;
1119 if (is_min(RHS, expr1, expr2)) {
1120 lhs = extract_comparison(op, LHS, expr1, comp);
1121 rhs = extract_comparison(op, LHS, expr2, comp);
1122 return pw_aff_and(lhs, rhs);
1124 if (is_max(LHS, expr1, expr2)) {
1125 lhs = extract_comparison(op, expr1, RHS, comp);
1126 rhs = extract_comparison(op, expr2, RHS, comp);
1127 return pw_aff_and(lhs, rhs);
1131 lhs = extract_affine(LHS);
1132 rhs = extract_affine(RHS);
1134 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1135 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1137 switch (op) {
1138 case BO_LT:
1139 cond = isl_pw_aff_lt_set(lhs, rhs);
1140 break;
1141 case BO_LE:
1142 cond = isl_pw_aff_le_set(lhs, rhs);
1143 break;
1144 case BO_EQ:
1145 cond = isl_pw_aff_eq_set(lhs, rhs);
1146 break;
1147 case BO_NE:
1148 cond = isl_pw_aff_ne_set(lhs, rhs);
1149 break;
1150 default:
1151 isl_pw_aff_free(lhs);
1152 isl_pw_aff_free(rhs);
1153 isl_set_free(dom);
1154 unsupported(comp);
1155 return NULL;
1158 cond = isl_set_coalesce(cond);
1159 res = indicator_function(cond, dom);
1161 return res;
1164 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1166 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1167 comp->getRHS(), comp);
1170 /* Extract an affine expression representing the negation (logical not)
1171 * of a subexpression.
1173 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1175 isl_set *set_cond, *dom;
1176 isl_pw_aff *cond, *res;
1178 cond = extract_condition(op->getSubExpr());
1180 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1182 set_cond = isl_pw_aff_zero_set(cond);
1184 res = indicator_function(set_cond, dom);
1186 return res;
1189 /* Extract an affine expression representing the disjunction (logical or)
1190 * or conjunction (logical and) of two subexpressions.
1192 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1194 isl_pw_aff *lhs, *rhs;
1196 lhs = extract_condition(comp->getLHS());
1197 rhs = extract_condition(comp->getRHS());
1199 switch (comp->getOpcode()) {
1200 case BO_LAnd:
1201 return pw_aff_and_then(lhs, rhs);
1202 case BO_LOr:
1203 return pw_aff_or_else(lhs, rhs);
1204 default:
1205 isl_pw_aff_free(lhs);
1206 isl_pw_aff_free(rhs);
1209 unsupported(comp);
1210 return NULL;
1213 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1215 switch (expr->getOpcode()) {
1216 case UO_LNot:
1217 return extract_boolean(expr);
1218 default:
1219 unsupported(expr);
1220 return NULL;
1224 /* Extract the affine expression "expr != 0 ? 1 : 0".
1226 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1228 isl_pw_aff *res;
1229 isl_set *set, *dom;
1231 res = extract_affine(expr);
1233 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1234 set = isl_pw_aff_non_zero_set(res);
1236 res = indicator_function(set, dom);
1238 return res;
1241 /* Extract an affine expression from a boolean expression.
1242 * In particular, return the expression "expr ? 1 : 0".
1244 * If the expression doesn't look like a condition, we assume it
1245 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1247 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1249 BinaryOperator *comp;
1251 if (!expr) {
1252 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1253 return indicator_function(u, isl_set_copy(u));
1256 if (expr->getStmtClass() == Stmt::ParenExprClass)
1257 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1259 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1260 return extract_condition(cast<UnaryOperator>(expr));
1262 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1263 return extract_implicit_condition(expr);
1265 comp = cast<BinaryOperator>(expr);
1266 switch (comp->getOpcode()) {
1267 case BO_LT:
1268 case BO_LE:
1269 case BO_GT:
1270 case BO_GE:
1271 case BO_EQ:
1272 case BO_NE:
1273 return extract_comparison(comp);
1274 case BO_LAnd:
1275 case BO_LOr:
1276 return extract_boolean(comp);
1277 default:
1278 return extract_implicit_condition(expr);
1282 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1284 switch (kind) {
1285 case UO_Minus:
1286 return pet_op_minus;
1287 case UO_PostInc:
1288 return pet_op_post_inc;
1289 case UO_PostDec:
1290 return pet_op_post_dec;
1291 case UO_PreInc:
1292 return pet_op_pre_inc;
1293 case UO_PreDec:
1294 return pet_op_pre_dec;
1295 default:
1296 return pet_op_last;
1300 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1302 switch (kind) {
1303 case BO_AddAssign:
1304 return pet_op_add_assign;
1305 case BO_SubAssign:
1306 return pet_op_sub_assign;
1307 case BO_MulAssign:
1308 return pet_op_mul_assign;
1309 case BO_DivAssign:
1310 return pet_op_div_assign;
1311 case BO_Assign:
1312 return pet_op_assign;
1313 case BO_Add:
1314 return pet_op_add;
1315 case BO_Sub:
1316 return pet_op_sub;
1317 case BO_Mul:
1318 return pet_op_mul;
1319 case BO_Div:
1320 return pet_op_div;
1321 case BO_Rem:
1322 return pet_op_mod;
1323 case BO_EQ:
1324 return pet_op_eq;
1325 case BO_LE:
1326 return pet_op_le;
1327 case BO_LT:
1328 return pet_op_lt;
1329 case BO_GT:
1330 return pet_op_gt;
1331 default:
1332 return pet_op_last;
1336 /* Construct a pet_expr representing a unary operator expression.
1338 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1340 struct pet_expr *arg;
1341 enum pet_op_type op;
1343 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1344 if (op == pet_op_last) {
1345 unsupported(expr);
1346 return NULL;
1349 arg = extract_expr(expr->getSubExpr());
1351 if (expr->isIncrementDecrementOp() &&
1352 arg && arg->type == pet_expr_access) {
1353 mark_write(arg);
1354 arg->acc.read = 1;
1357 return pet_expr_new_unary(ctx, op, arg);
1360 /* Mark the given access pet_expr as a write.
1361 * If a scalar is being accessed, then mark its value
1362 * as unknown in assigned_value.
1364 void PetScan::mark_write(struct pet_expr *access)
1366 isl_id *id;
1367 ValueDecl *decl;
1369 if (!access)
1370 return;
1372 access->acc.write = 1;
1373 access->acc.read = 0;
1375 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1376 return;
1378 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1379 decl = (ValueDecl *) isl_id_get_user(id);
1380 clear_assignment(assigned_value, decl);
1381 isl_id_free(id);
1384 /* Assign "rhs" to "lhs".
1386 * In particular, if "lhs" is a scalar variable, then mark
1387 * the variable as having been assigned. If, furthermore, "rhs"
1388 * is an affine expression, then keep track of this value in assigned_value
1389 * so that we can plug it in when we later come across the same variable.
1391 void PetScan::assign(struct pet_expr *lhs, Expr *rhs)
1393 isl_id *id;
1394 ValueDecl *decl;
1395 isl_pw_aff *pa;
1397 if (!lhs)
1398 return;
1399 if (lhs->type != pet_expr_access)
1400 return;
1401 if (isl_map_dim(lhs->acc.access, isl_dim_out) != 0)
1402 return;
1404 id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1405 decl = (ValueDecl *) isl_id_get_user(id);
1406 isl_id_free(id);
1408 pa = try_extract_affine(rhs);
1409 clear_assignment(assigned_value, decl);
1410 if (!pa)
1411 return;
1412 assigned_value[decl] = pa;
1413 insert_expression(pa);
1416 /* Construct a pet_expr representing a binary operator expression.
1418 * If the top level operator is an assignment and the LHS is an access,
1419 * then we mark that access as a write. If the operator is a compound
1420 * assignment, the access is marked as both a read and a write.
1422 * If "expr" assigns something to a scalar variable, then we mark
1423 * the variable as having been assigned. If, furthermore, the expression
1424 * is affine, then keep track of this value in assigned_value
1425 * so that we can plug it in when we later come across the same variable.
1427 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1429 struct pet_expr *lhs, *rhs;
1430 enum pet_op_type op;
1432 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1433 if (op == pet_op_last) {
1434 unsupported(expr);
1435 return NULL;
1438 lhs = extract_expr(expr->getLHS());
1439 rhs = extract_expr(expr->getRHS());
1441 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1442 mark_write(lhs);
1443 if (expr->isCompoundAssignmentOp())
1444 lhs->acc.read = 1;
1447 if (expr->getOpcode() == BO_Assign)
1448 assign(lhs, expr->getRHS());
1450 return pet_expr_new_binary(ctx, op, lhs, rhs);
1453 /* Construct a pet_expr representing a conditional operation.
1455 * We first try to extract the condition as an affine expression.
1456 * If that fails, we construct a pet_expr tree representing the condition.
1458 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1460 struct pet_expr *cond, *lhs, *rhs;
1461 isl_pw_aff *pa;
1463 pa = try_extract_affine(expr->getCond());
1464 if (pa) {
1465 isl_set *test = isl_set_from_pw_aff(pa);
1466 cond = pet_expr_from_access(isl_map_from_range(test));
1467 } else
1468 cond = extract_expr(expr->getCond());
1469 lhs = extract_expr(expr->getTrueExpr());
1470 rhs = extract_expr(expr->getFalseExpr());
1472 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1475 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1477 return extract_expr(expr->getSubExpr());
1480 /* Construct a pet_expr representing a floating point value.
1482 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1484 return pet_expr_new_double(ctx, expr->getValueAsApproximateDouble());
1487 /* Extract an access relation from "expr" and then convert it into
1488 * a pet_expr.
1490 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1492 isl_map *access;
1493 struct pet_expr *pe;
1495 access = extract_access(expr);
1497 pe = pet_expr_from_access(access);
1499 return pe;
1502 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1504 return extract_expr(expr->getSubExpr());
1507 /* Construct a pet_expr representing a function call.
1509 * If we are passing along a pointer to an array element
1510 * or an entire row or even higher dimensional slice of an array,
1511 * then the function being called may write into the array.
1513 * We assume here that if the function is declared to take a pointer
1514 * to a const type, then the function will perform a read
1515 * and that otherwise, it will perform a write.
1517 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1519 struct pet_expr *res = NULL;
1520 FunctionDecl *fd;
1521 string name;
1523 fd = expr->getDirectCallee();
1524 if (!fd) {
1525 unsupported(expr);
1526 return NULL;
1529 name = fd->getDeclName().getAsString();
1530 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1531 if (!res)
1532 return NULL;
1534 for (int i = 0; i < expr->getNumArgs(); ++i) {
1535 Expr *arg = expr->getArg(i);
1536 int is_addr = 0;
1537 pet_expr *main_arg;
1539 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1540 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1541 arg = ice->getSubExpr();
1543 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1544 UnaryOperator *op = cast<UnaryOperator>(arg);
1545 if (op->getOpcode() == UO_AddrOf) {
1546 is_addr = 1;
1547 arg = op->getSubExpr();
1550 res->args[i] = PetScan::extract_expr(arg);
1551 main_arg = res->args[i];
1552 if (is_addr)
1553 res->args[i] = pet_expr_new_unary(ctx,
1554 pet_op_address_of, res->args[i]);
1555 if (!res->args[i])
1556 goto error;
1557 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1558 array_depth(arg->getType().getTypePtr()) > 0)
1559 is_addr = 1;
1560 if (is_addr && main_arg->type == pet_expr_access) {
1561 ParmVarDecl *parm;
1562 if (!fd->hasPrototype()) {
1563 unsupported(expr, "prototype required");
1564 goto error;
1566 parm = fd->getParamDecl(i);
1567 if (!const_base(parm->getType()))
1568 mark_write(main_arg);
1572 return res;
1573 error:
1574 pet_expr_free(res);
1575 return NULL;
1578 /* Try and onstruct a pet_expr representing "expr".
1580 struct pet_expr *PetScan::extract_expr(Expr *expr)
1582 switch (expr->getStmtClass()) {
1583 case Stmt::UnaryOperatorClass:
1584 return extract_expr(cast<UnaryOperator>(expr));
1585 case Stmt::CompoundAssignOperatorClass:
1586 case Stmt::BinaryOperatorClass:
1587 return extract_expr(cast<BinaryOperator>(expr));
1588 case Stmt::ImplicitCastExprClass:
1589 return extract_expr(cast<ImplicitCastExpr>(expr));
1590 case Stmt::ArraySubscriptExprClass:
1591 case Stmt::DeclRefExprClass:
1592 case Stmt::IntegerLiteralClass:
1593 return extract_access_expr(expr);
1594 case Stmt::FloatingLiteralClass:
1595 return extract_expr(cast<FloatingLiteral>(expr));
1596 case Stmt::ParenExprClass:
1597 return extract_expr(cast<ParenExpr>(expr));
1598 case Stmt::ConditionalOperatorClass:
1599 return extract_expr(cast<ConditionalOperator>(expr));
1600 case Stmt::CallExprClass:
1601 return extract_expr(cast<CallExpr>(expr));
1602 default:
1603 unsupported(expr);
1605 return NULL;
1608 /* Check if the given initialization statement is an assignment.
1609 * If so, return that assignment. Otherwise return NULL.
1611 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1613 BinaryOperator *ass;
1615 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1616 return NULL;
1618 ass = cast<BinaryOperator>(init);
1619 if (ass->getOpcode() != BO_Assign)
1620 return NULL;
1622 return ass;
1625 /* Check if the given initialization statement is a declaration
1626 * of a single variable.
1627 * If so, return that declaration. Otherwise return NULL.
1629 Decl *PetScan::initialization_declaration(Stmt *init)
1631 DeclStmt *decl;
1633 if (init->getStmtClass() != Stmt::DeclStmtClass)
1634 return NULL;
1636 decl = cast<DeclStmt>(init);
1638 if (!decl->isSingleDecl())
1639 return NULL;
1641 return decl->getSingleDecl();
1644 /* Given the assignment operator in the initialization of a for loop,
1645 * extract the induction variable, i.e., the (integer)variable being
1646 * assigned.
1648 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1650 Expr *lhs;
1651 DeclRefExpr *ref;
1652 ValueDecl *decl;
1653 const Type *type;
1655 lhs = init->getLHS();
1656 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1657 unsupported(init);
1658 return NULL;
1661 ref = cast<DeclRefExpr>(lhs);
1662 decl = ref->getDecl();
1663 type = decl->getType().getTypePtr();
1665 if (!type->isIntegerType()) {
1666 unsupported(lhs);
1667 return NULL;
1670 return decl;
1673 /* Given the initialization statement of a for loop and the single
1674 * declaration in this initialization statement,
1675 * extract the induction variable, i.e., the (integer) variable being
1676 * declared.
1678 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1680 VarDecl *vd;
1682 vd = cast<VarDecl>(decl);
1684 const QualType type = vd->getType();
1685 if (!type->isIntegerType()) {
1686 unsupported(init);
1687 return NULL;
1690 if (!vd->getInit()) {
1691 unsupported(init);
1692 return NULL;
1695 return vd;
1698 /* Check that op is of the form iv++ or iv--.
1699 * Return an affine expression "1" or "-1" accordingly.
1701 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
1702 clang::UnaryOperator *op, clang::ValueDecl *iv)
1704 Expr *sub;
1705 DeclRefExpr *ref;
1706 isl_space *space;
1707 isl_aff *aff;
1709 if (!op->isIncrementDecrementOp()) {
1710 unsupported(op);
1711 return NULL;
1714 sub = op->getSubExpr();
1715 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1716 unsupported(op);
1717 return NULL;
1720 ref = cast<DeclRefExpr>(sub);
1721 if (ref->getDecl() != iv) {
1722 unsupported(op);
1723 return NULL;
1726 space = isl_space_params_alloc(ctx, 0);
1727 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1729 if (op->isIncrementOp())
1730 aff = isl_aff_add_constant_si(aff, 1);
1731 else
1732 aff = isl_aff_add_constant_si(aff, -1);
1734 return isl_pw_aff_from_aff(aff);
1737 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1738 * has a single constant expression, then put this constant in *user.
1739 * The caller is assumed to have checked that this function will
1740 * be called exactly once.
1742 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1743 void *user)
1745 isl_int *inc = (isl_int *)user;
1746 int res = 0;
1748 if (isl_aff_is_cst(aff))
1749 isl_aff_get_constant(aff, inc);
1750 else
1751 res = -1;
1753 isl_set_free(set);
1754 isl_aff_free(aff);
1756 return res;
1759 /* Check if op is of the form
1761 * iv = iv + inc
1763 * and return inc as an affine expression.
1765 * We extract an affine expression from the RHS, subtract iv and return
1766 * the result.
1768 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
1769 clang::ValueDecl *iv)
1771 Expr *lhs;
1772 DeclRefExpr *ref;
1773 isl_id *id;
1774 isl_space *dim;
1775 isl_aff *aff;
1776 isl_pw_aff *val;
1778 if (op->getOpcode() != BO_Assign) {
1779 unsupported(op);
1780 return NULL;
1783 lhs = op->getLHS();
1784 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1785 unsupported(op);
1786 return NULL;
1789 ref = cast<DeclRefExpr>(lhs);
1790 if (ref->getDecl() != iv) {
1791 unsupported(op);
1792 return NULL;
1795 val = extract_affine(op->getRHS());
1797 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1799 dim = isl_space_params_alloc(ctx, 1);
1800 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1801 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1802 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1804 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1806 return val;
1809 /* Check that op is of the form iv += cst or iv -= cst
1810 * and return an affine expression corresponding oto cst or -cst accordingly.
1812 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
1813 CompoundAssignOperator *op, clang::ValueDecl *iv)
1815 Expr *lhs;
1816 DeclRefExpr *ref;
1817 bool neg = false;
1818 isl_pw_aff *val;
1819 BinaryOperatorKind opcode;
1821 opcode = op->getOpcode();
1822 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1823 unsupported(op);
1824 return NULL;
1826 if (opcode == BO_SubAssign)
1827 neg = true;
1829 lhs = op->getLHS();
1830 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1831 unsupported(op);
1832 return NULL;
1835 ref = cast<DeclRefExpr>(lhs);
1836 if (ref->getDecl() != iv) {
1837 unsupported(op);
1838 return NULL;
1841 val = extract_affine(op->getRHS());
1842 if (neg)
1843 val = isl_pw_aff_neg(val);
1845 return val;
1848 /* Check that the increment of the given for loop increments
1849 * (or decrements) the induction variable "iv" and return
1850 * the increment as an affine expression if successful.
1852 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
1853 ValueDecl *iv)
1855 Stmt *inc = stmt->getInc();
1857 if (!inc) {
1858 unsupported(stmt);
1859 return NULL;
1862 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1863 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1864 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1865 return extract_compound_increment(
1866 cast<CompoundAssignOperator>(inc), iv);
1867 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1868 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1870 unsupported(inc);
1871 return NULL;
1874 /* Embed the given iteration domain in an extra outer loop
1875 * with induction variable "var".
1876 * If this variable appeared as a parameter in the constraints,
1877 * it is replaced by the new outermost dimension.
1879 static __isl_give isl_set *embed(__isl_take isl_set *set,
1880 __isl_take isl_id *var)
1882 int pos;
1884 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1885 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1886 if (pos >= 0) {
1887 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1888 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1891 isl_id_free(var);
1892 return set;
1895 /* Return those elements in the space of "cond" that come after
1896 * (based on "sign") an element in "cond".
1898 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
1900 isl_map *previous_to_this;
1902 if (sign > 0)
1903 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
1904 else
1905 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
1907 cond = isl_set_apply(cond, previous_to_this);
1909 return cond;
1912 /* Create the infinite iteration domain
1914 * { [id] : id >= 0 }
1916 * If "scop" has an affine skip of type pet_skip_later,
1917 * then remove those iterations i that have an earlier iteration
1918 * where the skip condition is satisfied, meaning that iteration i
1919 * is not executed.
1920 * Since we are dealing with a loop without loop iterator,
1921 * the skip condition cannot refer to the current loop iterator and
1922 * so effectively, the returned set is of the form
1924 * { [0]; [id] : id >= 1 and not skip }
1926 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
1927 struct pet_scop *scop)
1929 isl_ctx *ctx = isl_id_get_ctx(id);
1930 isl_set *domain;
1931 isl_set *skip;
1933 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1934 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
1936 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
1937 return domain;
1939 skip = pet_scop_get_skip(scop, pet_skip_later);
1940 skip = isl_set_fix_si(skip, isl_dim_set, 0, 1);
1941 skip = isl_set_params(skip);
1942 skip = embed(skip, isl_id_copy(id));
1943 skip = isl_set_intersect(skip , isl_set_copy(domain));
1944 domain = isl_set_subtract(domain, after(skip, 1));
1946 return domain;
1949 /* Create an identity mapping on the space containing "domain".
1951 static __isl_give isl_map *identity_map(__isl_keep isl_set *domain)
1953 isl_space *space;
1954 isl_map *id;
1956 space = isl_space_map_from_set(isl_set_get_space(domain));
1957 id = isl_map_identity(space);
1959 return id;
1962 /* Add a filter to "scop" that imposes that it is only executed
1963 * when "break_access" has a zero value for all previous iterations
1964 * of "domain".
1966 * The input "break_access" has a zero-dimensional domain and range.
1968 static struct pet_scop *scop_add_break(struct pet_scop *scop,
1969 __isl_take isl_map *break_access, __isl_take isl_set *domain, int sign)
1971 isl_ctx *ctx = isl_set_get_ctx(domain);
1972 isl_id *id_test;
1973 isl_map *prev;
1975 id_test = isl_map_get_tuple_id(break_access, isl_dim_out);
1976 break_access = isl_map_add_dims(break_access, isl_dim_in, 1);
1977 break_access = isl_map_add_dims(break_access, isl_dim_out, 1);
1978 break_access = isl_map_intersect_range(break_access, domain);
1979 break_access = isl_map_set_tuple_id(break_access, isl_dim_out, id_test);
1980 if (sign > 0)
1981 prev = isl_map_lex_gt_first(isl_map_get_space(break_access), 1);
1982 else
1983 prev = isl_map_lex_lt_first(isl_map_get_space(break_access), 1);
1984 break_access = isl_map_intersect(break_access, prev);
1985 scop = pet_scop_filter(scop, break_access, 0);
1986 scop = pet_scop_merge_filters(scop);
1988 return scop;
1991 /* Construct a pet_scop for an infinite loop around the given body.
1993 * We extract a pet_scop for the body and then embed it in a loop with
1994 * iteration domain
1996 * { [t] : t >= 0 }
1998 * and schedule
2000 * { [t] -> [t] }
2002 * If the body contains any break, then it is taken into
2003 * account in infinite_domain (if the skip condition is affine)
2004 * or in scop_add_break (if the skip condition is not affine).
2006 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2008 isl_id *id;
2009 isl_set *domain;
2010 isl_map *ident;
2011 isl_map *access;
2012 struct pet_scop *scop;
2013 bool has_var_break;
2015 scop = extract(body);
2016 if (!scop)
2017 return NULL;
2019 id = isl_id_alloc(ctx, "t", NULL);
2020 domain = infinite_domain(isl_id_copy(id), scop);
2021 ident = identity_map(domain);
2023 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2024 if (has_var_break)
2025 access = pet_scop_get_skip_map(scop, pet_skip_later);
2027 scop = pet_scop_embed(scop, isl_set_copy(domain),
2028 isl_map_copy(ident), ident, id);
2029 if (has_var_break)
2030 scop = scop_add_break(scop, access, domain, 1);
2031 else
2032 isl_set_free(domain);
2034 return scop;
2037 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2039 * for (;;)
2040 * body
2043 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2045 return extract_infinite_loop(stmt->getBody());
2048 /* Create an access to a virtual array representing the result
2049 * of a condition.
2050 * Unlike other accessed data, the id of the array is NULL as
2051 * there is no ValueDecl in the program corresponding to the virtual
2052 * array.
2053 * The array starts out as a scalar, but grows along with the
2054 * statement writing to the array in pet_scop_embed.
2056 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2058 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2059 isl_id *id;
2060 char name[50];
2062 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2063 id = isl_id_alloc(ctx, name, NULL);
2064 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2065 return isl_map_universe(dim);
2068 /* Add an array with the given extent ("access") to the list
2069 * of arrays in "scop" and return the extended pet_scop.
2070 * The array is marked as attaining values 0 and 1 only and
2071 * as each element being assigned at most once.
2073 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2074 __isl_keep isl_map *access, clang::ASTContext &ast_ctx)
2076 isl_ctx *ctx = isl_map_get_ctx(access);
2077 isl_space *dim;
2078 struct pet_array *array;
2080 if (!scop)
2081 return NULL;
2082 if (!ctx)
2083 goto error;
2085 array = isl_calloc_type(ctx, struct pet_array);
2086 if (!array)
2087 goto error;
2089 array->extent = isl_map_range(isl_map_copy(access));
2090 dim = isl_space_params_alloc(ctx, 0);
2091 array->context = isl_set_universe(dim);
2092 dim = isl_space_set_alloc(ctx, 0, 1);
2093 array->value_bounds = isl_set_universe(dim);
2094 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2095 isl_dim_set, 0, 0);
2096 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2097 isl_dim_set, 0, 1);
2098 array->element_type = strdup("int");
2099 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2100 array->uniquely_defined = 1;
2102 if (!array->extent || !array->context)
2103 array = pet_array_free(array);
2105 scop = pet_scop_add_array(scop, array);
2107 return scop;
2108 error:
2109 pet_scop_free(scop);
2110 return NULL;
2113 /* Construct a pet_scop for a while loop of the form
2115 * while (pa)
2116 * body
2118 * In particular, construct a scop for an infinite loop around body and
2119 * intersect the domain with the affine expression.
2120 * Note that this intersection may result in an empty loop.
2122 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2123 Stmt *body)
2125 struct pet_scop *scop;
2126 isl_set *dom;
2127 isl_set *valid;
2129 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2130 dom = isl_pw_aff_non_zero_set(pa);
2131 scop = extract_infinite_loop(body);
2132 scop = pet_scop_restrict(scop, dom);
2133 scop = pet_scop_restrict_context(scop, valid);
2135 return scop;
2138 /* Construct a scop for a while, given the scops for the condition
2139 * and the body, the filter access and the iteration domain of
2140 * the while loop.
2142 * In particular, the scop for the condition is filtered to depend
2143 * on "test_access" evaluating to true for all previous iterations
2144 * of the loop, while the scop for the body is filtered to depend
2145 * on "test_access" evaluating to true for all iterations up to the
2146 * current iteration.
2148 * These filtered scops are then combined into a single scop.
2150 * "sign" is positive if the iterator increases and negative
2151 * if it decreases.
2153 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2154 struct pet_scop *scop_body, __isl_take isl_map *test_access,
2155 __isl_take isl_set *domain, int sign)
2157 isl_ctx *ctx = isl_set_get_ctx(domain);
2158 isl_id *id_test;
2159 isl_map *prev;
2161 id_test = isl_map_get_tuple_id(test_access, isl_dim_out);
2162 test_access = isl_map_add_dims(test_access, isl_dim_in, 1);
2163 test_access = isl_map_add_dims(test_access, isl_dim_out, 1);
2164 test_access = isl_map_intersect_range(test_access, domain);
2165 test_access = isl_map_set_tuple_id(test_access, isl_dim_out, id_test);
2166 if (sign > 0)
2167 prev = isl_map_lex_ge_first(isl_map_get_space(test_access), 1);
2168 else
2169 prev = isl_map_lex_le_first(isl_map_get_space(test_access), 1);
2170 test_access = isl_map_intersect(test_access, prev);
2171 scop_body = pet_scop_filter(scop_body, isl_map_copy(test_access), 1);
2172 if (sign > 0)
2173 prev = isl_map_lex_gt_first(isl_map_get_space(test_access), 1);
2174 else
2175 prev = isl_map_lex_lt_first(isl_map_get_space(test_access), 1);
2176 test_access = isl_map_intersect(test_access, prev);
2177 scop_cond = pet_scop_filter(scop_cond, test_access, 1);
2179 return pet_scop_add_seq(ctx, scop_cond, scop_body);
2182 /* Check if the while loop is of the form
2184 * while (affine expression)
2185 * body
2187 * If so, call extract_affine_while to construct a scop.
2189 * Otherwise, construct a generic while scop, with iteration domain
2190 * { [t] : t >= 0 }. The scop consists of two parts, one for
2191 * evaluating the condition and one for the body.
2192 * The schedule is adjusted to reflect that the condition is evaluated
2193 * before the body is executed and the body is filtered to depend
2194 * on the result of the condition evaluating to true on all iterations
2195 * up to the current iteration, while the evaluation the condition itself
2196 * is filtered to depend on the result of the condition evaluating to true
2197 * on all previous iterations.
2198 * The context of the scop representing the body is dropped
2199 * because we don't know how many times the body will be executed,
2200 * if at all.
2202 * If the body contains any break, then it is taken into
2203 * account in infinite_domain (if the skip condition is affine)
2204 * or in scop_add_break (if the skip condition is not affine).
2206 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2208 Expr *cond;
2209 isl_id *id;
2210 isl_map *test_access;
2211 isl_set *domain;
2212 isl_map *ident;
2213 isl_pw_aff *pa;
2214 struct pet_scop *scop, *scop_body;
2215 bool has_var_break;
2216 isl_map *break_access;
2218 cond = stmt->getCond();
2219 if (!cond) {
2220 unsupported(stmt);
2221 return NULL;
2224 clear_assignments clear(assigned_value);
2225 clear.TraverseStmt(stmt->getBody());
2227 pa = try_extract_affine_condition(cond);
2228 if (pa)
2229 return extract_affine_while(pa, stmt->getBody());
2231 if (!allow_nested) {
2232 unsupported(stmt);
2233 return NULL;
2236 test_access = create_test_access(ctx, n_test++);
2237 scop = extract_non_affine_condition(cond, isl_map_copy(test_access));
2238 scop = scop_add_array(scop, test_access, ast_context);
2239 scop_body = extract(stmt->getBody());
2241 id = isl_id_alloc(ctx, "t", NULL);
2242 domain = infinite_domain(isl_id_copy(id), scop_body);
2243 ident = identity_map(domain);
2245 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2246 if (has_var_break)
2247 break_access = pet_scop_get_skip_map(scop_body, pet_skip_later);
2249 scop = pet_scop_prefix(scop, 0);
2250 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_map_copy(ident),
2251 isl_map_copy(ident), isl_id_copy(id));
2252 scop_body = pet_scop_reset_context(scop_body);
2253 scop_body = pet_scop_prefix(scop_body, 1);
2254 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2255 isl_map_copy(ident), ident, id);
2257 if (has_var_break) {
2258 scop = scop_add_break(scop, isl_map_copy(break_access),
2259 isl_set_copy(domain), 1);
2260 scop_body = scop_add_break(scop_body, break_access,
2261 isl_set_copy(domain), 1);
2263 scop = scop_add_while(scop, scop_body, test_access, domain, 1);
2265 return scop;
2268 /* Check whether "cond" expresses a simple loop bound
2269 * on the only set dimension.
2270 * In particular, if "up" is set then "cond" should contain only
2271 * upper bounds on the set dimension.
2272 * Otherwise, it should contain only lower bounds.
2274 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
2276 if (isl_int_is_pos(inc))
2277 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2278 else
2279 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2282 /* Extend a condition on a given iteration of a loop to one that
2283 * imposes the same condition on all previous iterations.
2284 * "domain" expresses the lower [upper] bound on the iterations
2285 * when inc is positive [negative].
2287 * In particular, we construct the condition (when inc is positive)
2289 * forall i' : (domain(i') and i' <= i) => cond(i')
2291 * which is equivalent to
2293 * not exists i' : domain(i') and i' <= i and not cond(i')
2295 * We construct this set by negating cond, applying a map
2297 * { [i'] -> [i] : domain(i') and i' <= i }
2299 * and then negating the result again.
2301 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2302 __isl_take isl_set *domain, isl_int inc)
2304 isl_map *previous_to_this;
2306 if (isl_int_is_pos(inc))
2307 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2308 else
2309 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2311 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2313 cond = isl_set_complement(cond);
2314 cond = isl_set_apply(cond, previous_to_this);
2315 cond = isl_set_complement(cond);
2317 return cond;
2320 /* Construct a domain of the form
2322 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2324 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2325 __isl_take isl_pw_aff *init, isl_int inc)
2327 isl_aff *aff;
2328 isl_space *dim;
2329 isl_set *set;
2331 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2332 dim = isl_pw_aff_get_domain_space(init);
2333 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2334 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
2335 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2337 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2338 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2339 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2340 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2342 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2344 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2346 return isl_set_params(set);
2349 /* Assuming "cond" represents a bound on a loop where the loop
2350 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2351 * is possible.
2353 * Under the given assumptions, wrapping is only possible if "cond" allows
2354 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2355 * increasing iterator and 0 in case of a decreasing iterator.
2357 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
2359 bool cw;
2360 isl_int limit;
2361 isl_set *test;
2363 test = isl_set_copy(cond);
2365 isl_int_init(limit);
2366 if (isl_int_is_neg(inc))
2367 isl_int_set_si(limit, 0);
2368 else {
2369 isl_int_set_si(limit, 1);
2370 isl_int_mul_2exp(limit, limit, get_type_size(iv));
2371 isl_int_sub_ui(limit, limit, 1);
2374 test = isl_set_fix(cond, isl_dim_set, 0, limit);
2375 cw = !isl_set_is_empty(test);
2376 isl_set_free(test);
2378 isl_int_clear(limit);
2380 return cw;
2383 /* Given a one-dimensional space, construct the following mapping on this
2384 * space
2386 * { [v] -> [v mod 2^width] }
2388 * where width is the number of bits used to represent the values
2389 * of the unsigned variable "iv".
2391 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
2392 ValueDecl *iv)
2394 isl_int mod;
2395 isl_aff *aff;
2396 isl_map *map;
2398 isl_int_init(mod);
2399 isl_int_set_si(mod, 1);
2400 isl_int_mul_2exp(mod, mod, get_type_size(iv));
2402 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2403 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2404 aff = isl_aff_mod(aff, mod);
2406 isl_int_clear(mod);
2408 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2409 map = isl_map_reverse(map);
2412 /* Project out the parameter "id" from "set".
2414 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2415 __isl_keep isl_id *id)
2417 int pos;
2419 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2420 if (pos >= 0)
2421 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2423 return set;
2426 /* Compute the set of parameters for which "set1" is a subset of "set2".
2428 * set1 is a subset of set2 if
2430 * forall i in set1 : i in set2
2432 * or
2434 * not exists i in set1 and i not in set2
2436 * i.e.,
2438 * not exists i in set1 \ set2
2440 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2441 __isl_take isl_set *set2)
2443 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2446 /* Compute the set of parameter values for which "cond" holds
2447 * on the next iteration for each element of "dom".
2449 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2450 * and then compute the set of parameters for which the result is a subset
2451 * of "cond".
2453 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2454 __isl_take isl_set *dom, isl_int inc)
2456 isl_space *space;
2457 isl_aff *aff;
2458 isl_map *next;
2460 space = isl_set_get_space(dom);
2461 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2462 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2463 aff = isl_aff_add_constant(aff, inc);
2464 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2466 dom = isl_set_apply(dom, next);
2468 return enforce_subset(dom, cond);
2471 /* Does "id" refer to a nested access?
2473 static bool is_nested_parameter(__isl_keep isl_id *id)
2475 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2478 /* Does parameter "pos" of "space" refer to a nested access?
2480 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2482 bool nested;
2483 isl_id *id;
2485 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2486 nested = is_nested_parameter(id);
2487 isl_id_free(id);
2489 return nested;
2492 /* Does "space" involve any parameters that refer to nested
2493 * accesses, i.e., parameters with no name?
2495 static bool has_nested(__isl_keep isl_space *space)
2497 int nparam;
2499 nparam = isl_space_dim(space, isl_dim_param);
2500 for (int i = 0; i < nparam; ++i)
2501 if (is_nested_parameter(space, i))
2502 return true;
2504 return false;
2507 /* Does "pa" involve any parameters that refer to nested
2508 * accesses, i.e., parameters with no name?
2510 static bool has_nested(__isl_keep isl_pw_aff *pa)
2512 isl_space *space;
2513 bool nested;
2515 space = isl_pw_aff_get_space(pa);
2516 nested = has_nested(space);
2517 isl_space_free(space);
2519 return nested;
2522 /* Construct a pet_scop for a for statement.
2523 * The for loop is required to be of the form
2525 * for (i = init; condition; ++i)
2527 * or
2529 * for (i = init; condition; --i)
2531 * The initialization of the for loop should either be an assignment
2532 * to an integer variable, or a declaration of such a variable with
2533 * initialization.
2535 * The condition is allowed to contain nested accesses, provided
2536 * they are not being written to inside the body of the loop.
2537 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2538 * essentially treated as a while loop, with iteration domain
2539 * { [i] : i >= init }.
2541 * We extract a pet_scop for the body and then embed it in a loop with
2542 * iteration domain and schedule
2544 * { [i] : i >= init and condition' }
2545 * { [i] -> [i] }
2547 * or
2549 * { [i] : i <= init and condition' }
2550 * { [i] -> [-i] }
2552 * Where condition' is equal to condition if the latter is
2553 * a simple upper [lower] bound and a condition that is extended
2554 * to apply to all previous iterations otherwise.
2556 * If the condition is non-affine, then we drop the condition from the
2557 * iteration domain and instead create a separate statement
2558 * for evaluating the condition. The body is then filtered to depend
2559 * on the result of the condition evaluating to true on all iterations
2560 * up to the current iteration, while the evaluation the condition itself
2561 * is filtered to depend on the result of the condition evaluating to true
2562 * on all previous iterations.
2563 * The context of the scop representing the body is dropped
2564 * because we don't know how many times the body will be executed,
2565 * if at all.
2567 * If the stride of the loop is not 1, then "i >= init" is replaced by
2569 * (exists a: i = init + stride * a and a >= 0)
2571 * If the loop iterator i is unsigned, then wrapping may occur.
2572 * During the computation, we work with a virtual iterator that
2573 * does not wrap. However, the condition in the code applies
2574 * to the wrapped value, so we need to change condition(i)
2575 * into condition([i % 2^width]).
2576 * After computing the virtual domain and schedule, we apply
2577 * the function { [v] -> [v % 2^width] } to the domain and the domain
2578 * of the schedule. In order not to lose any information, we also
2579 * need to intersect the domain of the schedule with the virtual domain
2580 * first, since some iterations in the wrapped domain may be scheduled
2581 * several times, typically an infinite number of times.
2582 * Note that there may be no need to perform this final wrapping
2583 * if the loop condition (after wrapping) satisfies certain conditions.
2584 * However, the is_simple_bound condition is not enough since it doesn't
2585 * check if there even is an upper bound.
2587 * If the loop condition is non-affine, then we keep the virtual
2588 * iterator in the iteration domain and instead replace all accesses
2589 * to the original iterator by the wrapping of the virtual iterator.
2591 * Wrapping on unsigned iterators can be avoided entirely if
2592 * loop condition is simple, the loop iterator is incremented
2593 * [decremented] by one and the last value before wrapping cannot
2594 * possibly satisfy the loop condition.
2596 * Before extracting a pet_scop from the body we remove all
2597 * assignments in assigned_value to variables that are assigned
2598 * somewhere in the body of the loop.
2600 * Valid parameters for a for loop are those for which the initial
2601 * value itself, the increment on each domain iteration and
2602 * the condition on both the initial value and
2603 * the result of incrementing the iterator for each iteration of the domain
2604 * can be evaluated.
2605 * If the loop condition is non-affine, then we only consider validity
2606 * of the initial value.
2608 * If the body contains any break, then we keep track of it in "skip"
2609 * (if the skip condition is affine) or it is handled in scop_add_break
2610 * (if the skip condition is not affine).
2611 * Note that the affine break condition needs to be considered with
2612 * respect to previous iterations in the virtual domain (if any)
2613 * and that the domain needs to be kept virtual if there is a non-affine
2614 * break condition.
2616 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2618 BinaryOperator *ass;
2619 Decl *decl;
2620 Stmt *init;
2621 Expr *lhs, *rhs;
2622 ValueDecl *iv;
2623 isl_space *space;
2624 isl_set *domain;
2625 isl_map *sched;
2626 isl_set *cond = NULL;
2627 isl_set *skip = NULL;
2628 isl_id *id;
2629 struct pet_scop *scop, *scop_cond = NULL;
2630 assigned_value_cache cache(assigned_value);
2631 isl_int inc;
2632 bool is_one;
2633 bool is_unsigned;
2634 bool is_simple;
2635 bool is_virtual;
2636 bool keep_virtual = false;
2637 bool has_affine_break;
2638 bool has_var_break;
2639 isl_map *wrap = NULL;
2640 isl_pw_aff *pa, *pa_inc, *init_val;
2641 isl_set *valid_init;
2642 isl_set *valid_cond;
2643 isl_set *valid_cond_init;
2644 isl_set *valid_cond_next;
2645 isl_set *valid_inc;
2646 isl_map *test_access = NULL, *break_access = NULL;
2647 int stmt_id;
2649 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2650 return extract_infinite_for(stmt);
2652 init = stmt->getInit();
2653 if (!init) {
2654 unsupported(stmt);
2655 return NULL;
2657 if ((ass = initialization_assignment(init)) != NULL) {
2658 iv = extract_induction_variable(ass);
2659 if (!iv)
2660 return NULL;
2661 lhs = ass->getLHS();
2662 rhs = ass->getRHS();
2663 } else if ((decl = initialization_declaration(init)) != NULL) {
2664 VarDecl *var = extract_induction_variable(init, decl);
2665 if (!var)
2666 return NULL;
2667 iv = var;
2668 rhs = var->getInit();
2669 lhs = create_DeclRefExpr(var);
2670 } else {
2671 unsupported(stmt->getInit());
2672 return NULL;
2675 pa_inc = extract_increment(stmt, iv);
2676 if (!pa_inc)
2677 return NULL;
2679 isl_int_init(inc);
2680 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
2681 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
2682 isl_pw_aff_free(pa_inc);
2683 unsupported(stmt->getInc());
2684 isl_int_clear(inc);
2685 return NULL;
2687 valid_inc = isl_pw_aff_domain(pa_inc);
2689 is_unsigned = iv->getType()->isUnsignedIntegerType();
2691 assigned_value.erase(iv);
2692 clear_assignments clear(assigned_value);
2693 clear.TraverseStmt(stmt->getBody());
2695 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2697 pa = try_extract_nested_condition(stmt->getCond());
2698 if (allow_nested && (!pa || has_nested(pa)))
2699 stmt_id = n_stmt++;
2701 scop = extract(stmt->getBody());
2703 has_affine_break = scop &&
2704 pet_scop_has_affine_skip(scop, pet_skip_later);
2705 if (has_affine_break) {
2706 skip = pet_scop_get_skip(scop, pet_skip_later);
2707 skip = isl_set_fix_si(skip, isl_dim_set, 0, 1);
2708 skip = isl_set_params(skip);
2710 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
2711 if (has_var_break) {
2712 break_access = pet_scop_get_skip_map(scop, pet_skip_later);
2713 keep_virtual = true;
2716 if (pa && !is_nested_allowed(pa, scop)) {
2717 isl_pw_aff_free(pa);
2718 pa = NULL;
2721 if (!allow_nested && !pa)
2722 pa = try_extract_affine_condition(stmt->getCond());
2723 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2724 cond = isl_pw_aff_non_zero_set(pa);
2725 if (allow_nested && !cond) {
2726 int save_n_stmt = n_stmt;
2727 test_access = create_test_access(ctx, n_test++);
2728 n_stmt = stmt_id;
2729 scop_cond = extract_non_affine_condition(stmt->getCond(),
2730 isl_map_copy(test_access));
2731 n_stmt = save_n_stmt;
2732 scop_cond = scop_add_array(scop_cond, test_access, ast_context);
2733 scop_cond = pet_scop_prefix(scop_cond, 0);
2734 scop = pet_scop_reset_context(scop);
2735 scop = pet_scop_prefix(scop, 1);
2736 keep_virtual = true;
2737 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2740 cond = embed(cond, isl_id_copy(id));
2741 skip = embed(skip, isl_id_copy(id));
2742 valid_cond = isl_set_coalesce(valid_cond);
2743 valid_cond = embed(valid_cond, isl_id_copy(id));
2744 valid_inc = embed(valid_inc, isl_id_copy(id));
2745 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
2746 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2748 init_val = extract_affine(rhs);
2749 valid_cond_init = enforce_subset(
2750 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
2751 isl_set_copy(valid_cond));
2752 if (is_one && !is_virtual) {
2753 isl_pw_aff_free(init_val);
2754 pa = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
2755 lhs, rhs, init);
2756 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2757 valid_init = set_project_out_by_id(valid_init, id);
2758 domain = isl_pw_aff_non_zero_set(pa);
2759 } else {
2760 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2761 domain = strided_domain(isl_id_copy(id), init_val, inc);
2764 domain = embed(domain, isl_id_copy(id));
2765 if (is_virtual) {
2766 isl_map *rev_wrap;
2767 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2768 rev_wrap = isl_map_reverse(isl_map_copy(wrap));
2769 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2770 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
2771 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2772 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2774 is_simple = is_simple_bound(cond, inc);
2775 if (!is_simple) {
2776 cond = isl_set_gist(cond, isl_set_copy(domain));
2777 is_simple = is_simple_bound(cond, inc);
2779 if (!is_simple)
2780 cond = valid_for_each_iteration(cond,
2781 isl_set_copy(domain), inc);
2782 domain = isl_set_intersect(domain, cond);
2783 if (has_affine_break) {
2784 skip = isl_set_intersect(skip , isl_set_copy(domain));
2785 skip = after(skip, isl_int_sgn(inc));
2786 domain = isl_set_subtract(domain, skip);
2788 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2789 space = isl_space_from_domain(isl_set_get_space(domain));
2790 space = isl_space_add_dims(space, isl_dim_out, 1);
2791 sched = isl_map_universe(space);
2792 if (isl_int_is_pos(inc))
2793 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2794 else
2795 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2797 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain), inc);
2798 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2800 if (is_virtual && !keep_virtual) {
2801 wrap = isl_map_set_dim_id(wrap,
2802 isl_dim_out, 0, isl_id_copy(id));
2803 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2804 domain = isl_set_apply(domain, isl_map_copy(wrap));
2805 sched = isl_map_apply_domain(sched, wrap);
2807 if (!(is_virtual && keep_virtual)) {
2808 space = isl_set_get_space(domain);
2809 wrap = isl_map_identity(isl_space_map_from_set(space));
2812 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
2813 isl_map_copy(sched), isl_map_copy(wrap), isl_id_copy(id));
2814 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
2815 scop = resolve_nested(scop);
2816 if (has_var_break)
2817 scop = scop_add_break(scop, break_access, isl_set_copy(domain),
2818 isl_int_sgn(inc));
2819 if (test_access) {
2820 scop = scop_add_while(scop_cond, scop, test_access, domain,
2821 isl_int_sgn(inc));
2822 isl_set_free(valid_inc);
2823 } else {
2824 scop = pet_scop_restrict_context(scop, valid_inc);
2825 scop = pet_scop_restrict_context(scop, valid_cond_next);
2826 scop = pet_scop_restrict_context(scop, valid_cond_init);
2827 isl_set_free(domain);
2829 clear_assignment(assigned_value, iv);
2831 isl_int_clear(inc);
2833 scop = pet_scop_restrict_context(scop, valid_init);
2835 return scop;
2838 struct pet_scop *PetScan::extract(CompoundStmt *stmt)
2840 return extract(stmt->children());
2843 /* Does parameter "pos" of "map" refer to a nested access?
2845 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2847 bool nested;
2848 isl_id *id;
2850 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2851 nested = is_nested_parameter(id);
2852 isl_id_free(id);
2854 return nested;
2857 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2859 static int n_nested_parameter(__isl_keep isl_space *space)
2861 int n = 0;
2862 int nparam;
2864 nparam = isl_space_dim(space, isl_dim_param);
2865 for (int i = 0; i < nparam; ++i)
2866 if (is_nested_parameter(space, i))
2867 ++n;
2869 return n;
2872 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2874 static int n_nested_parameter(__isl_keep isl_map *map)
2876 isl_space *space;
2877 int n;
2879 space = isl_map_get_space(map);
2880 n = n_nested_parameter(space);
2881 isl_space_free(space);
2883 return n;
2886 /* For each nested access parameter in "space",
2887 * construct a corresponding pet_expr, place it in args and
2888 * record its position in "param2pos".
2889 * "n_arg" is the number of elements that are already in args.
2890 * The position recorded in "param2pos" takes this number into account.
2891 * If the pet_expr corresponding to a parameter is identical to
2892 * the pet_expr corresponding to an earlier parameter, then these two
2893 * parameters are made to refer to the same element in args.
2895 * Return the final number of elements in args or -1 if an error has occurred.
2897 int PetScan::extract_nested(__isl_keep isl_space *space,
2898 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
2900 int nparam;
2902 nparam = isl_space_dim(space, isl_dim_param);
2903 for (int i = 0; i < nparam; ++i) {
2904 int j;
2905 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2906 Expr *nested;
2908 if (!is_nested_parameter(id)) {
2909 isl_id_free(id);
2910 continue;
2913 nested = (Expr *) isl_id_get_user(id);
2914 args[n_arg] = extract_expr(nested);
2915 if (!args[n_arg])
2916 return -1;
2918 for (j = 0; j < n_arg; ++j)
2919 if (pet_expr_is_equal(args[j], args[n_arg]))
2920 break;
2922 if (j < n_arg) {
2923 pet_expr_free(args[n_arg]);
2924 args[n_arg] = NULL;
2925 param2pos[i] = j;
2926 } else
2927 param2pos[i] = n_arg++;
2929 isl_id_free(id);
2932 return n_arg;
2935 /* For each nested access parameter in the access relations in "expr",
2936 * construct a corresponding pet_expr, place it in expr->args and
2937 * record its position in "param2pos".
2938 * n is the number of nested access parameters.
2940 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
2941 std::map<int,int> &param2pos)
2943 isl_space *space;
2945 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
2946 expr->n_arg = n;
2947 if (!expr->args)
2948 goto error;
2950 space = isl_map_get_space(expr->acc.access);
2951 n = extract_nested(space, 0, expr->args, param2pos);
2952 isl_space_free(space);
2954 if (n < 0)
2955 goto error;
2957 expr->n_arg = n;
2958 return expr;
2959 error:
2960 pet_expr_free(expr);
2961 return NULL;
2964 /* Look for parameters in any access relation in "expr" that
2965 * refer to nested accesses. In particular, these are
2966 * parameters with no name.
2968 * If there are any such parameters, then the domain of the access
2969 * relation, which is still [] at this point, is replaced by
2970 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2971 * (after identifying identical nested accesses).
2972 * The parameters are then equated to the corresponding t dimensions
2973 * and subsequently projected out.
2974 * param2pos maps the position of the parameter to the position
2975 * of the corresponding t dimension.
2977 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
2979 int n;
2980 int nparam;
2981 int n_in;
2982 isl_space *dim;
2983 isl_map *map;
2984 std::map<int,int> param2pos;
2986 if (!expr)
2987 return expr;
2989 for (int i = 0; i < expr->n_arg; ++i) {
2990 expr->args[i] = resolve_nested(expr->args[i]);
2991 if (!expr->args[i]) {
2992 pet_expr_free(expr);
2993 return NULL;
2997 if (expr->type != pet_expr_access)
2998 return expr;
3000 n = n_nested_parameter(expr->acc.access);
3001 if (n == 0)
3002 return expr;
3004 expr = extract_nested(expr, n, param2pos);
3005 if (!expr)
3006 return NULL;
3008 n = expr->n_arg;
3009 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
3010 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
3011 dim = isl_map_get_space(expr->acc.access);
3012 dim = isl_space_domain(dim);
3013 dim = isl_space_from_domain(dim);
3014 dim = isl_space_add_dims(dim, isl_dim_out, n);
3015 map = isl_map_universe(dim);
3016 map = isl_map_domain_map(map);
3017 map = isl_map_reverse(map);
3018 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
3020 for (int i = nparam - 1; i >= 0; --i) {
3021 isl_id *id = isl_map_get_dim_id(expr->acc.access,
3022 isl_dim_param, i);
3023 if (!is_nested_parameter(id)) {
3024 isl_id_free(id);
3025 continue;
3028 expr->acc.access = isl_map_equate(expr->acc.access,
3029 isl_dim_param, i, isl_dim_in,
3030 n_in + param2pos[i]);
3031 expr->acc.access = isl_map_project_out(expr->acc.access,
3032 isl_dim_param, i, 1);
3034 isl_id_free(id);
3037 return expr;
3038 error:
3039 pet_expr_free(expr);
3040 return NULL;
3043 /* Convert a top-level pet_expr to a pet_scop with one statement.
3044 * This mainly involves resolving nested expression parameters
3045 * and setting the name of the iteration space.
3046 * The name is given by "label" if it is non-NULL. Otherwise,
3047 * it is of the form S_<n_stmt>.
3049 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
3050 __isl_take isl_id *label)
3052 struct pet_stmt *ps;
3053 SourceLocation loc = stmt->getLocStart();
3054 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3056 expr = resolve_nested(expr);
3057 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
3058 return pet_scop_from_pet_stmt(ctx, ps);
3061 /* Check if we can extract an affine expression from "expr".
3062 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3063 * We turn on autodetection so that we won't generate any warnings
3064 * and turn off nesting, so that we won't accept any non-affine constructs.
3066 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3068 isl_pw_aff *pwaff;
3069 int save_autodetect = options->autodetect;
3070 bool save_nesting = nesting_enabled;
3072 options->autodetect = 1;
3073 nesting_enabled = false;
3075 pwaff = extract_affine(expr);
3077 options->autodetect = save_autodetect;
3078 nesting_enabled = save_nesting;
3080 return pwaff;
3083 /* Check whether "expr" is an affine expression.
3085 bool PetScan::is_affine(Expr *expr)
3087 isl_pw_aff *pwaff;
3089 pwaff = try_extract_affine(expr);
3090 isl_pw_aff_free(pwaff);
3092 return pwaff != NULL;
3095 /* Check if we can extract an affine constraint from "expr".
3096 * Return the constraint as an isl_set if we can and NULL otherwise.
3097 * We turn on autodetection so that we won't generate any warnings
3098 * and turn off nesting, so that we won't accept any non-affine constructs.
3100 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3102 isl_pw_aff *cond;
3103 int save_autodetect = options->autodetect;
3104 bool save_nesting = nesting_enabled;
3106 options->autodetect = 1;
3107 nesting_enabled = false;
3109 cond = extract_condition(expr);
3111 options->autodetect = save_autodetect;
3112 nesting_enabled = save_nesting;
3114 return cond;
3117 /* Check whether "expr" is an affine constraint.
3119 bool PetScan::is_affine_condition(Expr *expr)
3121 isl_pw_aff *cond;
3123 cond = try_extract_affine_condition(expr);
3124 isl_pw_aff_free(cond);
3126 return cond != NULL;
3129 /* Check if we can extract a condition from "expr".
3130 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3131 * If allow_nested is set, then the condition may involve parameters
3132 * corresponding to nested accesses.
3133 * We turn on autodetection so that we won't generate any warnings.
3135 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3137 isl_pw_aff *cond;
3138 int save_autodetect = options->autodetect;
3139 bool save_nesting = nesting_enabled;
3141 options->autodetect = 1;
3142 nesting_enabled = allow_nested;
3143 cond = extract_condition(expr);
3145 options->autodetect = save_autodetect;
3146 nesting_enabled = save_nesting;
3148 return cond;
3151 /* If the top-level expression of "stmt" is an assignment, then
3152 * return that assignment as a BinaryOperator.
3153 * Otherwise return NULL.
3155 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3157 BinaryOperator *ass;
3159 if (!stmt)
3160 return NULL;
3161 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3162 return NULL;
3164 ass = cast<BinaryOperator>(stmt);
3165 if(ass->getOpcode() != BO_Assign)
3166 return NULL;
3168 return ass;
3171 /* Check if the given if statement is a conditional assignement
3172 * with a non-affine condition. If so, construct a pet_scop
3173 * corresponding to this conditional assignment. Otherwise return NULL.
3175 * In particular we check if "stmt" is of the form
3177 * if (condition)
3178 * a = f(...);
3179 * else
3180 * a = g(...);
3182 * where a is some array or scalar access.
3183 * The constructed pet_scop then corresponds to the expression
3185 * a = condition ? f(...) : g(...)
3187 * All access relations in f(...) are intersected with condition
3188 * while all access relation in g(...) are intersected with the complement.
3190 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3192 BinaryOperator *ass_then, *ass_else;
3193 isl_map *write_then, *write_else;
3194 isl_set *cond, *comp;
3195 isl_map *map;
3196 isl_pw_aff *pa;
3197 int equal;
3198 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3199 bool save_nesting = nesting_enabled;
3201 if (!options->detect_conditional_assignment)
3202 return NULL;
3204 ass_then = top_assignment_or_null(stmt->getThen());
3205 ass_else = top_assignment_or_null(stmt->getElse());
3207 if (!ass_then || !ass_else)
3208 return NULL;
3210 if (is_affine_condition(stmt->getCond()))
3211 return NULL;
3213 write_then = extract_access(ass_then->getLHS());
3214 write_else = extract_access(ass_else->getLHS());
3216 equal = isl_map_is_equal(write_then, write_else);
3217 isl_map_free(write_else);
3218 if (equal < 0 || !equal) {
3219 isl_map_free(write_then);
3220 return NULL;
3223 nesting_enabled = allow_nested;
3224 pa = extract_condition(stmt->getCond());
3225 nesting_enabled = save_nesting;
3226 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3227 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3228 map = isl_map_from_range(isl_set_from_pw_aff(pa));
3230 pe_cond = pet_expr_from_access(map);
3232 pe_then = extract_expr(ass_then->getRHS());
3233 pe_then = pet_expr_restrict(pe_then, cond);
3234 pe_else = extract_expr(ass_else->getRHS());
3235 pe_else = pet_expr_restrict(pe_else, comp);
3237 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
3238 pe_write = pet_expr_from_access(write_then);
3239 if (pe_write) {
3240 pe_write->acc.write = 1;
3241 pe_write->acc.read = 0;
3243 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
3244 return extract(stmt, pe);
3247 /* Create a pet_scop with a single statement evaluating "cond"
3248 * and writing the result to a virtual scalar, as expressed by
3249 * "access".
3251 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
3252 __isl_take isl_map *access)
3254 struct pet_expr *expr, *write;
3255 struct pet_stmt *ps;
3256 struct pet_scop *scop;
3257 SourceLocation loc = cond->getLocStart();
3258 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3260 write = pet_expr_from_access(access);
3261 if (write) {
3262 write->acc.write = 1;
3263 write->acc.read = 0;
3265 expr = extract_expr(cond);
3266 expr = resolve_nested(expr);
3267 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
3268 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
3269 scop = pet_scop_from_pet_stmt(ctx, ps);
3270 scop = resolve_nested(scop);
3272 return scop;
3275 extern "C" {
3276 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
3277 void *user);
3280 /* Apply the map pointed to by "user" to the domain of the access
3281 * relation, thereby embedding it in the range of the map.
3282 * The domain of both relations is the zero-dimensional domain.
3284 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
3286 isl_map *map = (isl_map *) user;
3288 return isl_map_apply_domain(access, isl_map_copy(map));
3291 /* Apply "map" to all access relations in "expr".
3293 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
3295 return pet_expr_foreach_access(expr, &embed_access, map);
3298 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3300 static int n_nested_parameter(__isl_keep isl_set *set)
3302 isl_space *space;
3303 int n;
3305 space = isl_set_get_space(set);
3306 n = n_nested_parameter(space);
3307 isl_space_free(space);
3309 return n;
3312 /* Remove all parameters from "map" that refer to nested accesses.
3314 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
3316 int nparam;
3317 isl_space *space;
3319 space = isl_map_get_space(map);
3320 nparam = isl_space_dim(space, isl_dim_param);
3321 for (int i = nparam - 1; i >= 0; --i)
3322 if (is_nested_parameter(space, i))
3323 map = isl_map_project_out(map, isl_dim_param, i, 1);
3324 isl_space_free(space);
3326 return map;
3329 extern "C" {
3330 static __isl_give isl_map *access_remove_nested_parameters(
3331 __isl_take isl_map *access, void *user);
3334 static __isl_give isl_map *access_remove_nested_parameters(
3335 __isl_take isl_map *access, void *user)
3337 return remove_nested_parameters(access);
3340 /* Remove all nested access parameters from the schedule and all
3341 * accesses of "stmt".
3342 * There is no need to remove them from the domain as these parameters
3343 * have already been removed from the domain when this function is called.
3345 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
3347 if (!stmt)
3348 return NULL;
3349 stmt->schedule = remove_nested_parameters(stmt->schedule);
3350 stmt->body = pet_expr_foreach_access(stmt->body,
3351 &access_remove_nested_parameters, NULL);
3352 if (!stmt->schedule || !stmt->body)
3353 goto error;
3354 for (int i = 0; i < stmt->n_arg; ++i) {
3355 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
3356 &access_remove_nested_parameters, NULL);
3357 if (!stmt->args[i])
3358 goto error;
3361 return stmt;
3362 error:
3363 pet_stmt_free(stmt);
3364 return NULL;
3367 /* For each nested access parameter in the domain of "stmt",
3368 * construct a corresponding pet_expr, place it before the original
3369 * elements in stmt->args and record its position in "param2pos".
3370 * n is the number of nested access parameters.
3372 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3373 std::map<int,int> &param2pos)
3375 int i;
3376 isl_space *space;
3377 int n_arg;
3378 struct pet_expr **args;
3380 n_arg = stmt->n_arg;
3381 args = isl_calloc_array(ctx, struct pet_expr *, n + n_arg);
3382 if (!args)
3383 goto error;
3385 space = isl_set_get_space(stmt->domain);
3386 n_arg = extract_nested(space, 0, args, param2pos);
3387 isl_space_free(space);
3389 if (n_arg < 0)
3390 goto error;
3392 for (i = 0; i < stmt->n_arg; ++i)
3393 args[n_arg + i] = stmt->args[i];
3394 free(stmt->args);
3395 stmt->args = args;
3396 stmt->n_arg += n_arg;
3398 return stmt;
3399 error:
3400 if (args) {
3401 for (i = 0; i < n; ++i)
3402 pet_expr_free(args[i]);
3403 free(args);
3405 pet_stmt_free(stmt);
3406 return NULL;
3409 /* Check whether any of the arguments i of "stmt" starting at position "n"
3410 * is equal to one of the first "n" arguments j.
3411 * If so, combine the constraints on arguments i and j and remove
3412 * argument i.
3414 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3416 int i, j;
3417 isl_map *map;
3419 if (!stmt)
3420 return NULL;
3421 if (n == 0)
3422 return stmt;
3423 if (n == stmt->n_arg)
3424 return stmt;
3426 map = isl_set_unwrap(stmt->domain);
3428 for (i = stmt->n_arg - 1; i >= n; --i) {
3429 for (j = 0; j < n; ++j)
3430 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3431 break;
3432 if (j >= n)
3433 continue;
3435 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3436 map = isl_map_project_out(map, isl_dim_out, i, 1);
3438 pet_expr_free(stmt->args[i]);
3439 for (j = i; j + 1 < stmt->n_arg; ++j)
3440 stmt->args[j] = stmt->args[j + 1];
3441 stmt->n_arg--;
3444 stmt->domain = isl_map_wrap(map);
3445 if (!stmt->domain)
3446 goto error;
3447 return stmt;
3448 error:
3449 pet_stmt_free(stmt);
3450 return NULL;
3453 /* Look for parameters in the iteration domain of "stmt" that
3454 * refer to nested accesses. In particular, these are
3455 * parameters with no name.
3457 * If there are any such parameters, then as many extra variables
3458 * (after identifying identical nested accesses) are inserted in the
3459 * range of the map wrapped inside the domain, before the original variables.
3460 * If the original domain is not a wrapped map, then a new wrapped
3461 * map is created with zero output dimensions.
3462 * The parameters are then equated to the corresponding output dimensions
3463 * and subsequently projected out, from the iteration domain,
3464 * the schedule and the access relations.
3465 * For each of the output dimensions, a corresponding argument
3466 * expression is inserted. Initially they are created with
3467 * a zero-dimensional domain, so they have to be embedded
3468 * in the current iteration domain.
3469 * param2pos maps the position of the parameter to the position
3470 * of the corresponding output dimension in the wrapped map.
3472 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3474 int n;
3475 int nparam;
3476 unsigned n_arg;
3477 isl_map *map;
3478 std::map<int,int> param2pos;
3480 if (!stmt)
3481 return NULL;
3483 n = n_nested_parameter(stmt->domain);
3484 if (n == 0)
3485 return stmt;
3487 n_arg = stmt->n_arg;
3488 stmt = extract_nested(stmt, n, param2pos);
3489 if (!stmt)
3490 return NULL;
3492 n = stmt->n_arg - n_arg;
3493 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3494 if (isl_set_is_wrapping(stmt->domain))
3495 map = isl_set_unwrap(stmt->domain);
3496 else
3497 map = isl_map_from_domain(stmt->domain);
3498 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3500 for (int i = nparam - 1; i >= 0; --i) {
3501 isl_id *id;
3503 if (!is_nested_parameter(map, i))
3504 continue;
3506 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
3507 isl_dim_out);
3508 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3509 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3510 param2pos[i]);
3511 map = isl_map_project_out(map, isl_dim_param, i, 1);
3514 stmt->domain = isl_map_wrap(map);
3516 map = isl_set_unwrap(isl_set_copy(stmt->domain));
3517 map = isl_map_from_range(isl_map_domain(map));
3518 for (int pos = 0; pos < n; ++pos)
3519 stmt->args[pos] = embed(stmt->args[pos], map);
3520 isl_map_free(map);
3522 stmt = remove_nested_parameters(stmt);
3523 stmt = remove_duplicate_arguments(stmt, n);
3525 return stmt;
3526 error:
3527 pet_stmt_free(stmt);
3528 return NULL;
3531 /* For each statement in "scop", move the parameters that correspond
3532 * to nested access into the ranges of the domains and create
3533 * corresponding argument expressions.
3535 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3537 if (!scop)
3538 return NULL;
3540 for (int i = 0; i < scop->n_stmt; ++i) {
3541 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3542 if (!scop->stmts[i])
3543 goto error;
3546 return scop;
3547 error:
3548 pet_scop_free(scop);
3549 return NULL;
3552 /* Given an access expression "expr", is the variable accessed by
3553 * "expr" assigned anywhere inside "scop"?
3555 static bool is_assigned(pet_expr *expr, pet_scop *scop)
3557 bool assigned = false;
3558 isl_id *id;
3560 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
3561 assigned = pet_scop_writes(scop, id);
3562 isl_id_free(id);
3564 return assigned;
3567 /* Are all nested access parameters in "pa" allowed given "scop".
3568 * In particular, is none of them written by anywhere inside "scop".
3570 * If "scop" has any skip conditions, then no nested access parameters
3571 * are allowed. In particular, if there is any nested access in a guard
3572 * for a piece of code containing a "continue", then we want to introduce
3573 * a separate statement for evaluating this guard so that we can express
3574 * that the result is false for all previous iterations.
3576 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3578 int nparam;
3580 if (!scop)
3581 return true;
3583 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3584 for (int i = 0; i < nparam; ++i) {
3585 Expr *nested;
3586 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3587 pet_expr *expr;
3588 bool allowed;
3590 if (!is_nested_parameter(id)) {
3591 isl_id_free(id);
3592 continue;
3595 if (pet_scop_has_skip(scop, pet_skip_now)) {
3596 isl_id_free(id);
3597 return false;
3600 nested = (Expr *) isl_id_get_user(id);
3601 expr = extract_expr(nested);
3602 allowed = expr && expr->type == pet_expr_access &&
3603 !is_assigned(expr, scop);
3605 pet_expr_free(expr);
3606 isl_id_free(id);
3608 if (!allowed)
3609 return false;
3612 return true;
3615 /* Do we need to construct a skip condition of the given type
3616 * on an if statement, given that the if condition is non-affine?
3618 * pet_scop_filter_skip can only handle the case where the if condition
3619 * holds (the then branch) and the skip condition is universal.
3620 * In any other case, we need to construct a new skip condition.
3622 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3623 bool have_else, enum pet_skip type)
3625 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
3626 return true;
3627 if (scop_then && pet_scop_has_skip(scop_then, type) &&
3628 !pet_scop_has_universal_skip(scop_then, type))
3629 return true;
3630 return false;
3633 /* Do we need to construct a skip condition of the given type
3634 * on an if statement, given that the if condition is affine?
3636 * There is no need to construct a new skip condition if all
3637 * the skip conditions are affine.
3639 static bool need_skip_aff(struct pet_scop *scop_then,
3640 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
3642 if (scop_then && pet_scop_has_var_skip(scop_then, type))
3643 return true;
3644 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
3645 return true;
3646 return false;
3649 /* Do we need to construct a skip condition of the given type
3650 * on an if statement?
3652 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3653 bool have_else, enum pet_skip type, bool affine)
3655 if (affine)
3656 return need_skip_aff(scop_then, scop_else, have_else, type);
3657 else
3658 return need_skip(scop_then, scop_else, have_else, type);
3661 /* Construct an affine expression pet_expr that is evaluates
3662 * to the constant "val".
3664 static struct pet_expr *universally(isl_ctx *ctx, int val)
3666 isl_space *space;
3667 isl_map *map;
3669 space = isl_space_alloc(ctx, 0, 0, 1);
3670 map = isl_map_universe(space);
3671 map = isl_map_fix_si(map, isl_dim_out, 0, val);
3673 return pet_expr_from_access(map);
3676 /* Construct an affine expression pet_expr that is evaluates
3677 * to the constant 1.
3679 static struct pet_expr *universally_true(isl_ctx *ctx)
3681 return universally(ctx, 1);
3684 /* Construct an affine expression pet_expr that is evaluates
3685 * to the constant 0.
3687 static struct pet_expr *universally_false(isl_ctx *ctx)
3689 return universally(ctx, 0);
3692 /* Given an access relation "test_access" for the if condition,
3693 * an access relation "skip_access" for the skip condition and
3694 * scops for the then and else branches, construct a scop for
3695 * computing "skip_access".
3697 * The computed scop contains a single statement that essentially does
3699 * skip_cond = test_cond ? skip_cond_then : skip_cond_else
3701 * If the skip conditions of the then and/or else branch are not affine,
3702 * then they need to be filtered by test_access.
3703 * If they are missing, then this means the skip condition is false.
3705 * Since we are constructing a skip condition for the if statement,
3706 * the skip conditions on the then and else branches are removed.
3708 static struct pet_scop *extract_skip(PetScan *scan,
3709 __isl_take isl_map *test_access, __isl_take isl_map *skip_access,
3710 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
3711 enum pet_skip type)
3713 struct pet_expr *expr_then, *expr_else, *expr, *expr_skip;
3714 struct pet_stmt *stmt;
3715 struct pet_scop *scop;
3716 isl_ctx *ctx = scan->ctx;
3718 if (!scop_then)
3719 goto error;
3720 if (have_else && !scop_else)
3721 goto error;
3723 if (pet_scop_has_skip(scop_then, type)) {
3724 expr_then = pet_scop_get_skip_expr(scop_then, type);
3725 pet_scop_reset_skip(scop_then, type);
3726 if (!pet_expr_is_affine(expr_then))
3727 expr_then = pet_expr_filter(expr_then,
3728 isl_map_copy(test_access), 1);
3729 } else
3730 expr_then = universally_false(ctx);
3732 if (have_else && pet_scop_has_skip(scop_else, type)) {
3733 expr_else = pet_scop_get_skip_expr(scop_else, type);
3734 pet_scop_reset_skip(scop_else, type);
3735 if (!pet_expr_is_affine(expr_else))
3736 expr_else = pet_expr_filter(expr_else,
3737 isl_map_copy(test_access), 0);
3738 } else
3739 expr_else = universally_false(ctx);
3741 expr = pet_expr_from_access(test_access);
3742 expr = pet_expr_new_ternary(ctx, expr, expr_then, expr_else);
3743 expr_skip = pet_expr_from_access(isl_map_copy(skip_access));
3744 if (expr_skip) {
3745 expr_skip->acc.write = 1;
3746 expr_skip->acc.read = 0;
3748 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
3749 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, scan->n_stmt++, expr);
3751 scop = pet_scop_from_pet_stmt(ctx, stmt);
3752 scop = scop_add_array(scop, skip_access, scan->ast_context);
3753 isl_map_free(skip_access);
3755 return scop;
3756 error:
3757 isl_map_free(test_access);
3758 isl_map_free(skip_access);
3759 return NULL;
3762 /* Is scop's skip_now condition equal to its skip_later condition?
3763 * In particular, this means that it either has no skip_now condition
3764 * or both a skip_now and a skip_later condition (that are equal to each other).
3766 static bool skip_equals_skip_later(struct pet_scop *scop)
3768 int has_skip_now, has_skip_later;
3769 int equal;
3770 isl_set *skip_now, *skip_later;
3772 if (!scop)
3773 return false;
3774 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
3775 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
3776 if (has_skip_now != has_skip_later)
3777 return false;
3778 if (!has_skip_now)
3779 return true;
3781 skip_now = pet_scop_get_skip(scop, pet_skip_now);
3782 skip_later = pet_scop_get_skip(scop, pet_skip_later);
3783 equal = isl_set_is_equal(skip_now, skip_later);
3784 isl_set_free(skip_now);
3785 isl_set_free(skip_later);
3787 return equal;
3790 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
3792 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
3794 pet_scop_reset_skip(scop1, pet_skip_later);
3795 pet_scop_reset_skip(scop2, pet_skip_later);
3798 /* Structure that handles the construction of skip conditions.
3800 * scop_then and scop_else represent the then and else branches
3801 * of the if statement
3803 * skip[type] is true if we need to construct a skip condition of that type
3804 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
3805 * are equal to each other
3806 * access[type] is the virtual array representing the skip condition
3807 * scop[type] is a scop for computing the skip condition
3809 struct pet_skip_info {
3810 isl_ctx *ctx;
3812 bool skip[2];
3813 bool equal;
3814 isl_map *access[2];
3815 struct pet_scop *scop[2];
3817 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
3819 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
3822 /* Structure that handles the construction of skip conditions on if statements.
3824 * scop_then and scop_else represent the then and else branches
3825 * of the if statement
3827 struct pet_skip_info_if : public pet_skip_info {
3828 struct pet_scop *scop_then, *scop_else;
3829 bool have_else;
3831 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
3832 struct pet_scop *scop_else, bool have_else, bool affine);
3833 void extract(PetScan *scan, __isl_keep isl_map *access,
3834 enum pet_skip type);
3835 void extract(PetScan *scan, __isl_keep isl_map *access);
3836 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
3837 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
3838 int offset);
3839 struct pet_scop *add(struct pet_scop *scop, int offset);
3842 /* Initialize a pet_skip_info_if structure based on the then and else branches
3843 * and based on whether the if condition is affine or not.
3845 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
3846 struct pet_scop *scop_else, bool have_else, bool affine) :
3847 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
3848 have_else(have_else)
3850 skip[pet_skip_now] =
3851 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
3852 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
3853 (!have_else || skip_equals_skip_later(scop_else));
3854 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
3855 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
3858 /* If we need to construct a skip condition of the given type,
3859 * then do so now.
3861 * "map" represents the if condition.
3863 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_map *map,
3864 enum pet_skip type)
3866 if (!skip[type])
3867 return;
3869 access[type] = create_test_access(isl_map_get_ctx(map), scan->n_test++);
3870 scop[type] = extract_skip(scan, isl_map_copy(map),
3871 isl_map_copy(access[type]),
3872 scop_then, scop_else, have_else, type);
3875 /* Construct the required skip conditions, given the if condition "map".
3877 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_map *map)
3879 extract(scan, map, pet_skip_now);
3880 extract(scan, map, pet_skip_later);
3881 if (equal)
3882 drop_skip_later(scop_then, scop_else);
3885 /* Construct the required skip conditions, given the if condition "cond".
3887 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
3889 isl_set *test_set;
3890 isl_map *test;
3892 if (!skip[pet_skip_now] && !skip[pet_skip_later])
3893 return;
3895 test_set = isl_set_from_pw_aff(isl_pw_aff_copy(cond));
3896 test = isl_map_from_range(test_set);
3897 extract(scan, test);
3898 isl_map_free(test);
3901 /* Add the computed skip condition of the give type to "main" and
3902 * add the scop for computing the condition at the given offset.
3904 * If equal is set, then we only computed a skip condition for pet_skip_now,
3905 * but we also need to set it as main's pet_skip_later.
3907 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
3908 enum pet_skip type, int offset)
3910 isl_set *skip_set;
3912 if (!skip[type])
3913 return main;
3915 skip_set = isl_map_range(access[type]);
3916 access[type] = NULL;
3917 scop[type] = pet_scop_prefix(scop[type], offset);
3918 main = pet_scop_add_par(ctx, main, scop[type]);
3919 scop[type] = NULL;
3921 if (equal)
3922 main = pet_scop_set_skip(main, pet_skip_later,
3923 isl_set_copy(skip_set));
3925 main = pet_scop_set_skip(main, type, skip_set);
3927 return main;
3930 /* Add the computed skip conditions to "main" and
3931 * add the scops for computing the conditions at the given offset.
3933 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
3935 scop = add(scop, pet_skip_now, offset);
3936 scop = add(scop, pet_skip_later, offset);
3938 return scop;
3941 /* Construct a pet_scop for a non-affine if statement.
3943 * We create a separate statement that writes the result
3944 * of the non-affine condition to a virtual scalar.
3945 * A constraint requiring the value of this virtual scalar to be one
3946 * is added to the iteration domains of the then branch.
3947 * Similarly, a constraint requiring the value of this virtual scalar
3948 * to be zero is added to the iteration domains of the else branch, if any.
3949 * We adjust the schedules to ensure that the virtual scalar is written
3950 * before it is read.
3952 * If there are any breaks or continues in the then and/or else
3953 * branches, then we may have to compute a new skip condition.
3954 * This is handled using a pet_skip_info_if object.
3955 * On initialization, the object checks if skip conditions need
3956 * to be computed. If so, it does so in "extract" and adds them in "add".
3958 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
3959 struct pet_scop *scop_then, struct pet_scop *scop_else,
3960 bool have_else, int stmt_id)
3962 struct pet_scop *scop;
3963 isl_map *test_access;
3964 int save_n_stmt = n_stmt;
3966 test_access = create_test_access(ctx, n_test++);
3967 n_stmt = stmt_id;
3968 scop = extract_non_affine_condition(cond, isl_map_copy(test_access));
3969 n_stmt = save_n_stmt;
3970 scop = scop_add_array(scop, test_access, ast_context);
3972 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
3973 skip.extract(this, test_access);
3975 scop = pet_scop_prefix(scop, 0);
3976 scop_then = pet_scop_prefix(scop_then, 1);
3977 scop_then = pet_scop_filter(scop_then, isl_map_copy(test_access), 1);
3978 if (have_else) {
3979 scop_else = pet_scop_prefix(scop_else, 1);
3980 scop_else = pet_scop_filter(scop_else, test_access, 0);
3981 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
3982 } else
3983 isl_map_free(test_access);
3985 scop = pet_scop_add_seq(ctx, scop, scop_then);
3987 scop = skip.add(scop, 2);
3989 return scop;
3992 /* Construct a pet_scop for an if statement.
3994 * If the condition fits the pattern of a conditional assignment,
3995 * then it is handled by extract_conditional_assignment.
3996 * Otherwise, we do the following.
3998 * If the condition is affine, then the condition is added
3999 * to the iteration domains of the then branch, while the
4000 * opposite of the condition in added to the iteration domains
4001 * of the else branch, if any.
4002 * We allow the condition to be dynamic, i.e., to refer to
4003 * scalars or array elements that may be written to outside
4004 * of the given if statement. These nested accesses are then represented
4005 * as output dimensions in the wrapping iteration domain.
4006 * If it also written _inside_ the then or else branch, then
4007 * we treat the condition as non-affine.
4008 * As explained in extract_non_affine_if, this will introduce
4009 * an extra statement.
4010 * For aesthetic reasons, we want this statement to have a statement
4011 * number that is lower than those of the then and else branches.
4012 * In order to evaluate if will need such a statement, however, we
4013 * first construct scops for the then and else branches.
4014 * We therefore reserve a statement number if we might have to
4015 * introduce such an extra statement.
4017 * If the condition is not affine, then the scop is created in
4018 * extract_non_affine_if.
4020 * If there are any breaks or continues in the then and/or else
4021 * branches, then we may have to compute a new skip condition.
4022 * This is handled using a pet_skip_info_if object.
4023 * On initialization, the object checks if skip conditions need
4024 * to be computed. If so, it does so in "extract" and adds them in "add".
4026 struct pet_scop *PetScan::extract(IfStmt *stmt)
4028 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4029 isl_pw_aff *cond;
4030 int stmt_id;
4031 isl_set *set;
4032 isl_set *valid;
4034 scop = extract_conditional_assignment(stmt);
4035 if (scop)
4036 return scop;
4038 cond = try_extract_nested_condition(stmt->getCond());
4039 if (allow_nested && (!cond || has_nested(cond)))
4040 stmt_id = n_stmt++;
4043 assigned_value_cache cache(assigned_value);
4044 scop_then = extract(stmt->getThen());
4047 if (stmt->getElse()) {
4048 assigned_value_cache cache(assigned_value);
4049 scop_else = extract(stmt->getElse());
4050 if (options->autodetect) {
4051 if (scop_then && !scop_else) {
4052 partial = true;
4053 isl_pw_aff_free(cond);
4054 return scop_then;
4056 if (!scop_then && scop_else) {
4057 partial = true;
4058 isl_pw_aff_free(cond);
4059 return scop_else;
4064 if (cond &&
4065 (!is_nested_allowed(cond, scop_then) ||
4066 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4067 isl_pw_aff_free(cond);
4068 cond = NULL;
4070 if (allow_nested && !cond)
4071 return extract_non_affine_if(stmt->getCond(), scop_then,
4072 scop_else, stmt->getElse(), stmt_id);
4074 if (!cond)
4075 cond = extract_condition(stmt->getCond());
4077 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4078 skip.extract(this, cond);
4080 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4081 set = isl_pw_aff_non_zero_set(cond);
4082 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4084 if (stmt->getElse()) {
4085 set = isl_set_subtract(isl_set_copy(valid), set);
4086 scop_else = pet_scop_restrict(scop_else, set);
4087 scop = pet_scop_add_par(ctx, scop, scop_else);
4088 } else
4089 isl_set_free(set);
4090 scop = resolve_nested(scop);
4091 scop = pet_scop_restrict_context(scop, valid);
4093 if (skip)
4094 scop = pet_scop_prefix(scop, 0);
4095 scop = skip.add(scop, 1);
4097 return scop;
4100 /* Try and construct a pet_scop for a label statement.
4101 * We currently only allow labels on expression statements.
4103 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4105 isl_id *label;
4106 Stmt *sub;
4108 sub = stmt->getSubStmt();
4109 if (!isa<Expr>(sub)) {
4110 unsupported(stmt);
4111 return NULL;
4114 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4116 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4119 /* Construct a pet_scop for a continue statement.
4121 * We simply create an empty scop with a universal pet_skip_now
4122 * skip condition. This skip condition will then be taken into
4123 * account by the enclosing loop construct, possibly after
4124 * being incorporated into outer skip conditions.
4126 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4128 pet_scop *scop;
4129 isl_space *space;
4130 isl_set *set;
4132 scop = pet_scop_empty(ctx);
4133 if (!scop)
4134 return NULL;
4136 space = isl_space_set_alloc(ctx, 0, 1);
4137 set = isl_set_universe(space);
4138 set = isl_set_fix_si(set, isl_dim_set, 0, 1);
4139 scop = pet_scop_set_skip(scop, pet_skip_now, set);
4141 return scop;
4144 /* Construct a pet_scop for a break statement.
4146 * We simply create an empty scop with both a universal pet_skip_now
4147 * skip condition and a universal pet_skip_later skip condition.
4148 * These skip conditions will then be taken into
4149 * account by the enclosing loop construct, possibly after
4150 * being incorporated into outer skip conditions.
4152 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4154 pet_scop *scop;
4155 isl_space *space;
4156 isl_set *set;
4158 scop = pet_scop_empty(ctx);
4159 if (!scop)
4160 return NULL;
4162 space = isl_space_set_alloc(ctx, 0, 1);
4163 set = isl_set_universe(space);
4164 set = isl_set_fix_si(set, isl_dim_set, 0, 1);
4165 scop = pet_scop_set_skip(scop, pet_skip_now, isl_set_copy(set));
4166 scop = pet_scop_set_skip(scop, pet_skip_later, set);
4168 return scop;
4171 /* Try and construct a pet_scop corresponding to "stmt".
4173 struct pet_scop *PetScan::extract(Stmt *stmt)
4175 if (isa<Expr>(stmt))
4176 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4178 switch (stmt->getStmtClass()) {
4179 case Stmt::WhileStmtClass:
4180 return extract(cast<WhileStmt>(stmt));
4181 case Stmt::ForStmtClass:
4182 return extract_for(cast<ForStmt>(stmt));
4183 case Stmt::IfStmtClass:
4184 return extract(cast<IfStmt>(stmt));
4185 case Stmt::CompoundStmtClass:
4186 return extract(cast<CompoundStmt>(stmt));
4187 case Stmt::LabelStmtClass:
4188 return extract(cast<LabelStmt>(stmt));
4189 case Stmt::ContinueStmtClass:
4190 return extract(cast<ContinueStmt>(stmt));
4191 case Stmt::BreakStmtClass:
4192 return extract(cast<BreakStmt>(stmt));
4193 default:
4194 unsupported(stmt);
4197 return NULL;
4200 /* Do we need to construct a skip condition of the given type
4201 * on a sequence of statements?
4203 * There is no need to construct a new skip condition if only
4204 * only of the two statements has a skip condition or if both
4205 * of their skip conditions are affine.
4207 * In principle we also don't need a new continuation variable if
4208 * the continuation of scop2 is affine, but then we would need
4209 * to allow more complicated forms of continuations.
4211 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4212 enum pet_skip type)
4214 if (!scop1 || !pet_scop_has_skip(scop1, type))
4215 return false;
4216 if (!scop2 || !pet_scop_has_skip(scop2, type))
4217 return false;
4218 if (pet_scop_has_affine_skip(scop1, type) &&
4219 pet_scop_has_affine_skip(scop2, type))
4220 return false;
4221 return true;
4224 /* Construct a scop for computing the skip condition of the given type and
4225 * with access relation "skip_access" for a sequence of two scops "scop1"
4226 * and "scop2".
4228 * The computed scop contains a single statement that essentially does
4230 * skip_cond = skip_cond_1 ? 1 : skip_cond_2
4232 * or, in other words, skip_cond1 || skip_cond2.
4233 * In this expression, skip_cond_2 is filtered to reflect that it is
4234 * only evaluated when skip_cond_1 is false.
4236 * The skip condition on scop1 is not removed because it still needs
4237 * to be applied to scop2 when these two scops are combined.
4239 static struct pet_scop *extract_skip_seq(PetScan *ps,
4240 __isl_take isl_map *skip_access,
4241 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4243 isl_map *access;
4244 struct pet_expr *expr1, *expr2, *expr, *expr_skip;
4245 struct pet_stmt *stmt;
4246 struct pet_scop *scop;
4247 isl_ctx *ctx = ps->ctx;
4249 if (!scop1 || !scop2)
4250 goto error;
4252 expr1 = pet_scop_get_skip_expr(scop1, type);
4253 expr2 = pet_scop_get_skip_expr(scop2, type);
4254 pet_scop_reset_skip(scop2, type);
4256 expr2 = pet_expr_filter(expr2, isl_map_copy(expr1->acc.access), 0);
4258 expr = universally_true(ctx);
4259 expr = pet_expr_new_ternary(ctx, expr1, expr, expr2);
4260 expr_skip = pet_expr_from_access(isl_map_copy(skip_access));
4261 if (expr_skip) {
4262 expr_skip->acc.write = 1;
4263 expr_skip->acc.read = 0;
4265 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4266 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, ps->n_stmt++, expr);
4268 scop = pet_scop_from_pet_stmt(ctx, stmt);
4269 scop = scop_add_array(scop, skip_access, ps->ast_context);
4270 isl_map_free(skip_access);
4272 return scop;
4273 error:
4274 isl_map_free(skip_access);
4275 return NULL;
4278 /* Structure that handles the construction of skip conditions
4279 * on sequences of statements.
4281 * scop1 and scop2 represent the two statements that are combined
4283 struct pet_skip_info_seq : public pet_skip_info {
4284 struct pet_scop *scop1, *scop2;
4286 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4287 struct pet_scop *scop2);
4288 void extract(PetScan *scan, enum pet_skip type);
4289 void extract(PetScan *scan);
4290 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4291 int offset);
4292 struct pet_scop *add(struct pet_scop *scop, int offset);
4295 /* Initialize a pet_skip_info_seq structure based on
4296 * on the two statements that are going to be combined.
4298 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4299 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
4301 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
4302 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
4303 skip_equals_skip_later(scop2);
4304 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4305 need_skip_seq(scop1, scop2, pet_skip_later);
4308 /* If we need to construct a skip condition of the given type,
4309 * then do so now.
4311 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
4313 if (!skip[type])
4314 return;
4316 access[type] = create_test_access(ctx, scan->n_test++);
4317 scop[type] = extract_skip_seq(scan, isl_map_copy(access[type]),
4318 scop1, scop2, type);
4321 /* Construct the required skip conditions.
4323 void pet_skip_info_seq::extract(PetScan *scan)
4325 extract(scan, pet_skip_now);
4326 extract(scan, pet_skip_later);
4327 if (equal)
4328 drop_skip_later(scop1, scop2);
4331 /* Add the computed skip condition of the give type to "main" and
4332 * add the scop for computing the condition at the given offset (the statement
4333 * number). Within this offset, the condition is computed at position 1
4334 * to ensure that it is computed after the corresponding statement.
4336 * If equal is set, then we only computed a skip condition for pet_skip_now,
4337 * but we also need to set it as main's pet_skip_later.
4339 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
4340 enum pet_skip type, int offset)
4342 isl_set *skip_set;
4344 if (!skip[type])
4345 return main;
4347 skip_set = isl_map_range(access[type]);
4348 access[type] = NULL;
4349 scop[type] = pet_scop_prefix(scop[type], 1);
4350 scop[type] = pet_scop_prefix(scop[type], offset);
4351 main = pet_scop_add_par(ctx, main, scop[type]);
4352 scop[type] = NULL;
4354 if (equal)
4355 main = pet_scop_set_skip(main, pet_skip_later,
4356 isl_set_copy(skip_set));
4358 main = pet_scop_set_skip(main, type, skip_set);
4360 return main;
4363 /* Add the computed skip conditions to "main" and
4364 * add the scops for computing the conditions at the given offset.
4366 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
4368 scop = add(scop, pet_skip_now, offset);
4369 scop = add(scop, pet_skip_later, offset);
4371 return scop;
4374 /* Try and construct a pet_scop corresponding to (part of)
4375 * a sequence of statements.
4377 * If there are any breaks or continues in the individual statements,
4378 * then we may have to compute a new skip condition.
4379 * This is handled using a pet_skip_info_seq object.
4380 * On initialization, the object checks if skip conditions need
4381 * to be computed. If so, it does so in "extract" and adds them in "add".
4383 struct pet_scop *PetScan::extract(StmtRange stmt_range)
4385 pet_scop *scop;
4386 StmtIterator i;
4387 int j;
4388 bool partial_range = false;
4390 scop = pet_scop_empty(ctx);
4391 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4392 Stmt *child = *i;
4393 struct pet_scop *scop_i;
4395 scop_i = extract(child);
4396 if (scop && partial) {
4397 pet_scop_free(scop_i);
4398 break;
4400 pet_skip_info_seq skip(ctx, scop, scop_i);
4401 skip.extract(this);
4402 if (skip)
4403 scop_i = pet_scop_prefix(scop_i, 0);
4404 scop_i = pet_scop_prefix(scop_i, j);
4405 if (options->autodetect) {
4406 if (scop_i)
4407 scop = pet_scop_add_seq(ctx, scop, scop_i);
4408 else
4409 partial_range = true;
4410 if (scop->n_stmt != 0 && !scop_i)
4411 partial = true;
4412 } else {
4413 scop = pet_scop_add_seq(ctx, scop, scop_i);
4416 scop = skip.add(scop, j);
4418 if (partial)
4419 break;
4422 if (scop && partial_range)
4423 partial = true;
4425 return scop;
4428 /* Return the file offset of the expansion location of "Loc".
4430 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
4432 return SM.getFileOffset(SM.getExpansionLoc(Loc));
4435 /* Check if the scop marked by the user is exactly this Stmt
4436 * or part of this Stmt.
4437 * If so, return a pet_scop corresponding to the marked region.
4438 * Otherwise, return NULL.
4440 struct pet_scop *PetScan::scan(Stmt *stmt)
4442 SourceManager &SM = PP.getSourceManager();
4443 unsigned start_off, end_off;
4445 start_off = getExpansionOffset(SM, stmt->getLocStart());
4446 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4448 if (start_off > loc.end)
4449 return NULL;
4450 if (end_off < loc.start)
4451 return NULL;
4452 if (start_off >= loc.start && end_off <= loc.end) {
4453 return extract(stmt);
4456 StmtIterator start;
4457 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4458 Stmt *child = *start;
4459 if (!child)
4460 continue;
4461 start_off = getExpansionOffset(SM, child->getLocStart());
4462 end_off = getExpansionOffset(SM, child->getLocEnd());
4463 if (start_off < loc.start && end_off > loc.end)
4464 return scan(child);
4465 if (start_off >= loc.start)
4466 break;
4469 StmtIterator end;
4470 for (end = start; end != stmt->child_end(); ++end) {
4471 Stmt *child = *end;
4472 start_off = SM.getFileOffset(child->getLocStart());
4473 if (start_off >= loc.end)
4474 break;
4477 return extract(StmtRange(start, end));
4480 /* Set the size of index "pos" of "array" to "size".
4481 * In particular, add a constraint of the form
4483 * i_pos < size
4485 * to array->extent and a constraint of the form
4487 * size >= 0
4489 * to array->context.
4491 static struct pet_array *update_size(struct pet_array *array, int pos,
4492 __isl_take isl_pw_aff *size)
4494 isl_set *valid;
4495 isl_set *univ;
4496 isl_set *bound;
4497 isl_space *dim;
4498 isl_aff *aff;
4499 isl_pw_aff *index;
4500 isl_id *id;
4502 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
4503 array->context = isl_set_intersect(array->context, valid);
4505 dim = isl_set_get_space(array->extent);
4506 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
4507 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
4508 univ = isl_set_universe(isl_aff_get_domain_space(aff));
4509 index = isl_pw_aff_alloc(univ, aff);
4511 size = isl_pw_aff_add_dims(size, isl_dim_in,
4512 isl_set_dim(array->extent, isl_dim_set));
4513 id = isl_set_get_tuple_id(array->extent);
4514 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
4515 bound = isl_pw_aff_lt_set(index, size);
4517 array->extent = isl_set_intersect(array->extent, bound);
4519 if (!array->context || !array->extent)
4520 goto error;
4522 return array;
4523 error:
4524 pet_array_free(array);
4525 return NULL;
4528 /* Figure out the size of the array at position "pos" and all
4529 * subsequent positions from "type" and update "array" accordingly.
4531 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
4532 const Type *type, int pos)
4534 const ArrayType *atype;
4535 isl_pw_aff *size;
4537 if (!array)
4538 return NULL;
4540 if (type->isPointerType()) {
4541 type = type->getPointeeType().getTypePtr();
4542 return set_upper_bounds(array, type, pos + 1);
4544 if (!type->isArrayType())
4545 return array;
4547 type = type->getCanonicalTypeInternal().getTypePtr();
4548 atype = cast<ArrayType>(type);
4550 if (type->isConstantArrayType()) {
4551 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
4552 size = extract_affine(ca->getSize());
4553 array = update_size(array, pos, size);
4554 } else if (type->isVariableArrayType()) {
4555 const VariableArrayType *vla = cast<VariableArrayType>(atype);
4556 size = extract_affine(vla->getSizeExpr());
4557 array = update_size(array, pos, size);
4560 type = atype->getElementType().getTypePtr();
4562 return set_upper_bounds(array, type, pos + 1);
4565 /* Is "T" the type of a variable length array with static size?
4567 static bool is_vla_with_static_size(QualType T)
4569 const VariableArrayType *vlatype;
4571 if (!T->isVariableArrayType())
4572 return false;
4573 vlatype = cast<VariableArrayType>(T);
4574 return vlatype->getSizeModifier() == VariableArrayType::Static;
4577 /* Return the type of "decl" as an array.
4579 * In particular, if "decl" is a parameter declaration that
4580 * is a variable length array with a static size, then
4581 * return the original type (i.e., the variable length array).
4582 * Otherwise, return the type of decl.
4584 static QualType get_array_type(ValueDecl *decl)
4586 ParmVarDecl *parm;
4587 QualType T;
4589 parm = dyn_cast<ParmVarDecl>(decl);
4590 if (!parm)
4591 return decl->getType();
4593 T = parm->getOriginalType();
4594 if (!is_vla_with_static_size(T))
4595 return decl->getType();
4596 return T;
4599 /* Construct and return a pet_array corresponding to the variable "decl".
4600 * In particular, initialize array->extent to
4602 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4604 * and then call set_upper_bounds to set the upper bounds on the indices
4605 * based on the type of the variable.
4607 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
4609 struct pet_array *array;
4610 QualType qt = get_array_type(decl);
4611 const Type *type = qt.getTypePtr();
4612 int depth = array_depth(type);
4613 QualType base = base_type(qt);
4614 string name;
4615 isl_id *id;
4616 isl_space *dim;
4618 array = isl_calloc_type(ctx, struct pet_array);
4619 if (!array)
4620 return NULL;
4622 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
4623 dim = isl_space_set_alloc(ctx, 0, depth);
4624 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
4626 array->extent = isl_set_nat_universe(dim);
4628 dim = isl_space_params_alloc(ctx, 0);
4629 array->context = isl_set_universe(dim);
4631 array = set_upper_bounds(array, type, 0);
4632 if (!array)
4633 return NULL;
4635 name = base.getAsString();
4636 array->element_type = strdup(name.c_str());
4637 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
4639 return array;
4642 /* Construct a list of pet_arrays, one for each array (or scalar)
4643 * accessed inside "scop", add this list to "scop" and return the result.
4645 * The context of "scop" is updated with the intersection of
4646 * the contexts of all arrays, i.e., constraints on the parameters
4647 * that ensure that the arrays have a valid (non-negative) size.
4649 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
4651 int i;
4652 set<ValueDecl *> arrays;
4653 set<ValueDecl *>::iterator it;
4654 int n_array;
4655 struct pet_array **scop_arrays;
4657 if (!scop)
4658 return NULL;
4660 pet_scop_collect_arrays(scop, arrays);
4661 if (arrays.size() == 0)
4662 return scop;
4664 n_array = scop->n_array;
4666 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
4667 n_array + arrays.size());
4668 if (!scop_arrays)
4669 goto error;
4670 scop->arrays = scop_arrays;
4672 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
4673 struct pet_array *array;
4674 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
4675 if (!scop->arrays[n_array + i])
4676 goto error;
4677 scop->n_array++;
4678 scop->context = isl_set_intersect(scop->context,
4679 isl_set_copy(array->context));
4680 if (!scop->context)
4681 goto error;
4684 return scop;
4685 error:
4686 pet_scop_free(scop);
4687 return NULL;
4690 /* Bound all parameters in scop->context to the possible values
4691 * of the corresponding C variable.
4693 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
4695 int n;
4697 if (!scop)
4698 return NULL;
4700 n = isl_set_dim(scop->context, isl_dim_param);
4701 for (int i = 0; i < n; ++i) {
4702 isl_id *id;
4703 ValueDecl *decl;
4705 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
4706 if (is_nested_parameter(id)) {
4707 isl_id_free(id);
4708 isl_die(isl_set_get_ctx(scop->context),
4709 isl_error_internal,
4710 "unresolved nested parameter", goto error);
4712 decl = (ValueDecl *) isl_id_get_user(id);
4713 isl_id_free(id);
4715 scop->context = set_parameter_bounds(scop->context, i, decl);
4717 if (!scop->context)
4718 goto error;
4721 return scop;
4722 error:
4723 pet_scop_free(scop);
4724 return NULL;
4727 /* Construct a pet_scop from the given function.
4729 struct pet_scop *PetScan::scan(FunctionDecl *fd)
4731 pet_scop *scop;
4732 Stmt *stmt;
4734 stmt = fd->getBody();
4736 if (options->autodetect)
4737 scop = extract(stmt);
4738 else
4739 scop = scan(stmt);
4740 scop = pet_scop_detect_parameter_accesses(scop);
4741 scop = scan_arrays(scop);
4742 scop = add_parameter_bounds(scop);
4743 scop = pet_scop_gist(scop, value_bounds);
4745 return scop;