update isl for isl_pw_aff_tdiv_q and isl_pw_aff_tdiv_r
[pet.git] / scan.cc
blobec996997f1f92877aae0fa094c1fc1439f524b52
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 if (expr->getOpcode() != UO_AddrOf)
186 return true;
187 if (skip.find(expr) != skip.end())
188 return true;
190 arg = expr->getSubExpr();
191 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
192 return true;
193 ref = cast<DeclRefExpr>(arg);
194 decl = ref->getDecl();
195 clear_assignment(assigned_value, decl);
196 return true;
199 bool VisitBinaryOperator(BinaryOperator *expr) {
200 Expr *lhs;
201 DeclRefExpr *ref;
202 ValueDecl *decl;
204 if (!expr->isAssignmentOp())
205 return true;
206 lhs = expr->getLHS();
207 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
208 return true;
209 ref = cast<DeclRefExpr>(lhs);
210 decl = ref->getDecl();
211 clear_assignment(assigned_value, decl);
212 return true;
216 /* Keep a copy of the currently assigned values.
218 * Any variable that is assigned a value inside the current scope
219 * is removed again when we leave the scope (either because it wasn't
220 * stored in the cache or because it has a different value in the cache).
222 struct assigned_value_cache {
223 map<ValueDecl *, isl_pw_aff *> &assigned_value;
224 map<ValueDecl *, isl_pw_aff *> cache;
226 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
227 assigned_value(assigned_value), cache(assigned_value) {}
228 ~assigned_value_cache() {
229 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
230 for (it = assigned_value.begin(); it != assigned_value.end();
231 ++it) {
232 if (!it->second ||
233 (cache.find(it->first) != cache.end() &&
234 cache[it->first] != it->second))
235 cache[it->first] = NULL;
237 assigned_value = cache;
241 /* Insert an expression into the collection of expressions,
242 * provided it is not already in there.
243 * The isl_pw_affs are freed in the destructor.
245 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
247 std::set<isl_pw_aff *>::iterator it;
249 if (expressions.find(expr) == expressions.end())
250 expressions.insert(expr);
251 else
252 isl_pw_aff_free(expr);
255 PetScan::~PetScan()
257 std::set<isl_pw_aff *>::iterator it;
259 for (it = expressions.begin(); it != expressions.end(); ++it)
260 isl_pw_aff_free(*it);
262 isl_union_map_free(value_bounds);
265 /* Called if we found something we (currently) cannot handle.
266 * We'll provide more informative warnings later.
268 * We only actually complain if autodetect is false.
270 void PetScan::unsupported(Stmt *stmt, const char *msg)
272 if (options->autodetect)
273 return;
275 SourceLocation loc = stmt->getLocStart();
276 DiagnosticsEngine &diag = PP.getDiagnostics();
277 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
278 msg ? msg : "unsupported");
279 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
282 /* Extract an integer from "expr" and store it in "v".
284 int PetScan::extract_int(IntegerLiteral *expr, isl_int *v)
286 const Type *type = expr->getType().getTypePtr();
287 int is_signed = type->hasSignedIntegerRepresentation();
289 if (is_signed) {
290 int64_t i = expr->getValue().getSExtValue();
291 isl_int_set_si(*v, i);
292 } else {
293 uint64_t i = expr->getValue().getZExtValue();
294 isl_int_set_ui(*v, i);
297 return 0;
300 /* Extract an integer from "expr" and store it in "v".
301 * Return -1 if "expr" does not (obviously) represent an integer.
303 int PetScan::extract_int(clang::ParenExpr *expr, isl_int *v)
305 return extract_int(expr->getSubExpr(), v);
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::Expr *expr, isl_int *v)
313 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
314 return extract_int(cast<IntegerLiteral>(expr), v);
315 if (expr->getStmtClass() == Stmt::ParenExprClass)
316 return extract_int(cast<ParenExpr>(expr), v);
318 unsupported(expr);
319 return -1;
322 /* Extract an affine expression from the IntegerLiteral "expr".
324 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
326 isl_space *dim = isl_space_params_alloc(ctx, 0);
327 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
328 isl_aff *aff = isl_aff_zero_on_domain(ls);
329 isl_set *dom = isl_set_universe(dim);
330 isl_int v;
332 isl_int_init(v);
333 extract_int(expr, &v);
334 aff = isl_aff_add_constant(aff, v);
335 isl_int_clear(v);
337 return isl_pw_aff_alloc(dom, aff);
340 /* Extract an affine expression from the APInt "val".
342 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
344 isl_space *dim = isl_space_params_alloc(ctx, 0);
345 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
346 isl_aff *aff = isl_aff_zero_on_domain(ls);
347 isl_set *dom = isl_set_universe(dim);
348 isl_int v;
350 isl_int_init(v);
351 isl_int_set_ui(v, val.getZExtValue());
352 aff = isl_aff_add_constant(aff, v);
353 isl_int_clear(v);
355 return isl_pw_aff_alloc(dom, aff);
358 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
360 return extract_affine(expr->getSubExpr());
363 static unsigned get_type_size(ValueDecl *decl)
365 return decl->getASTContext().getIntWidth(decl->getType());
368 /* Bound parameter "pos" of "set" to the possible values of "decl".
370 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
371 unsigned pos, ValueDecl *decl)
373 unsigned width;
374 isl_int v;
376 isl_int_init(v);
378 width = get_type_size(decl);
379 if (decl->getType()->isUnsignedIntegerType()) {
380 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
381 isl_int_set_si(v, 1);
382 isl_int_mul_2exp(v, v, width);
383 isl_int_sub_ui(v, v, 1);
384 set = isl_set_upper_bound(set, isl_dim_param, pos, v);
385 } else {
386 isl_int_set_si(v, 1);
387 isl_int_mul_2exp(v, v, width - 1);
388 isl_int_sub_ui(v, v, 1);
389 set = isl_set_upper_bound(set, isl_dim_param, pos, v);
390 isl_int_neg(v, v);
391 isl_int_sub_ui(v, v, 1);
392 set = isl_set_lower_bound(set, isl_dim_param, pos, v);
395 isl_int_clear(v);
397 return set;
400 /* Extract an affine expression from the DeclRefExpr "expr".
402 * If the variable has been assigned a value, then we check whether
403 * we know what (affine) value was assigned.
404 * If so, we return this value. Otherwise we convert "expr"
405 * to an extra parameter (provided nesting_enabled is set).
407 * Otherwise, we simply return an expression that is equal
408 * to a parameter corresponding to the referenced variable.
410 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
412 ValueDecl *decl = expr->getDecl();
413 const Type *type = decl->getType().getTypePtr();
414 isl_id *id;
415 isl_space *dim;
416 isl_aff *aff;
417 isl_set *dom;
419 if (!type->isIntegerType()) {
420 unsupported(expr);
421 return NULL;
424 if (assigned_value.find(decl) != assigned_value.end()) {
425 if (assigned_value[decl])
426 return isl_pw_aff_copy(assigned_value[decl]);
427 else
428 return nested_access(expr);
431 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
432 dim = isl_space_params_alloc(ctx, 1);
434 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
436 dom = isl_set_universe(isl_space_copy(dim));
437 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
438 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
440 return isl_pw_aff_alloc(dom, aff);
443 /* Extract an affine expression from an integer division operation.
444 * In particular, if "expr" is lhs/rhs, then return
446 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
448 * The second argument (rhs) is required to be a (positive) integer constant.
450 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
452 Expr *rhs_expr;
453 isl_pw_aff *lhs, *lhs_f, *lhs_c;
454 isl_pw_aff *res;
455 isl_int v;
456 isl_set *cond;
458 rhs_expr = expr->getRHS();
459 isl_int_init(v);
460 if (extract_int(rhs_expr, &v) < 0) {
461 isl_int_clear(v);
462 return NULL;
465 lhs = extract_affine(expr->getLHS());
466 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
468 lhs = isl_pw_aff_scale_down(lhs, v);
469 isl_int_clear(v);
471 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(lhs));
472 lhs_c = isl_pw_aff_ceil(lhs);
473 res = isl_pw_aff_cond(isl_set_indicator_function(cond), lhs_f, lhs_c);
475 return res;
478 /* Extract an affine expression from a modulo operation.
479 * In particular, if "expr" is lhs/rhs, then return
481 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
483 * The second argument (rhs) is required to be a (positive) integer constant.
485 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
487 Expr *rhs_expr;
488 isl_pw_aff *lhs, *lhs_f, *lhs_c;
489 isl_pw_aff *res;
490 isl_int v;
491 isl_set *cond;
493 rhs_expr = expr->getRHS();
494 if (rhs_expr->getStmtClass() != Stmt::IntegerLiteralClass) {
495 unsupported(expr);
496 return NULL;
499 lhs = extract_affine(expr->getLHS());
500 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
502 isl_int_init(v);
503 extract_int(cast<IntegerLiteral>(rhs_expr), &v);
504 res = isl_pw_aff_scale_down(isl_pw_aff_copy(lhs), v);
506 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(res));
507 lhs_c = isl_pw_aff_ceil(res);
508 res = isl_pw_aff_cond(isl_set_indicator_function(cond), lhs_f, lhs_c);
510 res = isl_pw_aff_scale(res, v);
511 isl_int_clear(v);
513 res = isl_pw_aff_sub(lhs, res);
515 return res;
518 /* Extract an affine expression from a multiplication operation.
519 * This is only allowed if at least one of the two arguments
520 * is a (piecewise) constant.
522 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
524 isl_pw_aff *lhs;
525 isl_pw_aff *rhs;
527 lhs = extract_affine(expr->getLHS());
528 rhs = extract_affine(expr->getRHS());
530 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
531 isl_pw_aff_free(lhs);
532 isl_pw_aff_free(rhs);
533 unsupported(expr);
534 return NULL;
537 return isl_pw_aff_mul(lhs, rhs);
540 /* Extract an affine expression from an addition or subtraction operation.
542 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
544 isl_pw_aff *lhs;
545 isl_pw_aff *rhs;
547 lhs = extract_affine(expr->getLHS());
548 rhs = extract_affine(expr->getRHS());
550 switch (expr->getOpcode()) {
551 case BO_Add:
552 return isl_pw_aff_add(lhs, rhs);
553 case BO_Sub:
554 return isl_pw_aff_sub(lhs, rhs);
555 default:
556 isl_pw_aff_free(lhs);
557 isl_pw_aff_free(rhs);
558 return NULL;
563 /* Compute
565 * pwaff mod 2^width
567 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
568 unsigned width)
570 isl_int mod;
572 isl_int_init(mod);
573 isl_int_set_si(mod, 1);
574 isl_int_mul_2exp(mod, mod, width);
576 pwaff = isl_pw_aff_mod(pwaff, mod);
578 isl_int_clear(mod);
580 return pwaff;
583 /* Limit the domain of "pwaff" to those elements where the function
584 * value satisfies
586 * 2^{width-1} <= pwaff < 2^{width-1}
588 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
589 unsigned width)
591 isl_int v;
592 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
593 isl_local_space *ls = isl_local_space_from_space(space);
594 isl_aff *bound;
595 isl_set *dom;
596 isl_pw_aff *b;
598 isl_int_init(v);
599 isl_int_set_si(v, 1);
600 isl_int_mul_2exp(v, v, width - 1);
602 bound = isl_aff_zero_on_domain(ls);
603 bound = isl_aff_add_constant(bound, v);
604 b = isl_pw_aff_from_aff(bound);
606 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
607 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
609 b = isl_pw_aff_neg(b);
610 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
611 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
613 isl_int_clear(v);
615 return pwaff;
618 /* Handle potential overflows on signed computations.
620 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
621 * the we adjust the domain of "pa" to avoid overflows.
623 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
624 unsigned width)
626 if (options->signed_overflow == PET_OVERFLOW_AVOID)
627 pa = avoid_overflow(pa, width);
629 return pa;
632 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
634 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
635 __isl_take isl_set *dom)
637 isl_pw_aff *pa;
638 pa = isl_set_indicator_function(set);
639 pa = isl_pw_aff_intersect_domain(pa, dom);
640 return pa;
643 /* Extract an affine expression from some binary operations.
644 * If the result of the expression is unsigned, then we wrap it
645 * based on the size of the type. Otherwise, we ensure that
646 * no overflow occurs.
648 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
650 isl_pw_aff *res;
651 unsigned width;
653 switch (expr->getOpcode()) {
654 case BO_Add:
655 case BO_Sub:
656 res = extract_affine_add(expr);
657 break;
658 case BO_Div:
659 res = extract_affine_div(expr);
660 break;
661 case BO_Rem:
662 res = extract_affine_mod(expr);
663 break;
664 case BO_Mul:
665 res = extract_affine_mul(expr);
666 break;
667 case BO_LT:
668 case BO_LE:
669 case BO_GT:
670 case BO_GE:
671 case BO_EQ:
672 case BO_NE:
673 case BO_LAnd:
674 case BO_LOr:
675 return extract_condition(expr);
676 default:
677 unsupported(expr);
678 return NULL;
681 width = ast_context.getIntWidth(expr->getType());
682 if (expr->getType()->isUnsignedIntegerType())
683 res = wrap(res, width);
684 else
685 res = signed_overflow(res, width);
687 return res;
690 /* Extract an affine expression from a negation operation.
692 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
694 if (expr->getOpcode() == UO_Minus)
695 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
696 if (expr->getOpcode() == UO_LNot)
697 return extract_condition(expr);
699 unsupported(expr);
700 return NULL;
703 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
705 return extract_affine(expr->getSubExpr());
708 /* Extract an affine expression from some special function calls.
709 * In particular, we handle "min", "max", "ceild" and "floord".
710 * In case of the latter two, the second argument needs to be
711 * a (positive) integer constant.
713 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
715 FunctionDecl *fd;
716 string name;
717 isl_pw_aff *aff1, *aff2;
719 fd = expr->getDirectCallee();
720 if (!fd) {
721 unsupported(expr);
722 return NULL;
725 name = fd->getDeclName().getAsString();
726 if (!(expr->getNumArgs() == 2 && name == "min") &&
727 !(expr->getNumArgs() == 2 && name == "max") &&
728 !(expr->getNumArgs() == 2 && name == "floord") &&
729 !(expr->getNumArgs() == 2 && name == "ceild")) {
730 unsupported(expr);
731 return NULL;
734 if (name == "min" || name == "max") {
735 aff1 = extract_affine(expr->getArg(0));
736 aff2 = extract_affine(expr->getArg(1));
738 if (name == "min")
739 aff1 = isl_pw_aff_min(aff1, aff2);
740 else
741 aff1 = isl_pw_aff_max(aff1, aff2);
742 } else if (name == "floord" || name == "ceild") {
743 isl_int v;
744 Expr *arg2 = expr->getArg(1);
746 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
747 unsupported(expr);
748 return NULL;
750 aff1 = extract_affine(expr->getArg(0));
751 isl_int_init(v);
752 extract_int(cast<IntegerLiteral>(arg2), &v);
753 aff1 = isl_pw_aff_scale_down(aff1, v);
754 isl_int_clear(v);
755 if (name == "floord")
756 aff1 = isl_pw_aff_floor(aff1);
757 else
758 aff1 = isl_pw_aff_ceil(aff1);
759 } else {
760 unsupported(expr);
761 return NULL;
764 return aff1;
767 /* This method is called when we come across an access that is
768 * nested in what is supposed to be an affine expression.
769 * If nesting is allowed, we return a new parameter that corresponds
770 * to this nested access. Otherwise, we simply complain.
772 * Note that we currently don't allow nested accesses themselves
773 * to contain any nested accesses, so we check if we can extract
774 * the access without any nesting and complain if we can't.
776 * The new parameter is resolved in resolve_nested.
778 isl_pw_aff *PetScan::nested_access(Expr *expr)
780 isl_id *id;
781 isl_space *dim;
782 isl_aff *aff;
783 isl_set *dom;
784 isl_map *access;
786 if (!nesting_enabled) {
787 unsupported(expr);
788 return NULL;
791 allow_nested = false;
792 access = extract_access(expr);
793 allow_nested = true;
794 if (!access) {
795 unsupported(expr);
796 return NULL;
798 isl_map_free(access);
800 id = isl_id_alloc(ctx, NULL, expr);
801 dim = isl_space_params_alloc(ctx, 1);
803 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
805 dom = isl_set_universe(isl_space_copy(dim));
806 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
807 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
809 return isl_pw_aff_alloc(dom, aff);
812 /* Affine expressions are not supposed to contain array accesses,
813 * but if nesting is allowed, we return a parameter corresponding
814 * to the array access.
816 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
818 return nested_access(expr);
821 /* Extract an affine expression from a conditional operation.
823 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
825 isl_pw_aff *cond, *lhs, *rhs, *res;
827 cond = extract_condition(expr->getCond());
828 lhs = extract_affine(expr->getTrueExpr());
829 rhs = extract_affine(expr->getFalseExpr());
831 return isl_pw_aff_cond(cond, lhs, rhs);
834 /* Extract an affine expression, if possible, from "expr".
835 * Otherwise return NULL.
837 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
839 switch (expr->getStmtClass()) {
840 case Stmt::ImplicitCastExprClass:
841 return extract_affine(cast<ImplicitCastExpr>(expr));
842 case Stmt::IntegerLiteralClass:
843 return extract_affine(cast<IntegerLiteral>(expr));
844 case Stmt::DeclRefExprClass:
845 return extract_affine(cast<DeclRefExpr>(expr));
846 case Stmt::BinaryOperatorClass:
847 return extract_affine(cast<BinaryOperator>(expr));
848 case Stmt::UnaryOperatorClass:
849 return extract_affine(cast<UnaryOperator>(expr));
850 case Stmt::ParenExprClass:
851 return extract_affine(cast<ParenExpr>(expr));
852 case Stmt::CallExprClass:
853 return extract_affine(cast<CallExpr>(expr));
854 case Stmt::ArraySubscriptExprClass:
855 return extract_affine(cast<ArraySubscriptExpr>(expr));
856 case Stmt::ConditionalOperatorClass:
857 return extract_affine(cast<ConditionalOperator>(expr));
858 default:
859 unsupported(expr);
861 return NULL;
864 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
866 return extract_access(expr->getSubExpr());
869 /* Return the depth of an array of the given type.
871 static int array_depth(const Type *type)
873 if (type->isPointerType())
874 return 1 + array_depth(type->getPointeeType().getTypePtr());
875 if (type->isArrayType()) {
876 const ArrayType *atype;
877 type = type->getCanonicalTypeInternal().getTypePtr();
878 atype = cast<ArrayType>(type);
879 return 1 + array_depth(atype->getElementType().getTypePtr());
881 return 0;
884 /* Return the element type of the given array type.
886 static QualType base_type(QualType qt)
888 const Type *type = qt.getTypePtr();
890 if (type->isPointerType())
891 return base_type(type->getPointeeType());
892 if (type->isArrayType()) {
893 const ArrayType *atype;
894 type = type->getCanonicalTypeInternal().getTypePtr();
895 atype = cast<ArrayType>(type);
896 return base_type(atype->getElementType());
898 return qt;
901 /* Extract an access relation from a reference to a variable.
902 * If the variable has name "A" and its type corresponds to an
903 * array of depth d, then the returned access relation is of the
904 * form
906 * { [] -> A[i_1,...,i_d] }
908 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
910 ValueDecl *decl = expr->getDecl();
911 int depth = array_depth(decl->getType().getTypePtr());
912 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
913 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
914 isl_map *access_rel;
916 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
918 access_rel = isl_map_universe(dim);
920 return access_rel;
923 /* Extract an access relation from an integer contant.
924 * If the value of the constant is "v", then the returned access relation
925 * is
927 * { [] -> [v] }
929 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
931 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
934 /* Try and extract an access relation from the given Expr.
935 * Return NULL if it doesn't work out.
937 __isl_give isl_map *PetScan::extract_access(Expr *expr)
939 switch (expr->getStmtClass()) {
940 case Stmt::ImplicitCastExprClass:
941 return extract_access(cast<ImplicitCastExpr>(expr));
942 case Stmt::DeclRefExprClass:
943 return extract_access(cast<DeclRefExpr>(expr));
944 case Stmt::ArraySubscriptExprClass:
945 return extract_access(cast<ArraySubscriptExpr>(expr));
946 case Stmt::IntegerLiteralClass:
947 return extract_access(cast<IntegerLiteral>(expr));
948 default:
949 unsupported(expr);
951 return NULL;
954 /* Assign the affine expression "index" to the output dimension "pos" of "map",
955 * restrict the domain to those values that result in a non-negative index
956 * and return the result.
958 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
959 __isl_take isl_pw_aff *index)
961 isl_map *index_map;
962 int len = isl_map_dim(map, isl_dim_out);
963 isl_id *id;
964 isl_set *domain;
966 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
967 index = isl_pw_aff_intersect_domain(index, domain);
968 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
969 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
970 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
971 id = isl_map_get_tuple_id(map, isl_dim_out);
972 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
974 map = isl_map_intersect(map, index_map);
976 return map;
979 /* Extract an access relation from the given array subscript expression.
980 * If nesting is allowed in general, then we turn it on while
981 * examining the index expression.
983 * We first extract an access relation from the base.
984 * This will result in an access relation with a range that corresponds
985 * to the array being accessed and with earlier indices filled in already.
986 * We then extract the current index and fill that in as well.
987 * The position of the current index is based on the type of base.
988 * If base is the actual array variable, then the depth of this type
989 * will be the same as the depth of the array and we will fill in
990 * the first array index.
991 * Otherwise, the depth of the base type will be smaller and we will fill
992 * in a later index.
994 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
996 Expr *base = expr->getBase();
997 Expr *idx = expr->getIdx();
998 isl_pw_aff *index;
999 isl_map *base_access;
1000 isl_map *access;
1001 int depth = array_depth(base->getType().getTypePtr());
1002 int pos;
1003 bool save_nesting = nesting_enabled;
1005 nesting_enabled = allow_nested;
1007 base_access = extract_access(base);
1008 index = extract_affine(idx);
1010 nesting_enabled = save_nesting;
1012 pos = isl_map_dim(base_access, isl_dim_out) - depth;
1013 access = set_index(base_access, pos, index);
1015 return access;
1018 /* Check if "expr" calls function "minmax" with two arguments and if so
1019 * make lhs and rhs refer to these two arguments.
1021 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1023 CallExpr *call;
1024 FunctionDecl *fd;
1025 string name;
1027 if (expr->getStmtClass() != Stmt::CallExprClass)
1028 return false;
1030 call = cast<CallExpr>(expr);
1031 fd = call->getDirectCallee();
1032 if (!fd)
1033 return false;
1035 if (call->getNumArgs() != 2)
1036 return false;
1038 name = fd->getDeclName().getAsString();
1039 if (name != minmax)
1040 return false;
1042 lhs = call->getArg(0);
1043 rhs = call->getArg(1);
1045 return true;
1048 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1049 * lhs and rhs refer to the two arguments.
1051 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1053 return is_minmax(expr, "min", lhs, rhs);
1056 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1057 * lhs and rhs refer to the two arguments.
1059 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1061 return is_minmax(expr, "max", lhs, rhs);
1064 /* Return "lhs && rhs", defined on the shared definition domain.
1066 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1067 __isl_take isl_pw_aff *rhs)
1069 isl_set *cond;
1070 isl_set *dom;
1072 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1073 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1074 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1075 isl_pw_aff_non_zero_set(rhs));
1076 return indicator_function(cond, dom);
1079 /* Return "lhs && rhs", with shortcut semantics.
1080 * That is, if lhs is false, then the result is defined even if rhs is not.
1081 * In practice, we compute lhs ? rhs : lhs.
1083 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1084 __isl_take isl_pw_aff *rhs)
1086 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1089 /* Return "lhs || rhs", with shortcut semantics.
1090 * That is, if lhs is true, then the result is defined even if rhs is not.
1091 * In practice, we compute lhs ? lhs : rhs.
1093 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1094 __isl_take isl_pw_aff *rhs)
1096 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1099 /* Extract an affine expressions representing the comparison "LHS op RHS"
1100 * "comp" is the original statement that "LHS op RHS" is derived from
1101 * and is used for diagnostics.
1103 * If the comparison is of the form
1105 * a <= min(b,c)
1107 * then the expression is constructed as the conjunction of
1108 * the comparisons
1110 * a <= b and a <= c
1112 * A similar optimization is performed for max(a,b) <= c.
1113 * We do this because that will lead to simpler representations
1114 * of the expression.
1115 * If isl is ever enhanced to explicitly deal with min and max expressions,
1116 * this optimization can be removed.
1118 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1119 Expr *LHS, Expr *RHS, Stmt *comp)
1121 isl_pw_aff *lhs;
1122 isl_pw_aff *rhs;
1123 isl_pw_aff *res;
1124 isl_set *cond;
1125 isl_set *dom;
1127 if (op == BO_GT)
1128 return extract_comparison(BO_LT, RHS, LHS, comp);
1129 if (op == BO_GE)
1130 return extract_comparison(BO_LE, RHS, LHS, comp);
1132 if (op == BO_LT || op == BO_LE) {
1133 Expr *expr1, *expr2;
1134 if (is_min(RHS, expr1, expr2)) {
1135 lhs = extract_comparison(op, LHS, expr1, comp);
1136 rhs = extract_comparison(op, LHS, expr2, comp);
1137 return pw_aff_and(lhs, rhs);
1139 if (is_max(LHS, expr1, expr2)) {
1140 lhs = extract_comparison(op, expr1, RHS, comp);
1141 rhs = extract_comparison(op, expr2, RHS, comp);
1142 return pw_aff_and(lhs, rhs);
1146 lhs = extract_affine(LHS);
1147 rhs = extract_affine(RHS);
1149 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1150 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1152 switch (op) {
1153 case BO_LT:
1154 cond = isl_pw_aff_lt_set(lhs, rhs);
1155 break;
1156 case BO_LE:
1157 cond = isl_pw_aff_le_set(lhs, rhs);
1158 break;
1159 case BO_EQ:
1160 cond = isl_pw_aff_eq_set(lhs, rhs);
1161 break;
1162 case BO_NE:
1163 cond = isl_pw_aff_ne_set(lhs, rhs);
1164 break;
1165 default:
1166 isl_pw_aff_free(lhs);
1167 isl_pw_aff_free(rhs);
1168 isl_set_free(dom);
1169 unsupported(comp);
1170 return NULL;
1173 cond = isl_set_coalesce(cond);
1174 res = indicator_function(cond, dom);
1176 return res;
1179 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1181 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1182 comp->getRHS(), comp);
1185 /* Extract an affine expression representing the negation (logical not)
1186 * of a subexpression.
1188 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1190 isl_set *set_cond, *dom;
1191 isl_pw_aff *cond, *res;
1193 cond = extract_condition(op->getSubExpr());
1195 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1197 set_cond = isl_pw_aff_zero_set(cond);
1199 res = indicator_function(set_cond, dom);
1201 return res;
1204 /* Extract an affine expression representing the disjunction (logical or)
1205 * or conjunction (logical and) of two subexpressions.
1207 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1209 isl_pw_aff *lhs, *rhs;
1211 lhs = extract_condition(comp->getLHS());
1212 rhs = extract_condition(comp->getRHS());
1214 switch (comp->getOpcode()) {
1215 case BO_LAnd:
1216 return pw_aff_and_then(lhs, rhs);
1217 case BO_LOr:
1218 return pw_aff_or_else(lhs, rhs);
1219 default:
1220 isl_pw_aff_free(lhs);
1221 isl_pw_aff_free(rhs);
1224 unsupported(comp);
1225 return NULL;
1228 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1230 switch (expr->getOpcode()) {
1231 case UO_LNot:
1232 return extract_boolean(expr);
1233 default:
1234 unsupported(expr);
1235 return NULL;
1239 /* Extract the affine expression "expr != 0 ? 1 : 0".
1241 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1243 isl_pw_aff *res;
1244 isl_set *set, *dom;
1246 res = extract_affine(expr);
1248 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1249 set = isl_pw_aff_non_zero_set(res);
1251 res = indicator_function(set, dom);
1253 return res;
1256 /* Extract an affine expression from a boolean expression.
1257 * In particular, return the expression "expr ? 1 : 0".
1259 * If the expression doesn't look like a condition, we assume it
1260 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1262 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1264 BinaryOperator *comp;
1266 if (!expr) {
1267 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1268 return indicator_function(u, isl_set_copy(u));
1271 if (expr->getStmtClass() == Stmt::ParenExprClass)
1272 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1274 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1275 return extract_condition(cast<UnaryOperator>(expr));
1277 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1278 return extract_implicit_condition(expr);
1280 comp = cast<BinaryOperator>(expr);
1281 switch (comp->getOpcode()) {
1282 case BO_LT:
1283 case BO_LE:
1284 case BO_GT:
1285 case BO_GE:
1286 case BO_EQ:
1287 case BO_NE:
1288 return extract_comparison(comp);
1289 case BO_LAnd:
1290 case BO_LOr:
1291 return extract_boolean(comp);
1292 default:
1293 return extract_implicit_condition(expr);
1297 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1299 switch (kind) {
1300 case UO_Minus:
1301 return pet_op_minus;
1302 case UO_PostInc:
1303 return pet_op_post_inc;
1304 case UO_PostDec:
1305 return pet_op_post_dec;
1306 case UO_PreInc:
1307 return pet_op_pre_inc;
1308 case UO_PreDec:
1309 return pet_op_pre_dec;
1310 default:
1311 return pet_op_last;
1315 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1317 switch (kind) {
1318 case BO_AddAssign:
1319 return pet_op_add_assign;
1320 case BO_SubAssign:
1321 return pet_op_sub_assign;
1322 case BO_MulAssign:
1323 return pet_op_mul_assign;
1324 case BO_DivAssign:
1325 return pet_op_div_assign;
1326 case BO_Assign:
1327 return pet_op_assign;
1328 case BO_Add:
1329 return pet_op_add;
1330 case BO_Sub:
1331 return pet_op_sub;
1332 case BO_Mul:
1333 return pet_op_mul;
1334 case BO_Div:
1335 return pet_op_div;
1336 case BO_Rem:
1337 return pet_op_mod;
1338 case BO_EQ:
1339 return pet_op_eq;
1340 case BO_LE:
1341 return pet_op_le;
1342 case BO_LT:
1343 return pet_op_lt;
1344 case BO_GT:
1345 return pet_op_gt;
1346 default:
1347 return pet_op_last;
1351 /* Construct a pet_expr representing a unary operator expression.
1353 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1355 struct pet_expr *arg;
1356 enum pet_op_type op;
1358 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1359 if (op == pet_op_last) {
1360 unsupported(expr);
1361 return NULL;
1364 arg = extract_expr(expr->getSubExpr());
1366 if (expr->isIncrementDecrementOp() &&
1367 arg && arg->type == pet_expr_access) {
1368 mark_write(arg);
1369 arg->acc.read = 1;
1372 return pet_expr_new_unary(ctx, op, arg);
1375 /* Mark the given access pet_expr as a write.
1376 * If a scalar is being accessed, then mark its value
1377 * as unknown in assigned_value.
1379 void PetScan::mark_write(struct pet_expr *access)
1381 isl_id *id;
1382 ValueDecl *decl;
1384 access->acc.write = 1;
1385 access->acc.read = 0;
1387 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1388 return;
1390 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1391 decl = (ValueDecl *) isl_id_get_user(id);
1392 clear_assignment(assigned_value, decl);
1393 isl_id_free(id);
1396 /* Construct a pet_expr representing a binary operator expression.
1398 * If the top level operator is an assignment and the LHS is an access,
1399 * then we mark that access as a write. If the operator is a compound
1400 * assignment, the access is marked as both a read and a write.
1402 * If "expr" assigns something to a scalar variable, then we mark
1403 * the variable as having been assigned. If, furthermore, the expression
1404 * is affine, then keep track of this value in assigned_value
1405 * so that we can plug it in when we later come across the same variable.
1407 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1409 struct pet_expr *lhs, *rhs;
1410 enum pet_op_type op;
1412 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1413 if (op == pet_op_last) {
1414 unsupported(expr);
1415 return NULL;
1418 lhs = extract_expr(expr->getLHS());
1419 rhs = extract_expr(expr->getRHS());
1421 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1422 mark_write(lhs);
1423 if (expr->isCompoundAssignmentOp())
1424 lhs->acc.read = 1;
1427 if (expr->getOpcode() == BO_Assign &&
1428 lhs && lhs->type == pet_expr_access &&
1429 isl_map_dim(lhs->acc.access, isl_dim_out) == 0) {
1430 isl_id *id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1431 ValueDecl *decl = (ValueDecl *) isl_id_get_user(id);
1432 Expr *rhs = expr->getRHS();
1433 isl_pw_aff *pa = try_extract_affine(rhs);
1434 clear_assignment(assigned_value, decl);
1435 if (pa) {
1436 assigned_value[decl] = pa;
1437 insert_expression(pa);
1439 isl_id_free(id);
1442 return pet_expr_new_binary(ctx, op, lhs, rhs);
1445 /* Construct a pet_expr representing a conditional operation.
1447 * We first try to extract the condition as an affine expression.
1448 * If that fails, we construct a pet_expr tree representing the condition.
1450 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1452 struct pet_expr *cond, *lhs, *rhs;
1453 isl_pw_aff *pa;
1455 pa = try_extract_affine(expr->getCond());
1456 if (pa) {
1457 isl_set *test = isl_set_from_pw_aff(pa);
1458 cond = pet_expr_from_access(isl_map_from_range(test));
1459 } else
1460 cond = extract_expr(expr->getCond());
1461 lhs = extract_expr(expr->getTrueExpr());
1462 rhs = extract_expr(expr->getFalseExpr());
1464 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1467 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1469 return extract_expr(expr->getSubExpr());
1472 /* Construct a pet_expr representing a floating point value.
1474 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1476 return pet_expr_new_double(ctx, expr->getValueAsApproximateDouble());
1479 /* Extract an access relation from "expr" and then convert it into
1480 * a pet_expr.
1482 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1484 isl_map *access;
1485 struct pet_expr *pe;
1487 access = extract_access(expr);
1489 pe = pet_expr_from_access(access);
1491 return pe;
1494 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1496 return extract_expr(expr->getSubExpr());
1499 /* Construct a pet_expr representing a function call.
1501 * If we are passing along a pointer to an array element
1502 * or an entire row or even higher dimensional slice of an array,
1503 * then the function being called may write into the array.
1505 * We assume here that if the function is declared to take a pointer
1506 * to a const type, then the function will perform a read
1507 * and that otherwise, it will perform a write.
1509 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1511 struct pet_expr *res = NULL;
1512 FunctionDecl *fd;
1513 string name;
1515 fd = expr->getDirectCallee();
1516 if (!fd) {
1517 unsupported(expr);
1518 return NULL;
1521 name = fd->getDeclName().getAsString();
1522 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1523 if (!res)
1524 return NULL;
1526 for (int i = 0; i < expr->getNumArgs(); ++i) {
1527 Expr *arg = expr->getArg(i);
1528 int is_addr = 0;
1529 pet_expr *main_arg;
1531 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1532 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1533 arg = ice->getSubExpr();
1535 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1536 UnaryOperator *op = cast<UnaryOperator>(arg);
1537 if (op->getOpcode() == UO_AddrOf) {
1538 is_addr = 1;
1539 arg = op->getSubExpr();
1542 res->args[i] = PetScan::extract_expr(arg);
1543 main_arg = res->args[i];
1544 if (is_addr)
1545 res->args[i] = pet_expr_new_unary(ctx,
1546 pet_op_address_of, res->args[i]);
1547 if (!res->args[i])
1548 goto error;
1549 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1550 array_depth(arg->getType().getTypePtr()) > 0)
1551 is_addr = 1;
1552 if (is_addr && main_arg->type == pet_expr_access) {
1553 ParmVarDecl *parm;
1554 if (!fd->hasPrototype()) {
1555 unsupported(expr, "prototype required");
1556 goto error;
1558 parm = fd->getParamDecl(i);
1559 if (!const_base(parm->getType()))
1560 mark_write(main_arg);
1564 return res;
1565 error:
1566 pet_expr_free(res);
1567 return NULL;
1570 /* Try and onstruct a pet_expr representing "expr".
1572 struct pet_expr *PetScan::extract_expr(Expr *expr)
1574 switch (expr->getStmtClass()) {
1575 case Stmt::UnaryOperatorClass:
1576 return extract_expr(cast<UnaryOperator>(expr));
1577 case Stmt::CompoundAssignOperatorClass:
1578 case Stmt::BinaryOperatorClass:
1579 return extract_expr(cast<BinaryOperator>(expr));
1580 case Stmt::ImplicitCastExprClass:
1581 return extract_expr(cast<ImplicitCastExpr>(expr));
1582 case Stmt::ArraySubscriptExprClass:
1583 case Stmt::DeclRefExprClass:
1584 case Stmt::IntegerLiteralClass:
1585 return extract_access_expr(expr);
1586 case Stmt::FloatingLiteralClass:
1587 return extract_expr(cast<FloatingLiteral>(expr));
1588 case Stmt::ParenExprClass:
1589 return extract_expr(cast<ParenExpr>(expr));
1590 case Stmt::ConditionalOperatorClass:
1591 return extract_expr(cast<ConditionalOperator>(expr));
1592 case Stmt::CallExprClass:
1593 return extract_expr(cast<CallExpr>(expr));
1594 default:
1595 unsupported(expr);
1597 return NULL;
1600 /* Check if the given initialization statement is an assignment.
1601 * If so, return that assignment. Otherwise return NULL.
1603 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1605 BinaryOperator *ass;
1607 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1608 return NULL;
1610 ass = cast<BinaryOperator>(init);
1611 if (ass->getOpcode() != BO_Assign)
1612 return NULL;
1614 return ass;
1617 /* Check if the given initialization statement is a declaration
1618 * of a single variable.
1619 * If so, return that declaration. Otherwise return NULL.
1621 Decl *PetScan::initialization_declaration(Stmt *init)
1623 DeclStmt *decl;
1625 if (init->getStmtClass() != Stmt::DeclStmtClass)
1626 return NULL;
1628 decl = cast<DeclStmt>(init);
1630 if (!decl->isSingleDecl())
1631 return NULL;
1633 return decl->getSingleDecl();
1636 /* Given the assignment operator in the initialization of a for loop,
1637 * extract the induction variable, i.e., the (integer)variable being
1638 * assigned.
1640 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1642 Expr *lhs;
1643 DeclRefExpr *ref;
1644 ValueDecl *decl;
1645 const Type *type;
1647 lhs = init->getLHS();
1648 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1649 unsupported(init);
1650 return NULL;
1653 ref = cast<DeclRefExpr>(lhs);
1654 decl = ref->getDecl();
1655 type = decl->getType().getTypePtr();
1657 if (!type->isIntegerType()) {
1658 unsupported(lhs);
1659 return NULL;
1662 return decl;
1665 /* Given the initialization statement of a for loop and the single
1666 * declaration in this initialization statement,
1667 * extract the induction variable, i.e., the (integer) variable being
1668 * declared.
1670 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1672 VarDecl *vd;
1674 vd = cast<VarDecl>(decl);
1676 const QualType type = vd->getType();
1677 if (!type->isIntegerType()) {
1678 unsupported(init);
1679 return NULL;
1682 if (!vd->getInit()) {
1683 unsupported(init);
1684 return NULL;
1687 return vd;
1690 /* Check that op is of the form iv++ or iv--.
1691 * Return an affine expression "1" or "-1" accordingly.
1693 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
1694 clang::UnaryOperator *op, clang::ValueDecl *iv)
1696 Expr *sub;
1697 DeclRefExpr *ref;
1698 isl_space *space;
1699 isl_aff *aff;
1701 if (!op->isIncrementDecrementOp()) {
1702 unsupported(op);
1703 return NULL;
1706 sub = op->getSubExpr();
1707 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1708 unsupported(op);
1709 return NULL;
1712 ref = cast<DeclRefExpr>(sub);
1713 if (ref->getDecl() != iv) {
1714 unsupported(op);
1715 return NULL;
1718 space = isl_space_params_alloc(ctx, 0);
1719 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1721 if (op->isIncrementOp())
1722 aff = isl_aff_add_constant_si(aff, 1);
1723 else
1724 aff = isl_aff_add_constant_si(aff, -1);
1726 return isl_pw_aff_from_aff(aff);
1729 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1730 * has a single constant expression, then put this constant in *user.
1731 * The caller is assumed to have checked that this function will
1732 * be called exactly once.
1734 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1735 void *user)
1737 isl_int *inc = (isl_int *)user;
1738 int res = 0;
1740 if (isl_aff_is_cst(aff))
1741 isl_aff_get_constant(aff, inc);
1742 else
1743 res = -1;
1745 isl_set_free(set);
1746 isl_aff_free(aff);
1748 return res;
1751 /* Check if op is of the form
1753 * iv = iv + inc
1755 * and return inc as an affine expression.
1757 * We extract an affine expression from the RHS, subtract iv and return
1758 * the result.
1760 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
1761 clang::ValueDecl *iv)
1763 Expr *lhs;
1764 DeclRefExpr *ref;
1765 isl_id *id;
1766 isl_space *dim;
1767 isl_aff *aff;
1768 isl_pw_aff *val;
1770 if (op->getOpcode() != BO_Assign) {
1771 unsupported(op);
1772 return NULL;
1775 lhs = op->getLHS();
1776 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1777 unsupported(op);
1778 return NULL;
1781 ref = cast<DeclRefExpr>(lhs);
1782 if (ref->getDecl() != iv) {
1783 unsupported(op);
1784 return NULL;
1787 val = extract_affine(op->getRHS());
1789 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1791 dim = isl_space_params_alloc(ctx, 1);
1792 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1793 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1794 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1796 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1798 return val;
1801 /* Check that op is of the form iv += cst or iv -= cst
1802 * and return an affine expression corresponding oto cst or -cst accordingly.
1804 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
1805 CompoundAssignOperator *op, clang::ValueDecl *iv)
1807 Expr *lhs;
1808 DeclRefExpr *ref;
1809 bool neg = false;
1810 isl_pw_aff *val;
1811 BinaryOperatorKind opcode;
1813 opcode = op->getOpcode();
1814 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1815 unsupported(op);
1816 return NULL;
1818 if (opcode == BO_SubAssign)
1819 neg = true;
1821 lhs = op->getLHS();
1822 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1823 unsupported(op);
1824 return NULL;
1827 ref = cast<DeclRefExpr>(lhs);
1828 if (ref->getDecl() != iv) {
1829 unsupported(op);
1830 return NULL;
1833 val = extract_affine(op->getRHS());
1834 if (neg)
1835 val = isl_pw_aff_neg(val);
1837 return val;
1840 /* Check that the increment of the given for loop increments
1841 * (or decrements) the induction variable "iv" and return
1842 * the increment as an affine expression if successful.
1844 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
1845 ValueDecl *iv)
1847 Stmt *inc = stmt->getInc();
1849 if (!inc) {
1850 unsupported(stmt);
1851 return NULL;
1854 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1855 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1856 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1857 return extract_compound_increment(
1858 cast<CompoundAssignOperator>(inc), iv);
1859 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1860 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1862 unsupported(inc);
1863 return NULL;
1866 /* Embed the given iteration domain in an extra outer loop
1867 * with induction variable "var".
1868 * If this variable appeared as a parameter in the constraints,
1869 * it is replaced by the new outermost dimension.
1871 static __isl_give isl_set *embed(__isl_take isl_set *set,
1872 __isl_take isl_id *var)
1874 int pos;
1876 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1877 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1878 if (pos >= 0) {
1879 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1880 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1883 isl_id_free(var);
1884 return set;
1887 /* Return those elements in the space of "cond" that come after
1888 * (based on "sign") an element in "cond".
1890 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
1892 isl_map *previous_to_this;
1894 if (sign > 0)
1895 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
1896 else
1897 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
1899 cond = isl_set_apply(cond, previous_to_this);
1901 return cond;
1904 /* Create the infinite iteration domain
1906 * { [id] : id >= 0 }
1908 * If "scop" has an affine skip of type pet_skip_later,
1909 * then remove those iterations i that have an earlier iteration
1910 * where the skip condition is satisfied, meaning that iteration i
1911 * is not executed.
1912 * Since we are dealing with a loop without loop iterator,
1913 * the skip condition cannot refer to the current loop iterator and
1914 * so effectively, the returned set is of the form
1916 * { [0]; [id] : id >= 1 and not skip }
1918 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
1919 struct pet_scop *scop)
1921 isl_ctx *ctx = isl_id_get_ctx(id);
1922 isl_set *domain;
1923 isl_set *skip;
1925 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1926 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
1928 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
1929 return domain;
1931 skip = pet_scop_get_skip(scop, pet_skip_later);
1932 skip = isl_set_fix_si(skip, isl_dim_set, 0, 1);
1933 skip = isl_set_params(skip);
1934 skip = embed(skip, isl_id_copy(id));
1935 skip = isl_set_intersect(skip , isl_set_copy(domain));
1936 domain = isl_set_subtract(domain, after(skip, 1));
1938 return domain;
1941 /* Create an identity mapping on the space containing "domain".
1943 static __isl_give isl_map *identity_map(__isl_keep isl_set *domain)
1945 isl_space *space;
1946 isl_map *id;
1948 space = isl_space_map_from_set(isl_set_get_space(domain));
1949 id = isl_map_identity(space);
1951 return id;
1954 /* Add a filter to "scop" that imposes that it is only executed
1955 * when "break_access" has a zero value for all previous iterations
1956 * of "domain".
1958 * The input "break_access" has a zero-dimensional domain and range.
1960 static struct pet_scop *scop_add_break(struct pet_scop *scop,
1961 __isl_take isl_map *break_access, __isl_take isl_set *domain, int sign)
1963 isl_ctx *ctx = isl_set_get_ctx(domain);
1964 isl_id *id_test;
1965 isl_map *prev;
1967 id_test = isl_map_get_tuple_id(break_access, isl_dim_out);
1968 break_access = isl_map_add_dims(break_access, isl_dim_in, 1);
1969 break_access = isl_map_add_dims(break_access, isl_dim_out, 1);
1970 break_access = isl_map_intersect_range(break_access, domain);
1971 break_access = isl_map_set_tuple_id(break_access, isl_dim_out, id_test);
1972 if (sign > 0)
1973 prev = isl_map_lex_gt_first(isl_map_get_space(break_access), 1);
1974 else
1975 prev = isl_map_lex_lt_first(isl_map_get_space(break_access), 1);
1976 break_access = isl_map_intersect(break_access, prev);
1977 scop = pet_scop_filter(scop, break_access, 0);
1978 scop = pet_scop_merge_filters(scop);
1980 return scop;
1983 /* Construct a pet_scop for an infinite loop around the given body.
1985 * We extract a pet_scop for the body and then embed it in a loop with
1986 * iteration domain
1988 * { [t] : t >= 0 }
1990 * and schedule
1992 * { [t] -> [t] }
1994 * If the body contains any break, then it is taken into
1995 * account in infinite_domain (if the skip condition is affine)
1996 * or in scop_add_break (if the skip condition is not affine).
1998 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2000 isl_id *id;
2001 isl_set *domain;
2002 isl_map *ident;
2003 isl_map *access;
2004 struct pet_scop *scop;
2005 bool has_var_break;
2007 scop = extract(body);
2008 if (!scop)
2009 return NULL;
2011 id = isl_id_alloc(ctx, "t", NULL);
2012 domain = infinite_domain(isl_id_copy(id), scop);
2013 ident = identity_map(domain);
2015 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2016 if (has_var_break)
2017 access = pet_scop_get_skip_map(scop, pet_skip_later);
2019 scop = pet_scop_embed(scop, isl_set_copy(domain),
2020 isl_map_copy(ident), ident, id);
2021 if (has_var_break)
2022 scop = scop_add_break(scop, access, domain, 1);
2023 else
2024 isl_set_free(domain);
2026 return scop;
2029 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2031 * for (;;)
2032 * body
2035 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2037 return extract_infinite_loop(stmt->getBody());
2040 /* Create an access to a virtual array representing the result
2041 * of a condition.
2042 * Unlike other accessed data, the id of the array is NULL as
2043 * there is no ValueDecl in the program corresponding to the virtual
2044 * array.
2045 * The array starts out as a scalar, but grows along with the
2046 * statement writing to the array in pet_scop_embed.
2048 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2050 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2051 isl_id *id;
2052 char name[50];
2054 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2055 id = isl_id_alloc(ctx, name, NULL);
2056 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2057 return isl_map_universe(dim);
2060 /* Add an array with the given extent ("access") to the list
2061 * of arrays in "scop" and return the extended pet_scop.
2062 * The array is marked as attaining values 0 and 1 only and
2063 * as each element being assigned at most once.
2065 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2066 __isl_keep isl_map *access, clang::ASTContext &ast_ctx)
2068 isl_ctx *ctx = isl_map_get_ctx(access);
2069 isl_space *dim;
2070 struct pet_array **arrays;
2071 struct pet_array *array;
2073 if (!scop)
2074 return NULL;
2075 if (!ctx)
2076 goto error;
2078 arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2079 scop->n_array + 1);
2080 if (!arrays)
2081 goto error;
2082 scop->arrays = arrays;
2084 array = isl_calloc_type(ctx, struct pet_array);
2085 if (!array)
2086 goto error;
2088 array->extent = isl_map_range(isl_map_copy(access));
2089 dim = isl_space_params_alloc(ctx, 0);
2090 array->context = isl_set_universe(dim);
2091 dim = isl_space_set_alloc(ctx, 0, 1);
2092 array->value_bounds = isl_set_universe(dim);
2093 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2094 isl_dim_set, 0, 0);
2095 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2096 isl_dim_set, 0, 1);
2097 array->element_type = strdup("int");
2098 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2099 array->uniquely_defined = 1;
2101 scop->arrays[scop->n_array] = array;
2102 scop->n_array++;
2104 if (!array->extent || !array->context)
2105 goto error;
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 pa = try_extract_affine_condition(cond);
2225 if (pa)
2226 return extract_affine_while(pa, stmt->getBody());
2228 if (!allow_nested) {
2229 unsupported(stmt);
2230 return NULL;
2233 test_access = create_test_access(ctx, n_test++);
2234 scop = extract_non_affine_condition(cond, isl_map_copy(test_access));
2235 scop = scop_add_array(scop, test_access, ast_context);
2236 scop_body = extract(stmt->getBody());
2238 id = isl_id_alloc(ctx, "t", NULL);
2239 domain = infinite_domain(isl_id_copy(id), scop_body);
2240 ident = identity_map(domain);
2242 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2243 if (has_var_break)
2244 break_access = pet_scop_get_skip_map(scop_body, pet_skip_later);
2246 scop = pet_scop_prefix(scop, 0);
2247 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_map_copy(ident),
2248 isl_map_copy(ident), isl_id_copy(id));
2249 scop_body = pet_scop_reset_context(scop_body);
2250 scop_body = pet_scop_prefix(scop_body, 1);
2251 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2252 isl_map_copy(ident), ident, id);
2254 if (has_var_break) {
2255 scop = scop_add_break(scop, isl_map_copy(break_access),
2256 isl_set_copy(domain), 1);
2257 scop_body = scop_add_break(scop_body, break_access,
2258 isl_set_copy(domain), 1);
2260 scop = scop_add_while(scop, scop_body, test_access, domain, 1);
2262 return scop;
2265 /* Check whether "cond" expresses a simple loop bound
2266 * on the only set dimension.
2267 * In particular, if "up" is set then "cond" should contain only
2268 * upper bounds on the set dimension.
2269 * Otherwise, it should contain only lower bounds.
2271 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
2273 if (isl_int_is_pos(inc))
2274 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2275 else
2276 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2279 /* Extend a condition on a given iteration of a loop to one that
2280 * imposes the same condition on all previous iterations.
2281 * "domain" expresses the lower [upper] bound on the iterations
2282 * when inc is positive [negative].
2284 * In particular, we construct the condition (when inc is positive)
2286 * forall i' : (domain(i') and i' <= i) => cond(i')
2288 * which is equivalent to
2290 * not exists i' : domain(i') and i' <= i and not cond(i')
2292 * We construct this set by negating cond, applying a map
2294 * { [i'] -> [i] : domain(i') and i' <= i }
2296 * and then negating the result again.
2298 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2299 __isl_take isl_set *domain, isl_int inc)
2301 isl_map *previous_to_this;
2303 if (isl_int_is_pos(inc))
2304 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2305 else
2306 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2308 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2310 cond = isl_set_complement(cond);
2311 cond = isl_set_apply(cond, previous_to_this);
2312 cond = isl_set_complement(cond);
2314 return cond;
2317 /* Construct a domain of the form
2319 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2321 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2322 __isl_take isl_pw_aff *init, isl_int inc)
2324 isl_aff *aff;
2325 isl_space *dim;
2326 isl_set *set;
2328 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2329 dim = isl_pw_aff_get_domain_space(init);
2330 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2331 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
2332 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2334 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2335 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2336 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2337 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2339 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2341 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2343 return isl_set_params(set);
2346 /* Assuming "cond" represents a bound on a loop where the loop
2347 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2348 * is possible.
2350 * Under the given assumptions, wrapping is only possible if "cond" allows
2351 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2352 * increasing iterator and 0 in case of a decreasing iterator.
2354 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
2356 bool cw;
2357 isl_int limit;
2358 isl_set *test;
2360 test = isl_set_copy(cond);
2362 isl_int_init(limit);
2363 if (isl_int_is_neg(inc))
2364 isl_int_set_si(limit, 0);
2365 else {
2366 isl_int_set_si(limit, 1);
2367 isl_int_mul_2exp(limit, limit, get_type_size(iv));
2368 isl_int_sub_ui(limit, limit, 1);
2371 test = isl_set_fix(cond, isl_dim_set, 0, limit);
2372 cw = !isl_set_is_empty(test);
2373 isl_set_free(test);
2375 isl_int_clear(limit);
2377 return cw;
2380 /* Given a one-dimensional space, construct the following mapping on this
2381 * space
2383 * { [v] -> [v mod 2^width] }
2385 * where width is the number of bits used to represent the values
2386 * of the unsigned variable "iv".
2388 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
2389 ValueDecl *iv)
2391 isl_int mod;
2392 isl_aff *aff;
2393 isl_map *map;
2395 isl_int_init(mod);
2396 isl_int_set_si(mod, 1);
2397 isl_int_mul_2exp(mod, mod, get_type_size(iv));
2399 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2400 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2401 aff = isl_aff_mod(aff, mod);
2403 isl_int_clear(mod);
2405 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2406 map = isl_map_reverse(map);
2409 /* Project out the parameter "id" from "set".
2411 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2412 __isl_keep isl_id *id)
2414 int pos;
2416 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2417 if (pos >= 0)
2418 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2420 return set;
2423 /* Compute the set of parameters for which "set1" is a subset of "set2".
2425 * set1 is a subset of set2 if
2427 * forall i in set1 : i in set2
2429 * or
2431 * not exists i in set1 and i not in set2
2433 * i.e.,
2435 * not exists i in set1 \ set2
2437 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2438 __isl_take isl_set *set2)
2440 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2443 /* Compute the set of parameter values for which "cond" holds
2444 * on the next iteration for each element of "dom".
2446 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2447 * and then compute the set of parameters for which the result is a subset
2448 * of "cond".
2450 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2451 __isl_take isl_set *dom, isl_int inc)
2453 isl_space *space;
2454 isl_aff *aff;
2455 isl_map *next;
2457 space = isl_set_get_space(dom);
2458 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2459 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2460 aff = isl_aff_add_constant(aff, inc);
2461 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2463 dom = isl_set_apply(dom, next);
2465 return enforce_subset(dom, cond);
2468 /* Does "id" refer to a nested access?
2470 static bool is_nested_parameter(__isl_keep isl_id *id)
2472 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2475 /* Does parameter "pos" of "space" refer to a nested access?
2477 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2479 bool nested;
2480 isl_id *id;
2482 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2483 nested = is_nested_parameter(id);
2484 isl_id_free(id);
2486 return nested;
2489 /* Does "space" involve any parameters that refer to nested
2490 * accesses, i.e., parameters with no name?
2492 static bool has_nested(__isl_keep isl_space *space)
2494 int nparam;
2496 nparam = isl_space_dim(space, isl_dim_param);
2497 for (int i = 0; i < nparam; ++i)
2498 if (is_nested_parameter(space, i))
2499 return true;
2501 return false;
2504 /* Does "pa" involve any parameters that refer to nested
2505 * accesses, i.e., parameters with no name?
2507 static bool has_nested(__isl_keep isl_pw_aff *pa)
2509 isl_space *space;
2510 bool nested;
2512 space = isl_pw_aff_get_space(pa);
2513 nested = has_nested(space);
2514 isl_space_free(space);
2516 return nested;
2519 /* Construct a pet_scop for a for statement.
2520 * The for loop is required to be of the form
2522 * for (i = init; condition; ++i)
2524 * or
2526 * for (i = init; condition; --i)
2528 * The initialization of the for loop should either be an assignment
2529 * to an integer variable, or a declaration of such a variable with
2530 * initialization.
2532 * The condition is allowed to contain nested accesses, provided
2533 * they are not being written to inside the body of the loop.
2534 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2535 * essentially treated as a while loop, with iteration domain
2536 * { [i] : i >= init }.
2538 * We extract a pet_scop for the body and then embed it in a loop with
2539 * iteration domain and schedule
2541 * { [i] : i >= init and condition' }
2542 * { [i] -> [i] }
2544 * or
2546 * { [i] : i <= init and condition' }
2547 * { [i] -> [-i] }
2549 * Where condition' is equal to condition if the latter is
2550 * a simple upper [lower] bound and a condition that is extended
2551 * to apply to all previous iterations otherwise.
2553 * If the condition is non-affine, then we drop the condition from the
2554 * iteration domain and instead create a separate statement
2555 * for evaluating the condition. The body is then filtered to depend
2556 * on the result of the condition evaluating to true on all iterations
2557 * up to the current iteration, while the evaluation the condition itself
2558 * is filtered to depend on the result of the condition evaluating to true
2559 * on all previous iterations.
2560 * The context of the scop representing the body is dropped
2561 * because we don't know how many times the body will be executed,
2562 * if at all.
2564 * If the stride of the loop is not 1, then "i >= init" is replaced by
2566 * (exists a: i = init + stride * a and a >= 0)
2568 * If the loop iterator i is unsigned, then wrapping may occur.
2569 * During the computation, we work with a virtual iterator that
2570 * does not wrap. However, the condition in the code applies
2571 * to the wrapped value, so we need to change condition(i)
2572 * into condition([i % 2^width]).
2573 * After computing the virtual domain and schedule, we apply
2574 * the function { [v] -> [v % 2^width] } to the domain and the domain
2575 * of the schedule. In order not to lose any information, we also
2576 * need to intersect the domain of the schedule with the virtual domain
2577 * first, since some iterations in the wrapped domain may be scheduled
2578 * several times, typically an infinite number of times.
2579 * Note that there may be no need to perform this final wrapping
2580 * if the loop condition (after wrapping) satisfies certain conditions.
2581 * However, the is_simple_bound condition is not enough since it doesn't
2582 * check if there even is an upper bound.
2584 * If the loop condition is non-affine, then we keep the virtual
2585 * iterator in the iteration domain and instead replace all accesses
2586 * to the original iterator by the wrapping of the virtual iterator.
2588 * Wrapping on unsigned iterators can be avoided entirely if
2589 * loop condition is simple, the loop iterator is incremented
2590 * [decremented] by one and the last value before wrapping cannot
2591 * possibly satisfy the loop condition.
2593 * Before extracting a pet_scop from the body we remove all
2594 * assignments in assigned_value to variables that are assigned
2595 * somewhere in the body of the loop.
2597 * Valid parameters for a for loop are those for which the initial
2598 * value itself, the increment on each domain iteration and
2599 * the condition on both the initial value and
2600 * the result of incrementing the iterator for each iteration of the domain
2601 * can be evaluated.
2602 * If the loop condition is non-affine, then we only consider validity
2603 * of the initial value.
2605 * If the body contains any break, then we keep track of it in "skip"
2606 * (if the skip condition is affine) or it is handled in scop_add_break
2607 * (if the skip condition is not affine).
2608 * Note that the affine break condition needs to be considered with
2609 * respect to previous iterations in the virtual domain (if any)
2610 * and that the domain needs to be kept virtual if there is a non-affine
2611 * break condition.
2613 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2615 BinaryOperator *ass;
2616 Decl *decl;
2617 Stmt *init;
2618 Expr *lhs, *rhs;
2619 ValueDecl *iv;
2620 isl_space *space;
2621 isl_set *domain;
2622 isl_map *sched;
2623 isl_set *cond = NULL;
2624 isl_set *skip = NULL;
2625 isl_id *id;
2626 struct pet_scop *scop, *scop_cond = NULL;
2627 assigned_value_cache cache(assigned_value);
2628 isl_int inc;
2629 bool is_one;
2630 bool is_unsigned;
2631 bool is_simple;
2632 bool is_virtual;
2633 bool keep_virtual = false;
2634 bool has_affine_break;
2635 bool has_var_break;
2636 isl_map *wrap = NULL;
2637 isl_pw_aff *pa, *pa_inc, *init_val;
2638 isl_set *valid_init;
2639 isl_set *valid_cond;
2640 isl_set *valid_cond_init;
2641 isl_set *valid_cond_next;
2642 isl_set *valid_inc;
2643 isl_map *test_access = NULL, *break_access = NULL;
2644 int stmt_id;
2646 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2647 return extract_infinite_for(stmt);
2649 init = stmt->getInit();
2650 if (!init) {
2651 unsupported(stmt);
2652 return NULL;
2654 if ((ass = initialization_assignment(init)) != NULL) {
2655 iv = extract_induction_variable(ass);
2656 if (!iv)
2657 return NULL;
2658 lhs = ass->getLHS();
2659 rhs = ass->getRHS();
2660 } else if ((decl = initialization_declaration(init)) != NULL) {
2661 VarDecl *var = extract_induction_variable(init, decl);
2662 if (!var)
2663 return NULL;
2664 iv = var;
2665 rhs = var->getInit();
2666 lhs = create_DeclRefExpr(var);
2667 } else {
2668 unsupported(stmt->getInit());
2669 return NULL;
2672 pa_inc = extract_increment(stmt, iv);
2673 if (!pa_inc)
2674 return NULL;
2676 isl_int_init(inc);
2677 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
2678 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
2679 isl_pw_aff_free(pa_inc);
2680 unsupported(stmt->getInc());
2681 isl_int_clear(inc);
2682 return NULL;
2684 valid_inc = isl_pw_aff_domain(pa_inc);
2686 is_unsigned = iv->getType()->isUnsignedIntegerType();
2688 assigned_value.erase(iv);
2689 clear_assignments clear(assigned_value);
2690 clear.TraverseStmt(stmt->getBody());
2692 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2694 pa = try_extract_nested_condition(stmt->getCond());
2695 if (allow_nested && (!pa || has_nested(pa)))
2696 stmt_id = n_stmt++;
2698 scop = extract(stmt->getBody());
2700 has_affine_break = scop &&
2701 pet_scop_has_affine_skip(scop, pet_skip_later);
2702 if (has_affine_break) {
2703 skip = pet_scop_get_skip(scop, pet_skip_later);
2704 skip = isl_set_fix_si(skip, isl_dim_set, 0, 1);
2705 skip = isl_set_params(skip);
2707 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
2708 if (has_var_break) {
2709 break_access = pet_scop_get_skip_map(scop, pet_skip_later);
2710 keep_virtual = true;
2713 if (pa && !is_nested_allowed(pa, scop)) {
2714 isl_pw_aff_free(pa);
2715 pa = NULL;
2718 if (!allow_nested && !pa)
2719 pa = try_extract_affine_condition(stmt->getCond());
2720 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2721 cond = isl_pw_aff_non_zero_set(pa);
2722 if (allow_nested && !cond) {
2723 int save_n_stmt = n_stmt;
2724 test_access = create_test_access(ctx, n_test++);
2725 n_stmt = stmt_id;
2726 scop_cond = extract_non_affine_condition(stmt->getCond(),
2727 isl_map_copy(test_access));
2728 n_stmt = save_n_stmt;
2729 scop_cond = scop_add_array(scop_cond, test_access, ast_context);
2730 scop_cond = pet_scop_prefix(scop_cond, 0);
2731 scop = pet_scop_reset_context(scop);
2732 scop = pet_scop_prefix(scop, 1);
2733 keep_virtual = true;
2734 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2737 cond = embed(cond, isl_id_copy(id));
2738 skip = embed(skip, isl_id_copy(id));
2739 valid_cond = isl_set_coalesce(valid_cond);
2740 valid_cond = embed(valid_cond, isl_id_copy(id));
2741 valid_inc = embed(valid_inc, isl_id_copy(id));
2742 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
2743 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2745 init_val = extract_affine(rhs);
2746 valid_cond_init = enforce_subset(
2747 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
2748 isl_set_copy(valid_cond));
2749 if (is_one && !is_virtual) {
2750 isl_pw_aff_free(init_val);
2751 pa = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
2752 lhs, rhs, init);
2753 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2754 valid_init = set_project_out_by_id(valid_init, id);
2755 domain = isl_pw_aff_non_zero_set(pa);
2756 } else {
2757 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2758 domain = strided_domain(isl_id_copy(id), init_val, inc);
2761 domain = embed(domain, isl_id_copy(id));
2762 if (is_virtual) {
2763 isl_map *rev_wrap;
2764 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2765 rev_wrap = isl_map_reverse(isl_map_copy(wrap));
2766 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2767 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
2768 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2769 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2771 cond = isl_set_gist(cond, isl_set_copy(domain));
2772 is_simple = is_simple_bound(cond, inc);
2773 if (!is_simple)
2774 cond = valid_for_each_iteration(cond,
2775 isl_set_copy(domain), inc);
2776 domain = isl_set_intersect(domain, cond);
2777 if (has_affine_break) {
2778 skip = isl_set_intersect(skip , isl_set_copy(domain));
2779 skip = after(skip, isl_int_sgn(inc));
2780 domain = isl_set_subtract(domain, skip);
2782 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2783 space = isl_space_from_domain(isl_set_get_space(domain));
2784 space = isl_space_add_dims(space, isl_dim_out, 1);
2785 sched = isl_map_universe(space);
2786 if (isl_int_is_pos(inc))
2787 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2788 else
2789 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2791 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain), inc);
2792 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2794 if (is_virtual && !keep_virtual) {
2795 wrap = isl_map_set_dim_id(wrap,
2796 isl_dim_out, 0, isl_id_copy(id));
2797 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2798 domain = isl_set_apply(domain, isl_map_copy(wrap));
2799 sched = isl_map_apply_domain(sched, wrap);
2801 if (!(is_virtual && keep_virtual)) {
2802 space = isl_set_get_space(domain);
2803 wrap = isl_map_identity(isl_space_map_from_set(space));
2806 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
2807 isl_map_copy(sched), isl_map_copy(wrap), isl_id_copy(id));
2808 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
2809 scop = resolve_nested(scop);
2810 if (has_var_break)
2811 scop = scop_add_break(scop, break_access, isl_set_copy(domain),
2812 isl_int_sgn(inc));
2813 if (test_access) {
2814 scop = scop_add_while(scop_cond, scop, test_access, domain,
2815 isl_int_sgn(inc));
2816 isl_set_free(valid_inc);
2817 } else {
2818 scop = pet_scop_restrict_context(scop, valid_inc);
2819 scop = pet_scop_restrict_context(scop, valid_cond_next);
2820 scop = pet_scop_restrict_context(scop, valid_cond_init);
2821 isl_set_free(domain);
2823 clear_assignment(assigned_value, iv);
2825 isl_int_clear(inc);
2827 scop = pet_scop_restrict_context(scop, valid_init);
2829 return scop;
2832 struct pet_scop *PetScan::extract(CompoundStmt *stmt)
2834 return extract(stmt->children());
2837 /* Does parameter "pos" of "map" refer to a nested access?
2839 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2841 bool nested;
2842 isl_id *id;
2844 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2845 nested = is_nested_parameter(id);
2846 isl_id_free(id);
2848 return nested;
2851 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2853 static int n_nested_parameter(__isl_keep isl_space *space)
2855 int n = 0;
2856 int nparam;
2858 nparam = isl_space_dim(space, isl_dim_param);
2859 for (int i = 0; i < nparam; ++i)
2860 if (is_nested_parameter(space, i))
2861 ++n;
2863 return n;
2866 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2868 static int n_nested_parameter(__isl_keep isl_map *map)
2870 isl_space *space;
2871 int n;
2873 space = isl_map_get_space(map);
2874 n = n_nested_parameter(space);
2875 isl_space_free(space);
2877 return n;
2880 /* For each nested access parameter in "space",
2881 * construct a corresponding pet_expr, place it in args and
2882 * record its position in "param2pos".
2883 * "n_arg" is the number of elements that are already in args.
2884 * The position recorded in "param2pos" takes this number into account.
2885 * If the pet_expr corresponding to a parameter is identical to
2886 * the pet_expr corresponding to an earlier parameter, then these two
2887 * parameters are made to refer to the same element in args.
2889 * Return the final number of elements in args or -1 if an error has occurred.
2891 int PetScan::extract_nested(__isl_keep isl_space *space,
2892 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
2894 int nparam;
2896 nparam = isl_space_dim(space, isl_dim_param);
2897 for (int i = 0; i < nparam; ++i) {
2898 int j;
2899 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2900 Expr *nested;
2902 if (!is_nested_parameter(id)) {
2903 isl_id_free(id);
2904 continue;
2907 nested = (Expr *) isl_id_get_user(id);
2908 args[n_arg] = extract_expr(nested);
2909 if (!args[n_arg])
2910 return -1;
2912 for (j = 0; j < n_arg; ++j)
2913 if (pet_expr_is_equal(args[j], args[n_arg]))
2914 break;
2916 if (j < n_arg) {
2917 pet_expr_free(args[n_arg]);
2918 args[n_arg] = NULL;
2919 param2pos[i] = j;
2920 } else
2921 param2pos[i] = n_arg++;
2923 isl_id_free(id);
2926 return n_arg;
2929 /* For each nested access parameter in the access relations in "expr",
2930 * construct a corresponding pet_expr, place it in expr->args and
2931 * record its position in "param2pos".
2932 * n is the number of nested access parameters.
2934 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
2935 std::map<int,int> &param2pos)
2937 isl_space *space;
2939 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
2940 expr->n_arg = n;
2941 if (!expr->args)
2942 goto error;
2944 space = isl_map_get_space(expr->acc.access);
2945 n = extract_nested(space, 0, expr->args, param2pos);
2946 isl_space_free(space);
2948 if (n < 0)
2949 goto error;
2951 expr->n_arg = n;
2952 return expr;
2953 error:
2954 pet_expr_free(expr);
2955 return NULL;
2958 /* Look for parameters in any access relation in "expr" that
2959 * refer to nested accesses. In particular, these are
2960 * parameters with no name.
2962 * If there are any such parameters, then the domain of the access
2963 * relation, which is still [] at this point, is replaced by
2964 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2965 * (after identifying identical nested accesses).
2966 * The parameters are then equated to the corresponding t dimensions
2967 * and subsequently projected out.
2968 * param2pos maps the position of the parameter to the position
2969 * of the corresponding t dimension.
2971 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
2973 int n;
2974 int nparam;
2975 int n_in;
2976 isl_space *dim;
2977 isl_map *map;
2978 std::map<int,int> param2pos;
2980 if (!expr)
2981 return expr;
2983 for (int i = 0; i < expr->n_arg; ++i) {
2984 expr->args[i] = resolve_nested(expr->args[i]);
2985 if (!expr->args[i]) {
2986 pet_expr_free(expr);
2987 return NULL;
2991 if (expr->type != pet_expr_access)
2992 return expr;
2994 n = n_nested_parameter(expr->acc.access);
2995 if (n == 0)
2996 return expr;
2998 expr = extract_nested(expr, n, param2pos);
2999 if (!expr)
3000 return NULL;
3002 n = expr->n_arg;
3003 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
3004 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
3005 dim = isl_map_get_space(expr->acc.access);
3006 dim = isl_space_domain(dim);
3007 dim = isl_space_from_domain(dim);
3008 dim = isl_space_add_dims(dim, isl_dim_out, n);
3009 map = isl_map_universe(dim);
3010 map = isl_map_domain_map(map);
3011 map = isl_map_reverse(map);
3012 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
3014 for (int i = nparam - 1; i >= 0; --i) {
3015 isl_id *id = isl_map_get_dim_id(expr->acc.access,
3016 isl_dim_param, i);
3017 if (!is_nested_parameter(id)) {
3018 isl_id_free(id);
3019 continue;
3022 expr->acc.access = isl_map_equate(expr->acc.access,
3023 isl_dim_param, i, isl_dim_in,
3024 n_in + param2pos[i]);
3025 expr->acc.access = isl_map_project_out(expr->acc.access,
3026 isl_dim_param, i, 1);
3028 isl_id_free(id);
3031 return expr;
3032 error:
3033 pet_expr_free(expr);
3034 return NULL;
3037 /* Convert a top-level pet_expr to a pet_scop with one statement.
3038 * This mainly involves resolving nested expression parameters
3039 * and setting the name of the iteration space.
3040 * The name is given by "label" if it is non-NULL. Otherwise,
3041 * it is of the form S_<n_stmt>.
3043 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
3044 __isl_take isl_id *label)
3046 struct pet_stmt *ps;
3047 SourceLocation loc = stmt->getLocStart();
3048 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3050 expr = resolve_nested(expr);
3051 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
3052 return pet_scop_from_pet_stmt(ctx, ps);
3055 /* Check if we can extract an affine expression from "expr".
3056 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3057 * We turn on autodetection so that we won't generate any warnings
3058 * and turn off nesting, so that we won't accept any non-affine constructs.
3060 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3062 isl_pw_aff *pwaff;
3063 int save_autodetect = options->autodetect;
3064 bool save_nesting = nesting_enabled;
3066 options->autodetect = 1;
3067 nesting_enabled = false;
3069 pwaff = extract_affine(expr);
3071 options->autodetect = save_autodetect;
3072 nesting_enabled = save_nesting;
3074 return pwaff;
3077 /* Check whether "expr" is an affine expression.
3079 bool PetScan::is_affine(Expr *expr)
3081 isl_pw_aff *pwaff;
3083 pwaff = try_extract_affine(expr);
3084 isl_pw_aff_free(pwaff);
3086 return pwaff != NULL;
3089 /* Check if we can extract an affine constraint from "expr".
3090 * Return the constraint as an isl_set if we can and NULL otherwise.
3091 * We turn on autodetection so that we won't generate any warnings
3092 * and turn off nesting, so that we won't accept any non-affine constructs.
3094 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3096 isl_pw_aff *cond;
3097 int save_autodetect = options->autodetect;
3098 bool save_nesting = nesting_enabled;
3100 options->autodetect = 1;
3101 nesting_enabled = false;
3103 cond = extract_condition(expr);
3105 options->autodetect = save_autodetect;
3106 nesting_enabled = save_nesting;
3108 return cond;
3111 /* Check whether "expr" is an affine constraint.
3113 bool PetScan::is_affine_condition(Expr *expr)
3115 isl_pw_aff *cond;
3117 cond = try_extract_affine_condition(expr);
3118 isl_pw_aff_free(cond);
3120 return cond != NULL;
3123 /* Check if we can extract a condition from "expr".
3124 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3125 * If allow_nested is set, then the condition may involve parameters
3126 * corresponding to nested accesses.
3127 * We turn on autodetection so that we won't generate any warnings.
3129 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3131 isl_pw_aff *cond;
3132 int save_autodetect = options->autodetect;
3133 bool save_nesting = nesting_enabled;
3135 options->autodetect = 1;
3136 nesting_enabled = allow_nested;
3137 cond = extract_condition(expr);
3139 options->autodetect = save_autodetect;
3140 nesting_enabled = save_nesting;
3142 return cond;
3145 /* If the top-level expression of "stmt" is an assignment, then
3146 * return that assignment as a BinaryOperator.
3147 * Otherwise return NULL.
3149 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3151 BinaryOperator *ass;
3153 if (!stmt)
3154 return NULL;
3155 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3156 return NULL;
3158 ass = cast<BinaryOperator>(stmt);
3159 if(ass->getOpcode() != BO_Assign)
3160 return NULL;
3162 return ass;
3165 /* Check if the given if statement is a conditional assignement
3166 * with a non-affine condition. If so, construct a pet_scop
3167 * corresponding to this conditional assignment. Otherwise return NULL.
3169 * In particular we check if "stmt" is of the form
3171 * if (condition)
3172 * a = f(...);
3173 * else
3174 * a = g(...);
3176 * where a is some array or scalar access.
3177 * The constructed pet_scop then corresponds to the expression
3179 * a = condition ? f(...) : g(...)
3181 * All access relations in f(...) are intersected with condition
3182 * while all access relation in g(...) are intersected with the complement.
3184 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3186 BinaryOperator *ass_then, *ass_else;
3187 isl_map *write_then, *write_else;
3188 isl_set *cond, *comp;
3189 isl_map *map;
3190 isl_pw_aff *pa;
3191 int equal;
3192 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3193 bool save_nesting = nesting_enabled;
3195 if (!options->detect_conditional_assignment)
3196 return NULL;
3198 ass_then = top_assignment_or_null(stmt->getThen());
3199 ass_else = top_assignment_or_null(stmt->getElse());
3201 if (!ass_then || !ass_else)
3202 return NULL;
3204 if (is_affine_condition(stmt->getCond()))
3205 return NULL;
3207 write_then = extract_access(ass_then->getLHS());
3208 write_else = extract_access(ass_else->getLHS());
3210 equal = isl_map_is_equal(write_then, write_else);
3211 isl_map_free(write_else);
3212 if (equal < 0 || !equal) {
3213 isl_map_free(write_then);
3214 return NULL;
3217 nesting_enabled = allow_nested;
3218 pa = extract_condition(stmt->getCond());
3219 nesting_enabled = save_nesting;
3220 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3221 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3222 map = isl_map_from_range(isl_set_from_pw_aff(pa));
3224 pe_cond = pet_expr_from_access(map);
3226 pe_then = extract_expr(ass_then->getRHS());
3227 pe_then = pet_expr_restrict(pe_then, cond);
3228 pe_else = extract_expr(ass_else->getRHS());
3229 pe_else = pet_expr_restrict(pe_else, comp);
3231 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
3232 pe_write = pet_expr_from_access(write_then);
3233 if (pe_write) {
3234 pe_write->acc.write = 1;
3235 pe_write->acc.read = 0;
3237 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
3238 return extract(stmt, pe);
3241 /* Create a pet_scop with a single statement evaluating "cond"
3242 * and writing the result to a virtual scalar, as expressed by
3243 * "access".
3245 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
3246 __isl_take isl_map *access)
3248 struct pet_expr *expr, *write;
3249 struct pet_stmt *ps;
3250 struct pet_scop *scop;
3251 SourceLocation loc = cond->getLocStart();
3252 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3254 write = pet_expr_from_access(access);
3255 if (write) {
3256 write->acc.write = 1;
3257 write->acc.read = 0;
3259 expr = extract_expr(cond);
3260 expr = resolve_nested(expr);
3261 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
3262 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
3263 scop = pet_scop_from_pet_stmt(ctx, ps);
3264 scop = resolve_nested(scop);
3266 return scop;
3269 extern "C" {
3270 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
3271 void *user);
3274 /* Apply the map pointed to by "user" to the domain of the access
3275 * relation, thereby embedding it in the range of the map.
3276 * The domain of both relations is the zero-dimensional domain.
3278 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
3280 isl_map *map = (isl_map *) user;
3282 return isl_map_apply_domain(access, isl_map_copy(map));
3285 /* Apply "map" to all access relations in "expr".
3287 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
3289 return pet_expr_foreach_access(expr, &embed_access, map);
3292 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3294 static int n_nested_parameter(__isl_keep isl_set *set)
3296 isl_space *space;
3297 int n;
3299 space = isl_set_get_space(set);
3300 n = n_nested_parameter(space);
3301 isl_space_free(space);
3303 return n;
3306 /* Remove all parameters from "map" that refer to nested accesses.
3308 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
3310 int nparam;
3311 isl_space *space;
3313 space = isl_map_get_space(map);
3314 nparam = isl_space_dim(space, isl_dim_param);
3315 for (int i = nparam - 1; i >= 0; --i)
3316 if (is_nested_parameter(space, i))
3317 map = isl_map_project_out(map, isl_dim_param, i, 1);
3318 isl_space_free(space);
3320 return map;
3323 extern "C" {
3324 static __isl_give isl_map *access_remove_nested_parameters(
3325 __isl_take isl_map *access, void *user);
3328 static __isl_give isl_map *access_remove_nested_parameters(
3329 __isl_take isl_map *access, void *user)
3331 return remove_nested_parameters(access);
3334 /* Remove all nested access parameters from the schedule and all
3335 * accesses of "stmt".
3336 * There is no need to remove them from the domain as these parameters
3337 * have already been removed from the domain when this function is called.
3339 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
3341 if (!stmt)
3342 return NULL;
3343 stmt->schedule = remove_nested_parameters(stmt->schedule);
3344 stmt->body = pet_expr_foreach_access(stmt->body,
3345 &access_remove_nested_parameters, NULL);
3346 if (!stmt->schedule || !stmt->body)
3347 goto error;
3348 for (int i = 0; i < stmt->n_arg; ++i) {
3349 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
3350 &access_remove_nested_parameters, NULL);
3351 if (!stmt->args[i])
3352 goto error;
3355 return stmt;
3356 error:
3357 pet_stmt_free(stmt);
3358 return NULL;
3361 /* For each nested access parameter in the domain of "stmt",
3362 * construct a corresponding pet_expr, place it before the original
3363 * elements in stmt->args and record its position in "param2pos".
3364 * n is the number of nested access parameters.
3366 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3367 std::map<int,int> &param2pos)
3369 int i;
3370 isl_space *space;
3371 int n_arg;
3372 struct pet_expr **args;
3374 n_arg = stmt->n_arg;
3375 args = isl_calloc_array(ctx, struct pet_expr *, n + n_arg);
3376 if (!args)
3377 goto error;
3379 space = isl_set_get_space(stmt->domain);
3380 n_arg = extract_nested(space, 0, args, param2pos);
3381 isl_space_free(space);
3383 if (n_arg < 0)
3384 goto error;
3386 for (i = 0; i < stmt->n_arg; ++i)
3387 args[n_arg + i] = stmt->args[i];
3388 free(stmt->args);
3389 stmt->args = args;
3390 stmt->n_arg += n_arg;
3392 return stmt;
3393 error:
3394 if (args) {
3395 for (i = 0; i < n; ++i)
3396 pet_expr_free(args[i]);
3397 free(args);
3399 pet_stmt_free(stmt);
3400 return NULL;
3403 /* Check whether any of the arguments i of "stmt" starting at position "n"
3404 * is equal to one of the first "n" arguments j.
3405 * If so, combine the constraints on arguments i and j and remove
3406 * argument i.
3408 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3410 int i, j;
3411 isl_map *map;
3413 if (!stmt)
3414 return NULL;
3415 if (n == 0)
3416 return stmt;
3417 if (n == stmt->n_arg)
3418 return stmt;
3420 map = isl_set_unwrap(stmt->domain);
3422 for (i = stmt->n_arg - 1; i >= n; --i) {
3423 for (j = 0; j < n; ++j)
3424 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3425 break;
3426 if (j >= n)
3427 continue;
3429 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3430 map = isl_map_project_out(map, isl_dim_out, i, 1);
3432 pet_expr_free(stmt->args[i]);
3433 for (j = i; j + 1 < stmt->n_arg; ++j)
3434 stmt->args[j] = stmt->args[j + 1];
3435 stmt->n_arg--;
3438 stmt->domain = isl_map_wrap(map);
3439 if (!stmt->domain)
3440 goto error;
3441 return stmt;
3442 error:
3443 pet_stmt_free(stmt);
3444 return NULL;
3447 /* Look for parameters in the iteration domain of "stmt" that
3448 * refer to nested accesses. In particular, these are
3449 * parameters with no name.
3451 * If there are any such parameters, then as many extra variables
3452 * (after identifying identical nested accesses) are inserted in the
3453 * range of the map wrapped inside the domain, before the original variables.
3454 * If the original domain is not a wrapped map, then a new wrapped
3455 * map is created with zero output dimensions.
3456 * The parameters are then equated to the corresponding output dimensions
3457 * and subsequently projected out, from the iteration domain,
3458 * the schedule and the access relations.
3459 * For each of the output dimensions, a corresponding argument
3460 * expression is inserted. Initially they are created with
3461 * a zero-dimensional domain, so they have to be embedded
3462 * in the current iteration domain.
3463 * param2pos maps the position of the parameter to the position
3464 * of the corresponding output dimension in the wrapped map.
3466 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3468 int n;
3469 int nparam;
3470 unsigned n_arg;
3471 isl_map *map;
3472 std::map<int,int> param2pos;
3474 if (!stmt)
3475 return NULL;
3477 n = n_nested_parameter(stmt->domain);
3478 if (n == 0)
3479 return stmt;
3481 n_arg = stmt->n_arg;
3482 stmt = extract_nested(stmt, n, param2pos);
3483 if (!stmt)
3484 return NULL;
3486 n = stmt->n_arg - n_arg;
3487 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3488 if (isl_set_is_wrapping(stmt->domain))
3489 map = isl_set_unwrap(stmt->domain);
3490 else
3491 map = isl_map_from_domain(stmt->domain);
3492 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3494 for (int i = nparam - 1; i >= 0; --i) {
3495 isl_id *id;
3497 if (!is_nested_parameter(map, i))
3498 continue;
3500 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
3501 isl_dim_out);
3502 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3503 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3504 param2pos[i]);
3505 map = isl_map_project_out(map, isl_dim_param, i, 1);
3508 stmt->domain = isl_map_wrap(map);
3510 map = isl_set_unwrap(isl_set_copy(stmt->domain));
3511 map = isl_map_from_range(isl_map_domain(map));
3512 for (int pos = 0; pos < n; ++pos)
3513 stmt->args[pos] = embed(stmt->args[pos], map);
3514 isl_map_free(map);
3516 stmt = remove_nested_parameters(stmt);
3517 stmt = remove_duplicate_arguments(stmt, n);
3519 return stmt;
3520 error:
3521 pet_stmt_free(stmt);
3522 return NULL;
3525 /* For each statement in "scop", move the parameters that correspond
3526 * to nested access into the ranges of the domains and create
3527 * corresponding argument expressions.
3529 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3531 if (!scop)
3532 return NULL;
3534 for (int i = 0; i < scop->n_stmt; ++i) {
3535 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3536 if (!scop->stmts[i])
3537 goto error;
3540 return scop;
3541 error:
3542 pet_scop_free(scop);
3543 return NULL;
3546 /* Given an access expression "expr", is the variable accessed by
3547 * "expr" assigned anywhere inside "scop"?
3549 static bool is_assigned(pet_expr *expr, pet_scop *scop)
3551 bool assigned = false;
3552 isl_id *id;
3554 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
3555 assigned = pet_scop_writes(scop, id);
3556 isl_id_free(id);
3558 return assigned;
3561 /* Are all nested access parameters in "pa" allowed given "scop".
3562 * In particular, is none of them written by anywhere inside "scop".
3564 * If "scop" has any skip conditions, then no nested access parameters
3565 * are allowed. In particular, if there is any nested access in a guard
3566 * for a piece of code containing a "continue", then we want to introduce
3567 * a separate statement for evaluating this guard so that we can express
3568 * that the result is false for all previous iterations.
3570 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3572 int nparam;
3574 if (!scop)
3575 return true;
3577 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3578 for (int i = 0; i < nparam; ++i) {
3579 Expr *nested;
3580 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3581 pet_expr *expr;
3582 bool allowed;
3584 if (!is_nested_parameter(id)) {
3585 isl_id_free(id);
3586 continue;
3589 if (pet_scop_has_skip(scop, pet_skip_now)) {
3590 isl_id_free(id);
3591 return false;
3594 nested = (Expr *) isl_id_get_user(id);
3595 expr = extract_expr(nested);
3596 allowed = expr && expr->type == pet_expr_access &&
3597 !is_assigned(expr, scop);
3599 pet_expr_free(expr);
3600 isl_id_free(id);
3602 if (!allowed)
3603 return false;
3606 return true;
3609 /* Do we need to construct a skip condition of the given type
3610 * on an if statement, given that the if condition is non-affine?
3612 * pet_scop_filter_skip can only handle the case where the if condition
3613 * holds (the then branch) and the skip condition is universal.
3614 * In any other case, we need to construct a new skip condition.
3616 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3617 bool have_else, enum pet_skip type)
3619 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
3620 return true;
3621 if (scop_then && pet_scop_has_skip(scop_then, type) &&
3622 !pet_scop_has_universal_skip(scop_then, type))
3623 return true;
3624 return false;
3627 /* Do we need to construct a skip condition of the given type
3628 * on an if statement, given that the if condition is affine?
3630 * There is no need to construct a new skip condition if all
3631 * the skip conditions are affine.
3633 static bool need_skip_aff(struct pet_scop *scop_then,
3634 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
3636 if (scop_then && pet_scop_has_var_skip(scop_then, type))
3637 return true;
3638 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
3639 return true;
3640 return false;
3643 /* Do we need to construct a skip condition of the given type
3644 * on an if statement?
3646 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3647 bool have_else, enum pet_skip type, bool affine)
3649 if (affine)
3650 return need_skip_aff(scop_then, scop_else, have_else, type);
3651 else
3652 return need_skip(scop_then, scop_else, have_else, type);
3655 /* Construct an affine expression pet_expr that is evaluates
3656 * to the constant "val".
3658 static struct pet_expr *universally(isl_ctx *ctx, int val)
3660 isl_space *space;
3661 isl_map *map;
3663 space = isl_space_alloc(ctx, 0, 0, 1);
3664 map = isl_map_universe(space);
3665 map = isl_map_fix_si(map, isl_dim_out, 0, val);
3667 return pet_expr_from_access(map);
3670 /* Construct an affine expression pet_expr that is evaluates
3671 * to the constant 1.
3673 static struct pet_expr *universally_true(isl_ctx *ctx)
3675 return universally(ctx, 1);
3678 /* Construct an affine expression pet_expr that is evaluates
3679 * to the constant 0.
3681 static struct pet_expr *universally_false(isl_ctx *ctx)
3683 return universally(ctx, 0);
3686 /* Given an access relation "test_access" for the if condition,
3687 * an access relation "skip_access" for the skip condition and
3688 * scops for the then and else branches, construct a scop for
3689 * computing "skip_access".
3691 * The computed scop contains a single statement that essentially does
3693 * skip_cond = test_cond ? skip_cond_then : skip_cond_else
3695 * If the skip conditions of the then and/or else branch are not affine,
3696 * then they need to be filtered by test_access.
3697 * If they are missing, then this means the skip condition is false.
3699 * Since we are constructing a skip condition for the if statement,
3700 * the skip conditions on the then and else branches are removed.
3702 static struct pet_scop *extract_skip(PetScan *scan,
3703 __isl_take isl_map *test_access, __isl_take isl_map *skip_access,
3704 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
3705 enum pet_skip type)
3707 struct pet_expr *expr_then, *expr_else, *expr, *expr_skip;
3708 struct pet_stmt *stmt;
3709 struct pet_scop *scop;
3710 isl_ctx *ctx = scan->ctx;
3712 if (!scop_then)
3713 goto error;
3714 if (have_else && !scop_else)
3715 goto error;
3717 if (pet_scop_has_skip(scop_then, type)) {
3718 expr_then = pet_scop_get_skip_expr(scop_then, type);
3719 pet_scop_reset_skip(scop_then, type);
3720 if (!pet_expr_is_affine(expr_then))
3721 expr_then = pet_expr_filter(expr_then,
3722 isl_map_copy(test_access), 1);
3723 } else
3724 expr_then = universally_false(ctx);
3726 if (have_else && pet_scop_has_skip(scop_else, type)) {
3727 expr_else = pet_scop_get_skip_expr(scop_else, type);
3728 pet_scop_reset_skip(scop_else, type);
3729 if (!pet_expr_is_affine(expr_else))
3730 expr_else = pet_expr_filter(expr_else,
3731 isl_map_copy(test_access), 0);
3732 } else
3733 expr_else = universally_false(ctx);
3735 expr = pet_expr_from_access(test_access);
3736 expr = pet_expr_new_ternary(ctx, expr, expr_then, expr_else);
3737 expr_skip = pet_expr_from_access(isl_map_copy(skip_access));
3738 if (expr_skip) {
3739 expr_skip->acc.write = 1;
3740 expr_skip->acc.read = 0;
3742 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
3743 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, scan->n_stmt++, expr);
3745 scop = pet_scop_from_pet_stmt(ctx, stmt);
3746 scop = scop_add_array(scop, skip_access, scan->ast_context);
3747 isl_map_free(skip_access);
3749 return scop;
3750 error:
3751 isl_map_free(test_access);
3752 isl_map_free(skip_access);
3753 return NULL;
3756 /* Is scop's skip_now condition equal to its skip_later condition?
3757 * In particular, this means that it either has no skip_now condition
3758 * or both a skip_now and a skip_later condition (that are equal to each other).
3760 static bool skip_equals_skip_later(struct pet_scop *scop)
3762 int has_skip_now, has_skip_later;
3763 int equal;
3764 isl_set *skip_now, *skip_later;
3766 if (!scop)
3767 return false;
3768 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
3769 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
3770 if (has_skip_now != has_skip_later)
3771 return false;
3772 if (!has_skip_now)
3773 return true;
3775 skip_now = pet_scop_get_skip(scop, pet_skip_now);
3776 skip_later = pet_scop_get_skip(scop, pet_skip_later);
3777 equal = isl_set_is_equal(skip_now, skip_later);
3778 isl_set_free(skip_now);
3779 isl_set_free(skip_later);
3781 return equal;
3784 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
3786 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
3788 pet_scop_reset_skip(scop1, pet_skip_later);
3789 pet_scop_reset_skip(scop2, pet_skip_later);
3792 /* Structure that handles the construction of skip conditions.
3794 * scop_then and scop_else represent the then and else branches
3795 * of the if statement
3797 * skip[type] is true if we need to construct a skip condition of that type
3798 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
3799 * are equal to each other
3800 * access[type] is the virtual array representing the skip condition
3801 * scop[type] is a scop for computing the skip condition
3803 struct pet_skip_info {
3804 isl_ctx *ctx;
3806 bool skip[2];
3807 bool equal;
3808 isl_map *access[2];
3809 struct pet_scop *scop[2];
3811 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
3813 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
3816 /* Structure that handles the construction of skip conditions on if statements.
3818 * scop_then and scop_else represent the then and else branches
3819 * of the if statement
3821 struct pet_skip_info_if : public pet_skip_info {
3822 struct pet_scop *scop_then, *scop_else;
3823 bool have_else;
3825 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
3826 struct pet_scop *scop_else, bool have_else, bool affine);
3827 void extract(PetScan *scan, __isl_keep isl_map *access,
3828 enum pet_skip type);
3829 void extract(PetScan *scan, __isl_keep isl_map *access);
3830 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
3831 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
3832 int offset);
3833 struct pet_scop *add(struct pet_scop *scop, int offset);
3836 /* Initialize a pet_skip_info_if structure based on the then and else branches
3837 * and based on whether the if condition is affine or not.
3839 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
3840 struct pet_scop *scop_else, bool have_else, bool affine) :
3841 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
3842 have_else(have_else)
3844 skip[pet_skip_now] =
3845 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
3846 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
3847 (!have_else || skip_equals_skip_later(scop_else));
3848 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
3849 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
3852 /* If we need to construct a skip condition of the given type,
3853 * then do so now.
3855 * "map" represents the if condition.
3857 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_map *map,
3858 enum pet_skip type)
3860 if (!skip[type])
3861 return;
3863 access[type] = create_test_access(isl_map_get_ctx(map), scan->n_test++);
3864 scop[type] = extract_skip(scan, isl_map_copy(map),
3865 isl_map_copy(access[type]),
3866 scop_then, scop_else, have_else, type);
3869 /* Construct the required skip conditions, given the if condition "map".
3871 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_map *map)
3873 extract(scan, map, pet_skip_now);
3874 extract(scan, map, pet_skip_later);
3875 if (equal)
3876 drop_skip_later(scop_then, scop_else);
3879 /* Construct the required skip conditions, given the if condition "cond".
3881 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
3883 isl_set *test_set;
3884 isl_map *test;
3886 if (!skip[pet_skip_now] && !skip[pet_skip_later])
3887 return;
3889 test_set = isl_set_from_pw_aff(isl_pw_aff_copy(cond));
3890 test = isl_map_from_range(test_set);
3891 extract(scan, test);
3892 isl_map_free(test);
3895 /* Add the computed skip condition of the give type to "main" and
3896 * add the scop for computing the condition at the given offset.
3898 * If equal is set, then we only computed a skip condition for pet_skip_now,
3899 * but we also need to set it as main's pet_skip_later.
3901 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
3902 enum pet_skip type, int offset)
3904 isl_set *skip_set;
3906 if (!skip[type])
3907 return main;
3909 skip_set = isl_map_range(access[type]);
3910 access[type] = NULL;
3911 scop[type] = pet_scop_prefix(scop[type], offset);
3912 main = pet_scop_add_par(ctx, main, scop[type]);
3913 scop[type] = NULL;
3915 if (equal)
3916 main = pet_scop_set_skip(main, pet_skip_later,
3917 isl_set_copy(skip_set));
3919 main = pet_scop_set_skip(main, type, skip_set);
3921 return main;
3924 /* Add the computed skip conditions to "main" and
3925 * add the scops for computing the conditions at the given offset.
3927 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
3929 scop = add(scop, pet_skip_now, offset);
3930 scop = add(scop, pet_skip_later, offset);
3932 return scop;
3935 /* Construct a pet_scop for a non-affine if statement.
3937 * We create a separate statement that writes the result
3938 * of the non-affine condition to a virtual scalar.
3939 * A constraint requiring the value of this virtual scalar to be one
3940 * is added to the iteration domains of the then branch.
3941 * Similarly, a constraint requiring the value of this virtual scalar
3942 * to be zero is added to the iteration domains of the else branch, if any.
3943 * We adjust the schedules to ensure that the virtual scalar is written
3944 * before it is read.
3946 * If there are any breaks or continues in the then and/or else
3947 * branches, then we may have to compute a new skip condition.
3948 * This is handled using a pet_skip_info_if object.
3949 * On initialization, the object checks if skip conditions need
3950 * to be computed. If so, it does so in "extract" and adds them in "add".
3952 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
3953 struct pet_scop *scop_then, struct pet_scop *scop_else,
3954 bool have_else, int stmt_id)
3956 struct pet_scop *scop;
3957 isl_map *test_access;
3958 int save_n_stmt = n_stmt;
3960 test_access = create_test_access(ctx, n_test++);
3961 n_stmt = stmt_id;
3962 scop = extract_non_affine_condition(cond, isl_map_copy(test_access));
3963 n_stmt = save_n_stmt;
3964 scop = scop_add_array(scop, test_access, ast_context);
3966 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
3967 skip.extract(this, test_access);
3969 scop = pet_scop_prefix(scop, 0);
3970 scop_then = pet_scop_prefix(scop_then, 1);
3971 scop_then = pet_scop_filter(scop_then, isl_map_copy(test_access), 1);
3972 if (have_else) {
3973 scop_else = pet_scop_prefix(scop_else, 1);
3974 scop_else = pet_scop_filter(scop_else, test_access, 0);
3975 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
3976 } else
3977 isl_map_free(test_access);
3979 scop = pet_scop_add_seq(ctx, scop, scop_then);
3981 scop = skip.add(scop, 2);
3983 return scop;
3986 /* Construct a pet_scop for an if statement.
3988 * If the condition fits the pattern of a conditional assignment,
3989 * then it is handled by extract_conditional_assignment.
3990 * Otherwise, we do the following.
3992 * If the condition is affine, then the condition is added
3993 * to the iteration domains of the then branch, while the
3994 * opposite of the condition in added to the iteration domains
3995 * of the else branch, if any.
3996 * We allow the condition to be dynamic, i.e., to refer to
3997 * scalars or array elements that may be written to outside
3998 * of the given if statement. These nested accesses are then represented
3999 * as output dimensions in the wrapping iteration domain.
4000 * If it also written _inside_ the then or else branch, then
4001 * we treat the condition as non-affine.
4002 * As explained in extract_non_affine_if, this will introduce
4003 * an extra statement.
4004 * For aesthetic reasons, we want this statement to have a statement
4005 * number that is lower than those of the then and else branches.
4006 * In order to evaluate if will need such a statement, however, we
4007 * first construct scops for the then and else branches.
4008 * We therefore reserve a statement number if we might have to
4009 * introduce such an extra statement.
4011 * If the condition is not affine, then the scop is created in
4012 * extract_non_affine_if.
4014 * If there are any breaks or continues in the then and/or else
4015 * branches, then we may have to compute a new skip condition.
4016 * This is handled using a pet_skip_info_if object.
4017 * On initialization, the object checks if skip conditions need
4018 * to be computed. If so, it does so in "extract" and adds them in "add".
4020 struct pet_scop *PetScan::extract(IfStmt *stmt)
4022 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4023 isl_pw_aff *cond;
4024 int stmt_id;
4025 isl_set *set;
4026 isl_set *valid;
4028 scop = extract_conditional_assignment(stmt);
4029 if (scop)
4030 return scop;
4032 cond = try_extract_nested_condition(stmt->getCond());
4033 if (allow_nested && (!cond || has_nested(cond)))
4034 stmt_id = n_stmt++;
4037 assigned_value_cache cache(assigned_value);
4038 scop_then = extract(stmt->getThen());
4041 if (stmt->getElse()) {
4042 assigned_value_cache cache(assigned_value);
4043 scop_else = extract(stmt->getElse());
4044 if (options->autodetect) {
4045 if (scop_then && !scop_else) {
4046 partial = true;
4047 isl_pw_aff_free(cond);
4048 return scop_then;
4050 if (!scop_then && scop_else) {
4051 partial = true;
4052 isl_pw_aff_free(cond);
4053 return scop_else;
4058 if (cond &&
4059 (!is_nested_allowed(cond, scop_then) ||
4060 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4061 isl_pw_aff_free(cond);
4062 cond = NULL;
4064 if (allow_nested && !cond)
4065 return extract_non_affine_if(stmt->getCond(), scop_then,
4066 scop_else, stmt->getElse(), stmt_id);
4068 if (!cond)
4069 cond = extract_condition(stmt->getCond());
4071 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4072 skip.extract(this, cond);
4074 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4075 set = isl_pw_aff_non_zero_set(cond);
4076 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4078 if (stmt->getElse()) {
4079 set = isl_set_subtract(isl_set_copy(valid), set);
4080 scop_else = pet_scop_restrict(scop_else, set);
4081 scop = pet_scop_add_par(ctx, scop, scop_else);
4082 } else
4083 isl_set_free(set);
4084 scop = resolve_nested(scop);
4085 scop = pet_scop_restrict_context(scop, valid);
4087 if (skip)
4088 scop = pet_scop_prefix(scop, 0);
4089 scop = skip.add(scop, 1);
4091 return scop;
4094 /* Try and construct a pet_scop for a label statement.
4095 * We currently only allow labels on expression statements.
4097 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4099 isl_id *label;
4100 Stmt *sub;
4102 sub = stmt->getSubStmt();
4103 if (!isa<Expr>(sub)) {
4104 unsupported(stmt);
4105 return NULL;
4108 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4110 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4113 /* Construct a pet_scop for a continue statement.
4115 * We simply create an empty scop with a universal pet_skip_now
4116 * skip condition. This skip condition will then be taken into
4117 * account by the enclosing loop construct, possibly after
4118 * being incorporated into outer skip conditions.
4120 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4122 pet_scop *scop;
4123 isl_space *space;
4124 isl_set *set;
4126 scop = pet_scop_empty(ctx);
4127 if (!scop)
4128 return NULL;
4130 space = isl_space_set_alloc(ctx, 0, 1);
4131 set = isl_set_universe(space);
4132 set = isl_set_fix_si(set, isl_dim_set, 0, 1);
4133 scop = pet_scop_set_skip(scop, pet_skip_now, set);
4135 return scop;
4138 /* Construct a pet_scop for a break statement.
4140 * We simply create an empty scop with both a universal pet_skip_now
4141 * skip condition and a universal pet_skip_later skip condition.
4142 * These skip conditions will then be taken into
4143 * account by the enclosing loop construct, possibly after
4144 * being incorporated into outer skip conditions.
4146 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4148 pet_scop *scop;
4149 isl_space *space;
4150 isl_set *set;
4152 scop = pet_scop_empty(ctx);
4153 if (!scop)
4154 return NULL;
4156 space = isl_space_set_alloc(ctx, 0, 1);
4157 set = isl_set_universe(space);
4158 set = isl_set_fix_si(set, isl_dim_set, 0, 1);
4159 scop = pet_scop_set_skip(scop, pet_skip_now, isl_set_copy(set));
4160 scop = pet_scop_set_skip(scop, pet_skip_later, set);
4162 return scop;
4165 /* Try and construct a pet_scop corresponding to "stmt".
4167 struct pet_scop *PetScan::extract(Stmt *stmt)
4169 if (isa<Expr>(stmt))
4170 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4172 switch (stmt->getStmtClass()) {
4173 case Stmt::WhileStmtClass:
4174 return extract(cast<WhileStmt>(stmt));
4175 case Stmt::ForStmtClass:
4176 return extract_for(cast<ForStmt>(stmt));
4177 case Stmt::IfStmtClass:
4178 return extract(cast<IfStmt>(stmt));
4179 case Stmt::CompoundStmtClass:
4180 return extract(cast<CompoundStmt>(stmt));
4181 case Stmt::LabelStmtClass:
4182 return extract(cast<LabelStmt>(stmt));
4183 case Stmt::ContinueStmtClass:
4184 return extract(cast<ContinueStmt>(stmt));
4185 case Stmt::BreakStmtClass:
4186 return extract(cast<BreakStmt>(stmt));
4187 default:
4188 unsupported(stmt);
4191 return NULL;
4194 /* Do we need to construct a skip condition of the given type
4195 * on a sequence of statements?
4197 * There is no need to construct a new skip condition if only
4198 * only of the two statements has a skip condition or if both
4199 * of their skip conditions are affine.
4201 * In principle we also don't need a new continuation variable if
4202 * the continuation of scop2 is affine, but then we would need
4203 * to allow more complicated forms of continuations.
4205 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4206 enum pet_skip type)
4208 if (!scop1 || !pet_scop_has_skip(scop1, type))
4209 return false;
4210 if (!scop2 || !pet_scop_has_skip(scop2, type))
4211 return false;
4212 if (pet_scop_has_affine_skip(scop1, type) &&
4213 pet_scop_has_affine_skip(scop2, type))
4214 return false;
4215 return true;
4218 /* Construct a scop for computing the skip condition of the given type and
4219 * with access relation "skip_access" for a sequence of two scops "scop1"
4220 * and "scop2".
4222 * The computed scop contains a single statement that essentially does
4224 * skip_cond = skip_cond_1 ? 1 : skip_cond_2
4226 * or, in other words, skip_cond1 || skip_cond2.
4227 * In this expression, skip_cond_2 is filtered to reflect that it is
4228 * only evaluated when skip_cond_1 is false.
4230 * The skip condition on scop1 is not removed because it still needs
4231 * to be applied to scop2 when these two scops are combined.
4233 static struct pet_scop *extract_skip_seq(PetScan *ps,
4234 __isl_take isl_map *skip_access,
4235 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4237 isl_map *access;
4238 struct pet_expr *expr1, *expr2, *expr, *expr_skip;
4239 struct pet_stmt *stmt;
4240 struct pet_scop *scop;
4241 isl_ctx *ctx = ps->ctx;
4243 if (!scop1 || !scop2)
4244 goto error;
4246 expr1 = pet_scop_get_skip_expr(scop1, type);
4247 expr2 = pet_scop_get_skip_expr(scop2, type);
4248 pet_scop_reset_skip(scop2, type);
4250 expr2 = pet_expr_filter(expr2, isl_map_copy(expr1->acc.access), 0);
4252 expr = universally_true(ctx);
4253 expr = pet_expr_new_ternary(ctx, expr1, expr, expr2);
4254 expr_skip = pet_expr_from_access(isl_map_copy(skip_access));
4255 if (expr_skip) {
4256 expr_skip->acc.write = 1;
4257 expr_skip->acc.read = 0;
4259 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4260 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, ps->n_stmt++, expr);
4262 scop = pet_scop_from_pet_stmt(ctx, stmt);
4263 scop = scop_add_array(scop, skip_access, ps->ast_context);
4264 isl_map_free(skip_access);
4266 return scop;
4267 error:
4268 isl_map_free(skip_access);
4269 return NULL;
4272 /* Structure that handles the construction of skip conditions
4273 * on sequences of statements.
4275 * scop1 and scop2 represent the two statements that are combined
4277 struct pet_skip_info_seq : public pet_skip_info {
4278 struct pet_scop *scop1, *scop2;
4280 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4281 struct pet_scop *scop2);
4282 void extract(PetScan *scan, enum pet_skip type);
4283 void extract(PetScan *scan);
4284 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4285 int offset);
4286 struct pet_scop *add(struct pet_scop *scop, int offset);
4289 /* Initialize a pet_skip_info_seq structure based on
4290 * on the two statements that are going to be combined.
4292 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4293 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
4295 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
4296 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
4297 skip_equals_skip_later(scop2);
4298 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4299 need_skip_seq(scop1, scop2, pet_skip_later);
4302 /* If we need to construct a skip condition of the given type,
4303 * then do so now.
4305 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
4307 if (!skip[type])
4308 return;
4310 access[type] = create_test_access(ctx, scan->n_test++);
4311 scop[type] = extract_skip_seq(scan, isl_map_copy(access[type]),
4312 scop1, scop2, type);
4315 /* Construct the required skip conditions.
4317 void pet_skip_info_seq::extract(PetScan *scan)
4319 extract(scan, pet_skip_now);
4320 extract(scan, pet_skip_later);
4321 if (equal)
4322 drop_skip_later(scop1, scop2);
4325 /* Add the computed skip condition of the give type to "main" and
4326 * add the scop for computing the condition at the given offset (the statement
4327 * number). Within this offset, the condition is computed at position 1
4328 * to ensure that it is computed after the corresponding statement.
4330 * If equal is set, then we only computed a skip condition for pet_skip_now,
4331 * but we also need to set it as main's pet_skip_later.
4333 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
4334 enum pet_skip type, int offset)
4336 isl_set *skip_set;
4338 if (!skip[type])
4339 return main;
4341 skip_set = isl_map_range(access[type]);
4342 access[type] = NULL;
4343 scop[type] = pet_scop_prefix(scop[type], 1);
4344 scop[type] = pet_scop_prefix(scop[type], offset);
4345 main = pet_scop_add_par(ctx, main, scop[type]);
4346 scop[type] = NULL;
4348 if (equal)
4349 main = pet_scop_set_skip(main, pet_skip_later,
4350 isl_set_copy(skip_set));
4352 main = pet_scop_set_skip(main, type, skip_set);
4354 return main;
4357 /* Add the computed skip conditions to "main" and
4358 * add the scops for computing the conditions at the given offset.
4360 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
4362 scop = add(scop, pet_skip_now, offset);
4363 scop = add(scop, pet_skip_later, offset);
4365 return scop;
4368 /* Try and construct a pet_scop corresponding to (part of)
4369 * a sequence of statements.
4371 * If there are any breaks or continues in the individual statements,
4372 * then we may have to compute a new skip condition.
4373 * This is handled using a pet_skip_info_seq object.
4374 * On initialization, the object checks if skip conditions need
4375 * to be computed. If so, it does so in "extract" and adds them in "add".
4377 struct pet_scop *PetScan::extract(StmtRange stmt_range)
4379 pet_scop *scop;
4380 StmtIterator i;
4381 int j;
4382 bool partial_range = false;
4384 scop = pet_scop_empty(ctx);
4385 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4386 Stmt *child = *i;
4387 struct pet_scop *scop_i;
4389 scop_i = extract(child);
4390 if (scop && partial) {
4391 pet_scop_free(scop_i);
4392 break;
4394 pet_skip_info_seq skip(ctx, scop, scop_i);
4395 skip.extract(this);
4396 if (skip)
4397 scop_i = pet_scop_prefix(scop_i, 0);
4398 scop_i = pet_scop_prefix(scop_i, j);
4399 if (options->autodetect) {
4400 if (scop_i)
4401 scop = pet_scop_add_seq(ctx, scop, scop_i);
4402 else
4403 partial_range = true;
4404 if (scop->n_stmt != 0 && !scop_i)
4405 partial = true;
4406 } else {
4407 scop = pet_scop_add_seq(ctx, scop, scop_i);
4410 scop = skip.add(scop, j);
4412 if (partial)
4413 break;
4416 if (scop && partial_range)
4417 partial = true;
4419 return scop;
4422 /* Check if the scop marked by the user is exactly this Stmt
4423 * or part of this Stmt.
4424 * If so, return a pet_scop corresponding to the marked region.
4425 * Otherwise, return NULL.
4427 struct pet_scop *PetScan::scan(Stmt *stmt)
4429 SourceManager &SM = PP.getSourceManager();
4430 unsigned start_off, end_off;
4432 start_off = SM.getFileOffset(stmt->getLocStart());
4433 end_off = SM.getFileOffset(stmt->getLocEnd());
4435 if (start_off > loc.end)
4436 return NULL;
4437 if (end_off < loc.start)
4438 return NULL;
4439 if (start_off >= loc.start && end_off <= loc.end) {
4440 return extract(stmt);
4443 StmtIterator start;
4444 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4445 Stmt *child = *start;
4446 if (!child)
4447 continue;
4448 start_off = SM.getFileOffset(child->getLocStart());
4449 end_off = SM.getFileOffset(child->getLocEnd());
4450 if (start_off < loc.start && end_off > loc.end)
4451 return scan(child);
4452 if (start_off >= loc.start)
4453 break;
4456 StmtIterator end;
4457 for (end = start; end != stmt->child_end(); ++end) {
4458 Stmt *child = *end;
4459 start_off = SM.getFileOffset(child->getLocStart());
4460 if (start_off >= loc.end)
4461 break;
4464 return extract(StmtRange(start, end));
4467 /* Set the size of index "pos" of "array" to "size".
4468 * In particular, add a constraint of the form
4470 * i_pos < size
4472 * to array->extent and a constraint of the form
4474 * size >= 0
4476 * to array->context.
4478 static struct pet_array *update_size(struct pet_array *array, int pos,
4479 __isl_take isl_pw_aff *size)
4481 isl_set *valid;
4482 isl_set *univ;
4483 isl_set *bound;
4484 isl_space *dim;
4485 isl_aff *aff;
4486 isl_pw_aff *index;
4487 isl_id *id;
4489 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
4490 array->context = isl_set_intersect(array->context, valid);
4492 dim = isl_set_get_space(array->extent);
4493 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
4494 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
4495 univ = isl_set_universe(isl_aff_get_domain_space(aff));
4496 index = isl_pw_aff_alloc(univ, aff);
4498 size = isl_pw_aff_add_dims(size, isl_dim_in,
4499 isl_set_dim(array->extent, isl_dim_set));
4500 id = isl_set_get_tuple_id(array->extent);
4501 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
4502 bound = isl_pw_aff_lt_set(index, size);
4504 array->extent = isl_set_intersect(array->extent, bound);
4506 if (!array->context || !array->extent)
4507 goto error;
4509 return array;
4510 error:
4511 pet_array_free(array);
4512 return NULL;
4515 /* Figure out the size of the array at position "pos" and all
4516 * subsequent positions from "type" and update "array" accordingly.
4518 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
4519 const Type *type, int pos)
4521 const ArrayType *atype;
4522 isl_pw_aff *size;
4524 if (!array)
4525 return NULL;
4527 if (type->isPointerType()) {
4528 type = type->getPointeeType().getTypePtr();
4529 return set_upper_bounds(array, type, pos + 1);
4531 if (!type->isArrayType())
4532 return array;
4534 type = type->getCanonicalTypeInternal().getTypePtr();
4535 atype = cast<ArrayType>(type);
4537 if (type->isConstantArrayType()) {
4538 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
4539 size = extract_affine(ca->getSize());
4540 array = update_size(array, pos, size);
4541 } else if (type->isVariableArrayType()) {
4542 const VariableArrayType *vla = cast<VariableArrayType>(atype);
4543 size = extract_affine(vla->getSizeExpr());
4544 array = update_size(array, pos, size);
4547 type = atype->getElementType().getTypePtr();
4549 return set_upper_bounds(array, type, pos + 1);
4552 /* Construct and return a pet_array corresponding to the variable "decl".
4553 * In particular, initialize array->extent to
4555 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4557 * and then call set_upper_bounds to set the upper bounds on the indices
4558 * based on the type of the variable.
4560 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
4562 struct pet_array *array;
4563 QualType qt = decl->getType();
4564 const Type *type = qt.getTypePtr();
4565 int depth = array_depth(type);
4566 QualType base = base_type(qt);
4567 string name;
4568 isl_id *id;
4569 isl_space *dim;
4571 array = isl_calloc_type(ctx, struct pet_array);
4572 if (!array)
4573 return NULL;
4575 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
4576 dim = isl_space_set_alloc(ctx, 0, depth);
4577 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
4579 array->extent = isl_set_nat_universe(dim);
4581 dim = isl_space_params_alloc(ctx, 0);
4582 array->context = isl_set_universe(dim);
4584 array = set_upper_bounds(array, type, 0);
4585 if (!array)
4586 return NULL;
4588 name = base.getAsString();
4589 array->element_type = strdup(name.c_str());
4590 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
4592 return array;
4595 /* Construct a list of pet_arrays, one for each array (or scalar)
4596 * accessed inside "scop", add this list to "scop" and return the result.
4598 * The context of "scop" is updated with the intersection of
4599 * the contexts of all arrays, i.e., constraints on the parameters
4600 * that ensure that the arrays have a valid (non-negative) size.
4602 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
4604 int i;
4605 set<ValueDecl *> arrays;
4606 set<ValueDecl *>::iterator it;
4607 int n_array;
4608 struct pet_array **scop_arrays;
4610 if (!scop)
4611 return NULL;
4613 pet_scop_collect_arrays(scop, arrays);
4614 if (arrays.size() == 0)
4615 return scop;
4617 n_array = scop->n_array;
4619 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
4620 n_array + arrays.size());
4621 if (!scop_arrays)
4622 goto error;
4623 scop->arrays = scop_arrays;
4625 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
4626 struct pet_array *array;
4627 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
4628 if (!scop->arrays[n_array + i])
4629 goto error;
4630 scop->n_array++;
4631 scop->context = isl_set_intersect(scop->context,
4632 isl_set_copy(array->context));
4633 if (!scop->context)
4634 goto error;
4637 return scop;
4638 error:
4639 pet_scop_free(scop);
4640 return NULL;
4643 /* Bound all parameters in scop->context to the possible values
4644 * of the corresponding C variable.
4646 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
4648 int n;
4650 if (!scop)
4651 return NULL;
4653 n = isl_set_dim(scop->context, isl_dim_param);
4654 for (int i = 0; i < n; ++i) {
4655 isl_id *id;
4656 ValueDecl *decl;
4658 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
4659 if (is_nested_parameter(id)) {
4660 isl_id_free(id);
4661 isl_die(isl_set_get_ctx(scop->context),
4662 isl_error_internal,
4663 "unresolved nested parameter", goto error);
4665 decl = (ValueDecl *) isl_id_get_user(id);
4666 isl_id_free(id);
4668 scop->context = set_parameter_bounds(scop->context, i, decl);
4670 if (!scop->context)
4671 goto error;
4674 return scop;
4675 error:
4676 pet_scop_free(scop);
4677 return NULL;
4680 /* Construct a pet_scop from the given function.
4682 struct pet_scop *PetScan::scan(FunctionDecl *fd)
4684 pet_scop *scop;
4685 Stmt *stmt;
4687 stmt = fd->getBody();
4689 if (options->autodetect)
4690 scop = extract(stmt);
4691 else
4692 scop = scan(stmt);
4693 scop = pet_scop_detect_parameter_accesses(scop);
4694 scop = scan_arrays(scop);
4695 scop = add_parameter_bounds(scop);
4696 scop = pet_scop_gist(scop, value_bounds);
4698 return scop;