PetScan::extract_for: relax requirement on increment
[pet.git] / scan.cc
blob8729ecf306cc6a34b37cf154755c45ac87f9484f
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/ASTDiagnostic.h>
39 #include <clang/AST/Expr.h>
40 #include <clang/AST/RecursiveASTVisitor.h>
42 #include <isl/id.h>
43 #include <isl/space.h>
44 #include <isl/aff.h>
45 #include <isl/set.h>
47 #include "scan.h"
48 #include "scop.h"
49 #include "scop_plus.h"
51 #include "config.h"
53 using namespace std;
54 using namespace clang;
56 #ifdef DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION
57 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
59 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
60 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
61 VK_LValue);
63 #else
64 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
66 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
67 var, var->getInnerLocStart(), var->getType(), VK_LValue);
69 #endif
71 /* Check if the element type corresponding to the given array type
72 * has a const qualifier.
74 static bool const_base(QualType qt)
76 const Type *type = qt.getTypePtr();
78 if (type->isPointerType())
79 return const_base(type->getPointeeType());
80 if (type->isArrayType()) {
81 const ArrayType *atype;
82 type = type->getCanonicalTypeInternal().getTypePtr();
83 atype = cast<ArrayType>(type);
84 return const_base(atype->getElementType());
87 return qt.isConstQualified();
90 /* Mark "decl" as having an unknown value in "assigned_value".
92 * If no (known or unknown) value was assigned to "decl" before,
93 * then it may have been treated as a parameter before and may
94 * therefore appear in a value assigned to another variable.
95 * If so, this assignment needs to be turned into an unknown value too.
97 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
98 ValueDecl *decl)
100 map<ValueDecl *, isl_pw_aff *>::iterator it;
102 it = assigned_value.find(decl);
104 assigned_value[decl] = NULL;
106 if (it == assigned_value.end())
107 return;
109 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
110 isl_pw_aff *pa = it->second;
111 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
113 for (int i = 0; i < nparam; ++i) {
114 isl_id *id;
116 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
117 continue;
118 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
119 if (isl_id_get_user(id) == decl)
120 it->second = NULL;
121 isl_id_free(id);
126 /* Look for any assignments to scalar variables in part of the parse
127 * tree and set assigned_value to NULL for each of them.
128 * Also reset assigned_value if the address of a scalar variable
129 * is being taken. As an exception, if the address is passed to a function
130 * that is declared to receive a const pointer, then assigned_value is
131 * not reset.
133 * This ensures that we won't use any previously stored value
134 * in the current subtree and its parents.
136 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
137 map<ValueDecl *, isl_pw_aff *> &assigned_value;
138 set<UnaryOperator *> skip;
140 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
141 assigned_value(assigned_value) {}
143 /* Check for "address of" operators whose value is passed
144 * to a const pointer argument and add them to "skip", so that
145 * we can skip them in VisitUnaryOperator.
147 bool VisitCallExpr(CallExpr *expr) {
148 FunctionDecl *fd;
149 fd = expr->getDirectCallee();
150 if (!fd)
151 return true;
152 for (int i = 0; i < expr->getNumArgs(); ++i) {
153 Expr *arg = expr->getArg(i);
154 UnaryOperator *op;
155 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
156 ImplicitCastExpr *ice;
157 ice = cast<ImplicitCastExpr>(arg);
158 arg = ice->getSubExpr();
160 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
161 continue;
162 op = cast<UnaryOperator>(arg);
163 if (op->getOpcode() != UO_AddrOf)
164 continue;
165 if (const_base(fd->getParamDecl(i)->getType()))
166 skip.insert(op);
168 return true;
171 bool VisitUnaryOperator(UnaryOperator *expr) {
172 Expr *arg;
173 DeclRefExpr *ref;
174 ValueDecl *decl;
176 if (expr->getOpcode() != UO_AddrOf)
177 return true;
178 if (skip.find(expr) != skip.end())
179 return true;
181 arg = expr->getSubExpr();
182 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
183 return true;
184 ref = cast<DeclRefExpr>(arg);
185 decl = ref->getDecl();
186 clear_assignment(assigned_value, decl);
187 return true;
190 bool VisitBinaryOperator(BinaryOperator *expr) {
191 Expr *lhs;
192 DeclRefExpr *ref;
193 ValueDecl *decl;
195 if (!expr->isAssignmentOp())
196 return true;
197 lhs = expr->getLHS();
198 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
199 return true;
200 ref = cast<DeclRefExpr>(lhs);
201 decl = ref->getDecl();
202 clear_assignment(assigned_value, decl);
203 return true;
207 /* Keep a copy of the currently assigned values.
209 * Any variable that is assigned a value inside the current scope
210 * is removed again when we leave the scope (either because it wasn't
211 * stored in the cache or because it has a different value in the cache).
213 struct assigned_value_cache {
214 map<ValueDecl *, isl_pw_aff *> &assigned_value;
215 map<ValueDecl *, isl_pw_aff *> cache;
217 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
218 assigned_value(assigned_value), cache(assigned_value) {}
219 ~assigned_value_cache() {
220 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
221 for (it = assigned_value.begin(); it != assigned_value.end();
222 ++it) {
223 if (!it->second ||
224 (cache.find(it->first) != cache.end() &&
225 cache[it->first] != it->second))
226 cache[it->first] = NULL;
228 assigned_value = cache;
232 /* Insert an expression into the collection of expressions,
233 * provided it is not already in there.
234 * The isl_pw_affs are freed in the destructor.
236 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
238 std::set<isl_pw_aff *>::iterator it;
240 if (expressions.find(expr) == expressions.end())
241 expressions.insert(expr);
242 else
243 isl_pw_aff_free(expr);
246 PetScan::~PetScan()
248 std::set<isl_pw_aff *>::iterator it;
250 for (it = expressions.begin(); it != expressions.end(); ++it)
251 isl_pw_aff_free(*it);
253 isl_union_map_free(value_bounds);
256 /* Called if we found something we (currently) cannot handle.
257 * We'll provide more informative warnings later.
259 * We only actually complain if autodetect is false.
261 void PetScan::unsupported(Stmt *stmt, const char *msg)
263 if (autodetect)
264 return;
266 SourceLocation loc = stmt->getLocStart();
267 DiagnosticsEngine &diag = PP.getDiagnostics();
268 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
269 msg ? msg : "unsupported");
270 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
273 /* Extract an integer from "expr" and store it in "v".
275 int PetScan::extract_int(IntegerLiteral *expr, isl_int *v)
277 const Type *type = expr->getType().getTypePtr();
278 int is_signed = type->hasSignedIntegerRepresentation();
280 if (is_signed) {
281 int64_t i = expr->getValue().getSExtValue();
282 isl_int_set_si(*v, i);
283 } else {
284 uint64_t i = expr->getValue().getZExtValue();
285 isl_int_set_ui(*v, i);
288 return 0;
291 /* Extract an integer from "expr" and store it in "v".
292 * Return -1 if "expr" does not (obviously) represent an integer.
294 int PetScan::extract_int(clang::ParenExpr *expr, isl_int *v)
296 return extract_int(expr->getSubExpr(), v);
299 /* Extract an integer from "expr" and store it in "v".
300 * Return -1 if "expr" does not (obviously) represent an integer.
302 int PetScan::extract_int(clang::Expr *expr, isl_int *v)
304 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
305 return extract_int(cast<IntegerLiteral>(expr), v);
306 if (expr->getStmtClass() == Stmt::ParenExprClass)
307 return extract_int(cast<ParenExpr>(expr), v);
309 unsupported(expr);
310 return -1;
313 /* Extract an affine expression from the IntegerLiteral "expr".
315 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
317 isl_space *dim = isl_space_params_alloc(ctx, 0);
318 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
319 isl_aff *aff = isl_aff_zero_on_domain(ls);
320 isl_set *dom = isl_set_universe(dim);
321 isl_int v;
323 isl_int_init(v);
324 extract_int(expr, &v);
325 aff = isl_aff_add_constant(aff, v);
326 isl_int_clear(v);
328 return isl_pw_aff_alloc(dom, aff);
331 /* Extract an affine expression from the APInt "val".
333 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
335 isl_space *dim = isl_space_params_alloc(ctx, 0);
336 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
337 isl_aff *aff = isl_aff_zero_on_domain(ls);
338 isl_set *dom = isl_set_universe(dim);
339 isl_int v;
341 isl_int_init(v);
342 isl_int_set_ui(v, val.getZExtValue());
343 aff = isl_aff_add_constant(aff, v);
344 isl_int_clear(v);
346 return isl_pw_aff_alloc(dom, aff);
349 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
351 return extract_affine(expr->getSubExpr());
354 static unsigned get_type_size(ValueDecl *decl)
356 return decl->getASTContext().getIntWidth(decl->getType());
359 /* Bound parameter "pos" of "set" to the possible values of "decl".
361 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
362 unsigned pos, ValueDecl *decl)
364 unsigned width;
365 isl_int v;
367 isl_int_init(v);
369 width = get_type_size(decl);
370 if (decl->getType()->isUnsignedIntegerType()) {
371 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
372 isl_int_set_si(v, 1);
373 isl_int_mul_2exp(v, v, width);
374 isl_int_sub_ui(v, v, 1);
375 set = isl_set_upper_bound(set, isl_dim_param, pos, v);
376 } else {
377 isl_int_set_si(v, 1);
378 isl_int_mul_2exp(v, v, width - 1);
379 isl_int_sub_ui(v, v, 1);
380 set = isl_set_upper_bound(set, isl_dim_param, pos, v);
381 isl_int_neg(v, v);
382 isl_int_sub_ui(v, v, 1);
383 set = isl_set_lower_bound(set, isl_dim_param, pos, v);
386 isl_int_clear(v);
388 return set;
391 /* Extract an affine expression from the DeclRefExpr "expr".
393 * If the variable has been assigned a value, then we check whether
394 * we know what (affine) value was assigned.
395 * If so, we return this value. Otherwise we convert "expr"
396 * to an extra parameter (provided nesting_enabled is set).
398 * Otherwise, we simply return an expression that is equal
399 * to a parameter corresponding to the referenced variable.
401 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
403 ValueDecl *decl = expr->getDecl();
404 const Type *type = decl->getType().getTypePtr();
405 isl_id *id;
406 isl_space *dim;
407 isl_aff *aff;
408 isl_set *dom;
410 if (!type->isIntegerType()) {
411 unsupported(expr);
412 return NULL;
415 if (assigned_value.find(decl) != assigned_value.end()) {
416 if (assigned_value[decl])
417 return isl_pw_aff_copy(assigned_value[decl]);
418 else
419 return nested_access(expr);
422 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
423 dim = isl_space_params_alloc(ctx, 1);
425 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
427 dom = isl_set_universe(isl_space_copy(dim));
428 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
429 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
431 return isl_pw_aff_alloc(dom, aff);
434 /* Extract an affine expression from an integer division operation.
435 * In particular, if "expr" is lhs/rhs, then return
437 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
439 * The second argument (rhs) is required to be a (positive) integer constant.
441 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
443 Expr *rhs_expr;
444 isl_pw_aff *lhs, *lhs_f, *lhs_c;
445 isl_pw_aff *res;
446 isl_int v;
447 isl_set *cond;
449 rhs_expr = expr->getRHS();
450 isl_int_init(v);
451 if (extract_int(rhs_expr, &v) < 0) {
452 isl_int_clear(v);
453 return NULL;
456 lhs = extract_affine(expr->getLHS());
457 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
459 lhs = isl_pw_aff_scale_down(lhs, v);
460 isl_int_clear(v);
462 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(lhs));
463 lhs_c = isl_pw_aff_ceil(lhs);
464 res = isl_pw_aff_cond(isl_set_indicator_function(cond), lhs_f, lhs_c);
466 return res;
469 /* Extract an affine expression from a modulo operation.
470 * In particular, if "expr" is lhs/rhs, then return
472 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
474 * The second argument (rhs) is required to be a (positive) integer constant.
476 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
478 Expr *rhs_expr;
479 isl_pw_aff *lhs, *lhs_f, *lhs_c;
480 isl_pw_aff *res;
481 isl_int v;
482 isl_set *cond;
484 rhs_expr = expr->getRHS();
485 if (rhs_expr->getStmtClass() != Stmt::IntegerLiteralClass) {
486 unsupported(expr);
487 return NULL;
490 lhs = extract_affine(expr->getLHS());
491 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
493 isl_int_init(v);
494 extract_int(cast<IntegerLiteral>(rhs_expr), &v);
495 res = isl_pw_aff_scale_down(isl_pw_aff_copy(lhs), v);
497 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(res));
498 lhs_c = isl_pw_aff_ceil(res);
499 res = isl_pw_aff_cond(isl_set_indicator_function(cond), lhs_f, lhs_c);
501 res = isl_pw_aff_scale(res, v);
502 isl_int_clear(v);
504 res = isl_pw_aff_sub(lhs, res);
506 return res;
509 /* Extract an affine expression from a multiplication operation.
510 * This is only allowed if at least one of the two arguments
511 * is a (piecewise) constant.
513 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
515 isl_pw_aff *lhs;
516 isl_pw_aff *rhs;
518 lhs = extract_affine(expr->getLHS());
519 rhs = extract_affine(expr->getRHS());
521 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
522 isl_pw_aff_free(lhs);
523 isl_pw_aff_free(rhs);
524 unsupported(expr);
525 return NULL;
528 return isl_pw_aff_mul(lhs, rhs);
531 /* Extract an affine expression from an addition or subtraction operation.
533 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
535 isl_pw_aff *lhs;
536 isl_pw_aff *rhs;
538 lhs = extract_affine(expr->getLHS());
539 rhs = extract_affine(expr->getRHS());
541 switch (expr->getOpcode()) {
542 case BO_Add:
543 return isl_pw_aff_add(lhs, rhs);
544 case BO_Sub:
545 return isl_pw_aff_sub(lhs, rhs);
546 default:
547 isl_pw_aff_free(lhs);
548 isl_pw_aff_free(rhs);
549 return NULL;
554 /* Compute
556 * pwaff mod 2^width
558 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
559 unsigned width)
561 isl_int mod;
563 isl_int_init(mod);
564 isl_int_set_si(mod, 1);
565 isl_int_mul_2exp(mod, mod, width);
567 pwaff = isl_pw_aff_mod(pwaff, mod);
569 isl_int_clear(mod);
571 return pwaff;
574 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
576 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
577 __isl_take isl_set *dom)
579 isl_pw_aff *pa;
580 pa = isl_set_indicator_function(set);
581 pa = isl_pw_aff_intersect_domain(pa, dom);
582 return pa;
585 /* Extract an affine expression from some binary operations.
586 * If the result of the expression is unsigned, then we wrap it
587 * based on the size of the type.
589 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
591 isl_pw_aff *res;
593 switch (expr->getOpcode()) {
594 case BO_Add:
595 case BO_Sub:
596 res = extract_affine_add(expr);
597 break;
598 case BO_Div:
599 res = extract_affine_div(expr);
600 break;
601 case BO_Rem:
602 res = extract_affine_mod(expr);
603 break;
604 case BO_Mul:
605 res = extract_affine_mul(expr);
606 break;
607 case BO_LT:
608 case BO_LE:
609 case BO_GT:
610 case BO_GE:
611 case BO_EQ:
612 case BO_NE:
613 case BO_LAnd:
614 case BO_LOr:
615 return extract_condition(expr);
616 default:
617 unsupported(expr);
618 return NULL;
621 if (expr->getType()->isUnsignedIntegerType())
622 res = wrap(res, ast_context.getIntWidth(expr->getType()));
624 return res;
627 /* Extract an affine expression from a negation operation.
629 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
631 if (expr->getOpcode() == UO_Minus)
632 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
633 if (expr->getOpcode() == UO_LNot)
634 return extract_condition(expr);
636 unsupported(expr);
637 return NULL;
640 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
642 return extract_affine(expr->getSubExpr());
645 /* Extract an affine expression from some special function calls.
646 * In particular, we handle "min", "max", "ceild" and "floord".
647 * In case of the latter two, the second argument needs to be
648 * a (positive) integer constant.
650 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
652 FunctionDecl *fd;
653 string name;
654 isl_pw_aff *aff1, *aff2;
656 fd = expr->getDirectCallee();
657 if (!fd) {
658 unsupported(expr);
659 return NULL;
662 name = fd->getDeclName().getAsString();
663 if (!(expr->getNumArgs() == 2 && name == "min") &&
664 !(expr->getNumArgs() == 2 && name == "max") &&
665 !(expr->getNumArgs() == 2 && name == "floord") &&
666 !(expr->getNumArgs() == 2 && name == "ceild")) {
667 unsupported(expr);
668 return NULL;
671 if (name == "min" || name == "max") {
672 aff1 = extract_affine(expr->getArg(0));
673 aff2 = extract_affine(expr->getArg(1));
675 if (name == "min")
676 aff1 = isl_pw_aff_min(aff1, aff2);
677 else
678 aff1 = isl_pw_aff_max(aff1, aff2);
679 } else if (name == "floord" || name == "ceild") {
680 isl_int v;
681 Expr *arg2 = expr->getArg(1);
683 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
684 unsupported(expr);
685 return NULL;
687 aff1 = extract_affine(expr->getArg(0));
688 isl_int_init(v);
689 extract_int(cast<IntegerLiteral>(arg2), &v);
690 aff1 = isl_pw_aff_scale_down(aff1, v);
691 isl_int_clear(v);
692 if (name == "floord")
693 aff1 = isl_pw_aff_floor(aff1);
694 else
695 aff1 = isl_pw_aff_ceil(aff1);
696 } else {
697 unsupported(expr);
698 return NULL;
701 return aff1;
705 /* This method is called when we come across an access that is
706 * nested in what is supposed to be an affine expression.
707 * If nesting is allowed, we return a new parameter that corresponds
708 * to this nested access. Otherwise, we simply complain.
710 * The new parameter is resolved in resolve_nested.
712 isl_pw_aff *PetScan::nested_access(Expr *expr)
714 isl_id *id;
715 isl_space *dim;
716 isl_aff *aff;
717 isl_set *dom;
719 if (!nesting_enabled) {
720 unsupported(expr);
721 return NULL;
724 id = isl_id_alloc(ctx, NULL, expr);
725 dim = isl_space_params_alloc(ctx, 1);
727 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
729 dom = isl_set_universe(isl_space_copy(dim));
730 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
731 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
733 return isl_pw_aff_alloc(dom, aff);
736 /* Affine expressions are not supposed to contain array accesses,
737 * but if nesting is allowed, we return a parameter corresponding
738 * to the array access.
740 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
742 return nested_access(expr);
745 /* Extract an affine expression from a conditional operation.
747 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
749 isl_pw_aff *cond, *lhs, *rhs, *res;
751 cond = extract_condition(expr->getCond());
752 lhs = extract_affine(expr->getTrueExpr());
753 rhs = extract_affine(expr->getFalseExpr());
755 return isl_pw_aff_cond(cond, lhs, rhs);
758 /* Extract an affine expression, if possible, from "expr".
759 * Otherwise return NULL.
761 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
763 switch (expr->getStmtClass()) {
764 case Stmt::ImplicitCastExprClass:
765 return extract_affine(cast<ImplicitCastExpr>(expr));
766 case Stmt::IntegerLiteralClass:
767 return extract_affine(cast<IntegerLiteral>(expr));
768 case Stmt::DeclRefExprClass:
769 return extract_affine(cast<DeclRefExpr>(expr));
770 case Stmt::BinaryOperatorClass:
771 return extract_affine(cast<BinaryOperator>(expr));
772 case Stmt::UnaryOperatorClass:
773 return extract_affine(cast<UnaryOperator>(expr));
774 case Stmt::ParenExprClass:
775 return extract_affine(cast<ParenExpr>(expr));
776 case Stmt::CallExprClass:
777 return extract_affine(cast<CallExpr>(expr));
778 case Stmt::ArraySubscriptExprClass:
779 return extract_affine(cast<ArraySubscriptExpr>(expr));
780 case Stmt::ConditionalOperatorClass:
781 return extract_affine(cast<ConditionalOperator>(expr));
782 default:
783 unsupported(expr);
785 return NULL;
788 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
790 return extract_access(expr->getSubExpr());
793 /* Return the depth of an array of the given type.
795 static int array_depth(const Type *type)
797 if (type->isPointerType())
798 return 1 + array_depth(type->getPointeeType().getTypePtr());
799 if (type->isArrayType()) {
800 const ArrayType *atype;
801 type = type->getCanonicalTypeInternal().getTypePtr();
802 atype = cast<ArrayType>(type);
803 return 1 + array_depth(atype->getElementType().getTypePtr());
805 return 0;
808 /* Return the element type of the given array type.
810 static QualType base_type(QualType qt)
812 const Type *type = qt.getTypePtr();
814 if (type->isPointerType())
815 return base_type(type->getPointeeType());
816 if (type->isArrayType()) {
817 const ArrayType *atype;
818 type = type->getCanonicalTypeInternal().getTypePtr();
819 atype = cast<ArrayType>(type);
820 return base_type(atype->getElementType());
822 return qt;
825 /* Extract an access relation from a reference to a variable.
826 * If the variable has name "A" and its type corresponds to an
827 * array of depth d, then the returned access relation is of the
828 * form
830 * { [] -> A[i_1,...,i_d] }
832 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
834 ValueDecl *decl = expr->getDecl();
835 int depth = array_depth(decl->getType().getTypePtr());
836 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
837 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
838 isl_map *access_rel;
840 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
842 access_rel = isl_map_universe(dim);
844 return access_rel;
847 /* Extract an access relation from an integer contant.
848 * If the value of the constant is "v", then the returned access relation
849 * is
851 * { [] -> [v] }
853 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
855 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
858 /* Try and extract an access relation from the given Expr.
859 * Return NULL if it doesn't work out.
861 __isl_give isl_map *PetScan::extract_access(Expr *expr)
863 switch (expr->getStmtClass()) {
864 case Stmt::ImplicitCastExprClass:
865 return extract_access(cast<ImplicitCastExpr>(expr));
866 case Stmt::DeclRefExprClass:
867 return extract_access(cast<DeclRefExpr>(expr));
868 case Stmt::ArraySubscriptExprClass:
869 return extract_access(cast<ArraySubscriptExpr>(expr));
870 default:
871 unsupported(expr);
873 return NULL;
876 /* Assign the affine expression "index" to the output dimension "pos" of "map"
877 * and return the result.
879 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
880 __isl_take isl_pw_aff *index)
882 isl_map *index_map;
883 int len = isl_map_dim(map, isl_dim_out);
884 isl_id *id;
886 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
887 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
888 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
889 id = isl_map_get_tuple_id(map, isl_dim_out);
890 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
892 map = isl_map_intersect(map, index_map);
894 return map;
897 /* Extract an access relation from the given array subscript expression.
898 * If nesting is allowed in general, then we turn it on while
899 * examining the index expression.
901 * We first extract an access relation from the base.
902 * This will result in an access relation with a range that corresponds
903 * to the array being accessed and with earlier indices filled in already.
904 * We then extract the current index and fill that in as well.
905 * The position of the current index is based on the type of base.
906 * If base is the actual array variable, then the depth of this type
907 * will be the same as the depth of the array and we will fill in
908 * the first array index.
909 * Otherwise, the depth of the base type will be smaller and we will fill
910 * in a later index.
912 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
914 Expr *base = expr->getBase();
915 Expr *idx = expr->getIdx();
916 isl_pw_aff *index;
917 isl_map *base_access;
918 isl_map *access;
919 int depth = array_depth(base->getType().getTypePtr());
920 int pos;
921 bool save_nesting = nesting_enabled;
923 nesting_enabled = allow_nested;
925 base_access = extract_access(base);
926 index = extract_affine(idx);
928 nesting_enabled = save_nesting;
930 pos = isl_map_dim(base_access, isl_dim_out) - depth;
931 access = set_index(base_access, pos, index);
933 return access;
936 /* Check if "expr" calls function "minmax" with two arguments and if so
937 * make lhs and rhs refer to these two arguments.
939 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
941 CallExpr *call;
942 FunctionDecl *fd;
943 string name;
945 if (expr->getStmtClass() != Stmt::CallExprClass)
946 return false;
948 call = cast<CallExpr>(expr);
949 fd = call->getDirectCallee();
950 if (!fd)
951 return false;
953 if (call->getNumArgs() != 2)
954 return false;
956 name = fd->getDeclName().getAsString();
957 if (name != minmax)
958 return false;
960 lhs = call->getArg(0);
961 rhs = call->getArg(1);
963 return true;
966 /* Check if "expr" is of the form min(lhs, rhs) and if so make
967 * lhs and rhs refer to the two arguments.
969 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
971 return is_minmax(expr, "min", lhs, rhs);
974 /* Check if "expr" is of the form max(lhs, rhs) and if so make
975 * lhs and rhs refer to the two arguments.
977 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
979 return is_minmax(expr, "max", lhs, rhs);
982 /* Return "lhs && rhs", defined on the shared definition domain.
984 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
985 __isl_take isl_pw_aff *rhs)
987 isl_set *cond;
988 isl_set *dom;
990 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
991 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
992 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
993 isl_pw_aff_non_zero_set(rhs));
994 return indicator_function(cond, dom);
997 /* Return "lhs && rhs", with shortcut semantics.
998 * That is, if lhs is false, then the result is defined even if rhs is not.
999 * In practice, we compute lhs ? rhs : lhs.
1001 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1002 __isl_take isl_pw_aff *rhs)
1004 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1007 /* Return "lhs || rhs", with shortcut semantics.
1008 * That is, if lhs is true, then the result is defined even if rhs is not.
1009 * In practice, we compute lhs ? lhs : rhs.
1011 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1012 __isl_take isl_pw_aff *rhs)
1014 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1017 /* Extract an affine expressions representing the comparison "LHS op RHS"
1018 * "comp" is the original statement that "LHS op RHS" is derived from
1019 * and is used for diagnostics.
1021 * If the comparison is of the form
1023 * a <= min(b,c)
1025 * then the expression is constructed as the conjunction of
1026 * the comparisons
1028 * a <= b and a <= c
1030 * A similar optimization is performed for max(a,b) <= c.
1031 * We do this because that will lead to simpler representations
1032 * of the expression.
1033 * If isl is ever enhanced to explicitly deal with min and max expressions,
1034 * this optimization can be removed.
1036 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1037 Expr *LHS, Expr *RHS, Stmt *comp)
1039 isl_pw_aff *lhs;
1040 isl_pw_aff *rhs;
1041 isl_pw_aff *res;
1042 isl_set *cond;
1043 isl_set *dom;
1045 if (op == BO_GT)
1046 return extract_comparison(BO_LT, RHS, LHS, comp);
1047 if (op == BO_GE)
1048 return extract_comparison(BO_LE, RHS, LHS, comp);
1050 if (op == BO_LT || op == BO_LE) {
1051 Expr *expr1, *expr2;
1052 if (is_min(RHS, expr1, expr2)) {
1053 lhs = extract_comparison(op, LHS, expr1, comp);
1054 rhs = extract_comparison(op, LHS, expr2, comp);
1055 return pw_aff_and(lhs, rhs);
1057 if (is_max(LHS, expr1, expr2)) {
1058 lhs = extract_comparison(op, expr1, RHS, comp);
1059 rhs = extract_comparison(op, expr2, RHS, comp);
1060 return pw_aff_and(lhs, rhs);
1064 lhs = extract_affine(LHS);
1065 rhs = extract_affine(RHS);
1067 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1068 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1070 switch (op) {
1071 case BO_LT:
1072 cond = isl_pw_aff_lt_set(lhs, rhs);
1073 break;
1074 case BO_LE:
1075 cond = isl_pw_aff_le_set(lhs, rhs);
1076 break;
1077 case BO_EQ:
1078 cond = isl_pw_aff_eq_set(lhs, rhs);
1079 break;
1080 case BO_NE:
1081 cond = isl_pw_aff_ne_set(lhs, rhs);
1082 break;
1083 default:
1084 isl_pw_aff_free(lhs);
1085 isl_pw_aff_free(rhs);
1086 isl_set_free(dom);
1087 unsupported(comp);
1088 return NULL;
1091 cond = isl_set_coalesce(cond);
1092 res = indicator_function(cond, dom);
1094 return res;
1097 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1099 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1100 comp->getRHS(), comp);
1103 /* Extract an affine expression representing the negation (logical not)
1104 * of a subexpression.
1106 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1108 isl_set *set_cond, *dom;
1109 isl_pw_aff *cond, *res;
1111 cond = extract_condition(op->getSubExpr());
1113 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1115 set_cond = isl_pw_aff_zero_set(cond);
1117 res = indicator_function(set_cond, dom);
1119 return res;
1122 /* Extract an affine expression representing the disjunction (logical or)
1123 * or conjunction (logical and) of two subexpressions.
1125 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1127 isl_pw_aff *lhs, *rhs;
1129 lhs = extract_condition(comp->getLHS());
1130 rhs = extract_condition(comp->getRHS());
1132 switch (comp->getOpcode()) {
1133 case BO_LAnd:
1134 return pw_aff_and_then(lhs, rhs);
1135 case BO_LOr:
1136 return pw_aff_or_else(lhs, rhs);
1137 default:
1138 isl_pw_aff_free(lhs);
1139 isl_pw_aff_free(rhs);
1142 unsupported(comp);
1143 return NULL;
1146 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1148 switch (expr->getOpcode()) {
1149 case UO_LNot:
1150 return extract_boolean(expr);
1151 default:
1152 unsupported(expr);
1153 return NULL;
1157 /* Extract the affine expression "expr != 0 ? 1 : 0".
1159 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1161 isl_pw_aff *res;
1162 isl_set *set, *dom;
1164 res = extract_affine(expr);
1166 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1167 set = isl_pw_aff_non_zero_set(res);
1169 res = indicator_function(set, dom);
1171 return res;
1174 /* Extract an affine expression from a boolean expression.
1175 * In particular, return the expression "expr ? 1 : 0".
1177 * If the expression doesn't look like a condition, we assume it
1178 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1180 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1182 BinaryOperator *comp;
1184 if (!expr) {
1185 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1186 return indicator_function(u, isl_set_copy(u));
1189 if (expr->getStmtClass() == Stmt::ParenExprClass)
1190 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1192 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1193 return extract_condition(cast<UnaryOperator>(expr));
1195 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1196 return extract_implicit_condition(expr);
1198 comp = cast<BinaryOperator>(expr);
1199 switch (comp->getOpcode()) {
1200 case BO_LT:
1201 case BO_LE:
1202 case BO_GT:
1203 case BO_GE:
1204 case BO_EQ:
1205 case BO_NE:
1206 return extract_comparison(comp);
1207 case BO_LAnd:
1208 case BO_LOr:
1209 return extract_boolean(comp);
1210 default:
1211 return extract_implicit_condition(expr);
1215 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1217 switch (kind) {
1218 case UO_Minus:
1219 return pet_op_minus;
1220 default:
1221 return pet_op_last;
1225 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1227 switch (kind) {
1228 case BO_AddAssign:
1229 return pet_op_add_assign;
1230 case BO_SubAssign:
1231 return pet_op_sub_assign;
1232 case BO_MulAssign:
1233 return pet_op_mul_assign;
1234 case BO_DivAssign:
1235 return pet_op_div_assign;
1236 case BO_Assign:
1237 return pet_op_assign;
1238 case BO_Add:
1239 return pet_op_add;
1240 case BO_Sub:
1241 return pet_op_sub;
1242 case BO_Mul:
1243 return pet_op_mul;
1244 case BO_Div:
1245 return pet_op_div;
1246 case BO_EQ:
1247 return pet_op_eq;
1248 case BO_LE:
1249 return pet_op_le;
1250 case BO_LT:
1251 return pet_op_lt;
1252 case BO_GT:
1253 return pet_op_gt;
1254 default:
1255 return pet_op_last;
1259 /* Construct a pet_expr representing a unary operator expression.
1261 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1263 struct pet_expr *arg;
1264 enum pet_op_type op;
1266 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1267 if (op == pet_op_last) {
1268 unsupported(expr);
1269 return NULL;
1272 arg = extract_expr(expr->getSubExpr());
1274 return pet_expr_new_unary(ctx, op, arg);
1277 /* Mark the given access pet_expr as a write.
1278 * If a scalar is being accessed, then mark its value
1279 * as unknown in assigned_value.
1281 void PetScan::mark_write(struct pet_expr *access)
1283 isl_id *id;
1284 ValueDecl *decl;
1286 access->acc.write = 1;
1287 access->acc.read = 0;
1289 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1290 return;
1292 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1293 decl = (ValueDecl *) isl_id_get_user(id);
1294 clear_assignment(assigned_value, decl);
1295 isl_id_free(id);
1298 /* Construct a pet_expr representing a binary operator expression.
1300 * If the top level operator is an assignment and the LHS is an access,
1301 * then we mark that access as a write. If the operator is a compound
1302 * assignment, the access is marked as both a read and a write.
1304 * If "expr" assigns something to a scalar variable, then we mark
1305 * the variable as having been assigned. If, furthermore, the expression
1306 * is affine, then keep track of this value in assigned_value
1307 * so that we can plug it in when we later come across the same variable.
1309 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1311 struct pet_expr *lhs, *rhs;
1312 enum pet_op_type op;
1314 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1315 if (op == pet_op_last) {
1316 unsupported(expr);
1317 return NULL;
1320 lhs = extract_expr(expr->getLHS());
1321 rhs = extract_expr(expr->getRHS());
1323 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1324 mark_write(lhs);
1325 if (expr->isCompoundAssignmentOp())
1326 lhs->acc.read = 1;
1329 if (expr->getOpcode() == BO_Assign &&
1330 lhs && lhs->type == pet_expr_access &&
1331 isl_map_dim(lhs->acc.access, isl_dim_out) == 0) {
1332 isl_id *id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1333 ValueDecl *decl = (ValueDecl *) isl_id_get_user(id);
1334 Expr *rhs = expr->getRHS();
1335 isl_pw_aff *pa = try_extract_affine(rhs);
1336 clear_assignment(assigned_value, decl);
1337 if (pa) {
1338 assigned_value[decl] = pa;
1339 insert_expression(pa);
1341 isl_id_free(id);
1344 return pet_expr_new_binary(ctx, op, lhs, rhs);
1347 /* Construct a pet_expr representing a conditional operation.
1349 * We first try to extract the condition as an affine expression.
1350 * If that fails, we construct a pet_expr tree representing the condition.
1352 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1354 struct pet_expr *cond, *lhs, *rhs;
1355 isl_pw_aff *pa;
1357 pa = try_extract_affine(expr->getCond());
1358 if (pa) {
1359 isl_set *test = isl_set_from_pw_aff(pa);
1360 cond = pet_expr_from_access(isl_map_from_range(test));
1361 } else
1362 cond = extract_expr(expr->getCond());
1363 lhs = extract_expr(expr->getTrueExpr());
1364 rhs = extract_expr(expr->getFalseExpr());
1366 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1369 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1371 return extract_expr(expr->getSubExpr());
1374 /* Construct a pet_expr representing a floating point value.
1376 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1378 return pet_expr_new_double(ctx, expr->getValueAsApproximateDouble());
1381 /* Extract an access relation from "expr" and then convert it into
1382 * a pet_expr.
1384 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1386 isl_map *access;
1387 struct pet_expr *pe;
1389 switch (expr->getStmtClass()) {
1390 case Stmt::ArraySubscriptExprClass:
1391 access = extract_access(cast<ArraySubscriptExpr>(expr));
1392 break;
1393 case Stmt::DeclRefExprClass:
1394 access = extract_access(cast<DeclRefExpr>(expr));
1395 break;
1396 case Stmt::IntegerLiteralClass:
1397 access = extract_access(cast<IntegerLiteral>(expr));
1398 break;
1399 default:
1400 unsupported(expr);
1401 return NULL;
1404 pe = pet_expr_from_access(access);
1406 return pe;
1409 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1411 return extract_expr(expr->getSubExpr());
1414 /* Construct a pet_expr representing a function call.
1416 * If we are passing along a pointer to an array element
1417 * or an entire row or even higher dimensional slice of an array,
1418 * then the function being called may write into the array.
1420 * We assume here that if the function is declared to take a pointer
1421 * to a const type, then the function will perform a read
1422 * and that otherwise, it will perform a write.
1424 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1426 struct pet_expr *res = NULL;
1427 FunctionDecl *fd;
1428 string name;
1430 fd = expr->getDirectCallee();
1431 if (!fd) {
1432 unsupported(expr);
1433 return NULL;
1436 name = fd->getDeclName().getAsString();
1437 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1438 if (!res)
1439 return NULL;
1441 for (int i = 0; i < expr->getNumArgs(); ++i) {
1442 Expr *arg = expr->getArg(i);
1443 int is_addr = 0;
1444 pet_expr *main_arg;
1446 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1447 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1448 arg = ice->getSubExpr();
1450 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1451 UnaryOperator *op = cast<UnaryOperator>(arg);
1452 if (op->getOpcode() == UO_AddrOf) {
1453 is_addr = 1;
1454 arg = op->getSubExpr();
1457 res->args[i] = PetScan::extract_expr(arg);
1458 main_arg = res->args[i];
1459 if (is_addr)
1460 res->args[i] = pet_expr_new_unary(ctx,
1461 pet_op_address_of, res->args[i]);
1462 if (!res->args[i])
1463 goto error;
1464 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1465 array_depth(arg->getType().getTypePtr()) > 0)
1466 is_addr = 1;
1467 if (is_addr && main_arg->type == pet_expr_access) {
1468 ParmVarDecl *parm;
1469 if (!fd->hasPrototype()) {
1470 unsupported(expr, "prototype required");
1471 goto error;
1473 parm = fd->getParamDecl(i);
1474 if (!const_base(parm->getType()))
1475 mark_write(main_arg);
1479 return res;
1480 error:
1481 pet_expr_free(res);
1482 return NULL;
1485 /* Try and onstruct a pet_expr representing "expr".
1487 struct pet_expr *PetScan::extract_expr(Expr *expr)
1489 switch (expr->getStmtClass()) {
1490 case Stmt::UnaryOperatorClass:
1491 return extract_expr(cast<UnaryOperator>(expr));
1492 case Stmt::CompoundAssignOperatorClass:
1493 case Stmt::BinaryOperatorClass:
1494 return extract_expr(cast<BinaryOperator>(expr));
1495 case Stmt::ImplicitCastExprClass:
1496 return extract_expr(cast<ImplicitCastExpr>(expr));
1497 case Stmt::ArraySubscriptExprClass:
1498 case Stmt::DeclRefExprClass:
1499 case Stmt::IntegerLiteralClass:
1500 return extract_access_expr(expr);
1501 case Stmt::FloatingLiteralClass:
1502 return extract_expr(cast<FloatingLiteral>(expr));
1503 case Stmt::ParenExprClass:
1504 return extract_expr(cast<ParenExpr>(expr));
1505 case Stmt::ConditionalOperatorClass:
1506 return extract_expr(cast<ConditionalOperator>(expr));
1507 case Stmt::CallExprClass:
1508 return extract_expr(cast<CallExpr>(expr));
1509 default:
1510 unsupported(expr);
1512 return NULL;
1515 /* Check if the given initialization statement is an assignment.
1516 * If so, return that assignment. Otherwise return NULL.
1518 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1520 BinaryOperator *ass;
1522 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1523 return NULL;
1525 ass = cast<BinaryOperator>(init);
1526 if (ass->getOpcode() != BO_Assign)
1527 return NULL;
1529 return ass;
1532 /* Check if the given initialization statement is a declaration
1533 * of a single variable.
1534 * If so, return that declaration. Otherwise return NULL.
1536 Decl *PetScan::initialization_declaration(Stmt *init)
1538 DeclStmt *decl;
1540 if (init->getStmtClass() != Stmt::DeclStmtClass)
1541 return NULL;
1543 decl = cast<DeclStmt>(init);
1545 if (!decl->isSingleDecl())
1546 return NULL;
1548 return decl->getSingleDecl();
1551 /* Given the assignment operator in the initialization of a for loop,
1552 * extract the induction variable, i.e., the (integer)variable being
1553 * assigned.
1555 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1557 Expr *lhs;
1558 DeclRefExpr *ref;
1559 ValueDecl *decl;
1560 const Type *type;
1562 lhs = init->getLHS();
1563 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1564 unsupported(init);
1565 return NULL;
1568 ref = cast<DeclRefExpr>(lhs);
1569 decl = ref->getDecl();
1570 type = decl->getType().getTypePtr();
1572 if (!type->isIntegerType()) {
1573 unsupported(lhs);
1574 return NULL;
1577 return decl;
1580 /* Given the initialization statement of a for loop and the single
1581 * declaration in this initialization statement,
1582 * extract the induction variable, i.e., the (integer) variable being
1583 * declared.
1585 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1587 VarDecl *vd;
1589 vd = cast<VarDecl>(decl);
1591 const QualType type = vd->getType();
1592 if (!type->isIntegerType()) {
1593 unsupported(init);
1594 return NULL;
1597 if (!vd->getInit()) {
1598 unsupported(init);
1599 return NULL;
1602 return vd;
1605 /* Check that op is of the form iv++ or iv--.
1606 * Return an affine expression "1" or "-1" accordingly.
1608 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
1609 clang::UnaryOperator *op, clang::ValueDecl *iv)
1611 Expr *sub;
1612 DeclRefExpr *ref;
1613 isl_space *space;
1614 isl_aff *aff;
1616 if (!op->isIncrementDecrementOp()) {
1617 unsupported(op);
1618 return NULL;
1621 sub = op->getSubExpr();
1622 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1623 unsupported(op);
1624 return NULL;
1627 ref = cast<DeclRefExpr>(sub);
1628 if (ref->getDecl() != iv) {
1629 unsupported(op);
1630 return NULL;
1633 space = isl_space_params_alloc(ctx, 0);
1634 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1636 if (op->isIncrementOp())
1637 aff = isl_aff_add_constant_si(aff, 1);
1638 else
1639 aff = isl_aff_add_constant_si(aff, -1);
1641 return isl_pw_aff_from_aff(aff);
1644 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1645 * has a single constant expression, then put this constant in *user.
1646 * The caller is assumed to have checked that this function will
1647 * be called exactly once.
1649 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1650 void *user)
1652 isl_int *inc = (isl_int *)user;
1653 int res = 0;
1655 if (isl_aff_is_cst(aff))
1656 isl_aff_get_constant(aff, inc);
1657 else
1658 res = -1;
1660 isl_set_free(set);
1661 isl_aff_free(aff);
1663 return res;
1666 /* Check if op is of the form
1668 * iv = iv + inc
1670 * and return inc as an affine expression.
1672 * We extract an affine expression from the RHS, subtract iv and return
1673 * the result.
1675 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
1676 clang::ValueDecl *iv)
1678 Expr *lhs;
1679 DeclRefExpr *ref;
1680 isl_id *id;
1681 isl_space *dim;
1682 isl_aff *aff;
1683 isl_pw_aff *val;
1685 if (op->getOpcode() != BO_Assign) {
1686 unsupported(op);
1687 return NULL;
1690 lhs = op->getLHS();
1691 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1692 unsupported(op);
1693 return NULL;
1696 ref = cast<DeclRefExpr>(lhs);
1697 if (ref->getDecl() != iv) {
1698 unsupported(op);
1699 return NULL;
1702 val = extract_affine(op->getRHS());
1704 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1706 dim = isl_space_params_alloc(ctx, 1);
1707 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1708 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1709 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1711 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1713 return val;
1716 /* Check that op is of the form iv += cst or iv -= cst
1717 * and return an affine expression corresponding oto cst or -cst accordingly.
1719 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
1720 CompoundAssignOperator *op, clang::ValueDecl *iv)
1722 Expr *lhs;
1723 DeclRefExpr *ref;
1724 bool neg = false;
1725 isl_pw_aff *val;
1726 BinaryOperatorKind opcode;
1728 opcode = op->getOpcode();
1729 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1730 unsupported(op);
1731 return NULL;
1733 if (opcode == BO_SubAssign)
1734 neg = true;
1736 lhs = op->getLHS();
1737 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1738 unsupported(op);
1739 return NULL;
1742 ref = cast<DeclRefExpr>(lhs);
1743 if (ref->getDecl() != iv) {
1744 unsupported(op);
1745 return NULL;
1748 val = extract_affine(op->getRHS());
1749 if (neg)
1750 val = isl_pw_aff_neg(val);
1752 return val;
1755 /* Check that the increment of the given for loop increments
1756 * (or decrements) the induction variable "iv" and return
1757 * the increment as an affine expression if successful.
1759 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
1760 ValueDecl *iv)
1762 Stmt *inc = stmt->getInc();
1764 if (!inc) {
1765 unsupported(stmt);
1766 return NULL;
1769 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1770 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1771 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1772 return extract_compound_increment(
1773 cast<CompoundAssignOperator>(inc), iv);
1774 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1775 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1777 unsupported(inc);
1778 return NULL;
1781 /* Embed the given iteration domain in an extra outer loop
1782 * with induction variable "var".
1783 * If this variable appeared as a parameter in the constraints,
1784 * it is replaced by the new outermost dimension.
1786 static __isl_give isl_set *embed(__isl_take isl_set *set,
1787 __isl_take isl_id *var)
1789 int pos;
1791 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1792 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1793 if (pos >= 0) {
1794 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1795 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1798 isl_id_free(var);
1799 return set;
1802 /* Construct a pet_scop for an infinite loop around the given body.
1804 * We extract a pet_scop for the body and then embed it in a loop with
1805 * iteration domain
1807 * { [t] : t >= 0 }
1809 * and schedule
1811 * { [t] -> [t] }
1813 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1815 isl_id *id;
1816 isl_space *dim;
1817 isl_set *domain;
1818 isl_map *sched;
1819 struct pet_scop *scop;
1821 scop = extract(body);
1822 if (!scop)
1823 return NULL;
1825 id = isl_id_alloc(ctx, "t", NULL);
1826 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1827 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
1828 dim = isl_space_from_domain(isl_set_get_space(domain));
1829 dim = isl_space_add_dims(dim, isl_dim_out, 1);
1830 sched = isl_map_universe(dim);
1831 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
1832 scop = pet_scop_embed(scop, domain, sched, id);
1834 return scop;
1837 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1839 * for (;;)
1840 * body
1843 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1845 return extract_infinite_loop(stmt->getBody());
1848 /* Check if the while loop is of the form
1850 * while (1)
1851 * body
1853 * If so, construct a scop for an infinite loop around body.
1854 * Otherwise, fail.
1856 struct pet_scop *PetScan::extract(WhileStmt *stmt)
1858 Expr *cond;
1859 isl_set *set;
1860 int is_universe;
1862 cond = stmt->getCond();
1863 if (!cond) {
1864 unsupported(stmt);
1865 return NULL;
1868 set = isl_pw_aff_non_zero_set(extract_condition(cond));
1869 is_universe = isl_set_plain_is_universe(set);
1870 isl_set_free(set);
1872 if (!is_universe) {
1873 unsupported(stmt);
1874 return NULL;
1877 return extract_infinite_loop(stmt->getBody());
1880 /* Check whether "cond" expresses a simple loop bound
1881 * on the only set dimension.
1882 * In particular, if "up" is set then "cond" should contain only
1883 * upper bounds on the set dimension.
1884 * Otherwise, it should contain only lower bounds.
1886 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
1888 if (isl_int_is_pos(inc))
1889 return !isl_set_dim_has_lower_bound(cond, isl_dim_set, 0);
1890 else
1891 return !isl_set_dim_has_upper_bound(cond, isl_dim_set, 0);
1894 /* Extend a condition on a given iteration of a loop to one that
1895 * imposes the same condition on all previous iterations.
1896 * "domain" expresses the lower [upper] bound on the iterations
1897 * when inc is positive [negative].
1899 * In particular, we construct the condition (when inc is positive)
1901 * forall i' : (domain(i') and i' <= i) => cond(i')
1903 * which is equivalent to
1905 * not exists i' : domain(i') and i' <= i and not cond(i')
1907 * We construct this set by negating cond, applying a map
1909 * { [i'] -> [i] : domain(i') and i' <= i }
1911 * and then negating the result again.
1913 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
1914 __isl_take isl_set *domain, isl_int inc)
1916 isl_map *previous_to_this;
1918 if (isl_int_is_pos(inc))
1919 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
1920 else
1921 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
1923 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
1925 cond = isl_set_complement(cond);
1926 cond = isl_set_apply(cond, previous_to_this);
1927 cond = isl_set_complement(cond);
1929 return cond;
1932 /* Construct a domain of the form
1934 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
1936 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
1937 __isl_take isl_pw_aff *init, isl_int inc)
1939 isl_aff *aff;
1940 isl_space *dim;
1941 isl_set *set;
1943 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
1944 dim = isl_pw_aff_get_domain_space(init);
1945 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1946 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
1947 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
1949 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
1950 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1951 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1952 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1954 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
1956 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
1958 return isl_set_params(set);
1961 /* Assuming "cond" represents a bound on a loop where the loop
1962 * iterator "iv" is incremented (or decremented) by one, check if wrapping
1963 * is possible.
1965 * Under the given assumptions, wrapping is only possible if "cond" allows
1966 * for the last value before wrapping, i.e., 2^width - 1 in case of an
1967 * increasing iterator and 0 in case of a decreasing iterator.
1969 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
1971 bool cw;
1972 isl_int limit;
1973 isl_set *test;
1975 test = isl_set_copy(cond);
1977 isl_int_init(limit);
1978 if (isl_int_is_neg(inc))
1979 isl_int_set_si(limit, 0);
1980 else {
1981 isl_int_set_si(limit, 1);
1982 isl_int_mul_2exp(limit, limit, get_type_size(iv));
1983 isl_int_sub_ui(limit, limit, 1);
1986 test = isl_set_fix(cond, isl_dim_set, 0, limit);
1987 cw = !isl_set_is_empty(test);
1988 isl_set_free(test);
1990 isl_int_clear(limit);
1992 return cw;
1995 /* Given a one-dimensional space, construct the following mapping on this
1996 * space
1998 * { [v] -> [v mod 2^width] }
2000 * where width is the number of bits used to represent the values
2001 * of the unsigned variable "iv".
2003 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
2004 ValueDecl *iv)
2006 isl_int mod;
2007 isl_aff *aff;
2008 isl_map *map;
2010 isl_int_init(mod);
2011 isl_int_set_si(mod, 1);
2012 isl_int_mul_2exp(mod, mod, get_type_size(iv));
2014 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2015 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2016 aff = isl_aff_mod(aff, mod);
2018 isl_int_clear(mod);
2020 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2021 map = isl_map_reverse(map);
2024 /* Project out the parameter "id" from "set".
2026 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2027 __isl_keep isl_id *id)
2029 int pos;
2031 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2032 if (pos >= 0)
2033 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2035 return set;
2038 /* Compute the set of parameters for which "set1" is a subset of "set2".
2040 * set1 is a subset of set2 if
2042 * forall i in set1 : i in set2
2044 * or
2046 * not exists i in set1 and i not in set2
2048 * i.e.,
2050 * not exists i in set1 \ set2
2052 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2053 __isl_take isl_set *set2)
2055 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2058 /* Compute the set of parameter values for which "cond" holds
2059 * on the next iteration for each element of "dom".
2061 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2062 * and then compute the set of parameters for which the result is a subset
2063 * of "cond".
2065 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2066 __isl_take isl_set *dom, isl_int inc)
2068 isl_space *space;
2069 isl_aff *aff;
2070 isl_map *next;
2072 space = isl_set_get_space(dom);
2073 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2074 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2075 aff = isl_aff_add_constant(aff, inc);
2076 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2078 dom = isl_set_apply(dom, next);
2080 return enforce_subset(dom, cond);
2083 /* Construct a pet_scop for a for statement.
2084 * The for loop is required to be of the form
2086 * for (i = init; condition; ++i)
2088 * or
2090 * for (i = init; condition; --i)
2092 * The initialization of the for loop should either be an assignment
2093 * to an integer variable, or a declaration of such a variable with
2094 * initialization.
2096 * The condition is allowed to contain nested accesses, provided
2097 * they are not being written to inside the body of the loop.
2099 * We extract a pet_scop for the body and then embed it in a loop with
2100 * iteration domain and schedule
2102 * { [i] : i >= init and condition' }
2103 * { [i] -> [i] }
2105 * or
2107 * { [i] : i <= init and condition' }
2108 * { [i] -> [-i] }
2110 * Where condition' is equal to condition if the latter is
2111 * a simple upper [lower] bound and a condition that is extended
2112 * to apply to all previous iterations otherwise.
2114 * If the stride of the loop is not 1, then "i >= init" is replaced by
2116 * (exists a: i = init + stride * a and a >= 0)
2118 * If the loop iterator i is unsigned, then wrapping may occur.
2119 * During the computation, we work with a virtual iterator that
2120 * does not wrap. However, the condition in the code applies
2121 * to the wrapped value, so we need to change condition(i)
2122 * into condition([i % 2^width]).
2123 * After computing the virtual domain and schedule, we apply
2124 * the function { [v] -> [v % 2^width] } to the domain and the domain
2125 * of the schedule. In order not to lose any information, we also
2126 * need to intersect the domain of the schedule with the virtual domain
2127 * first, since some iterations in the wrapped domain may be scheduled
2128 * several times, typically an infinite number of times.
2129 * Note that there is no need to perform this final wrapping
2130 * if the loop condition (after wrapping) is simple.
2132 * Wrapping on unsigned iterators can be avoided entirely if
2133 * loop condition is simple, the loop iterator is incremented
2134 * [decremented] by one and the last value before wrapping cannot
2135 * possibly satisfy the loop condition.
2137 * Before extracting a pet_scop from the body we remove all
2138 * assignments in assigned_value to variables that are assigned
2139 * somewhere in the body of the loop.
2141 * Valid parameters for a for loop are those for which the initial
2142 * value itself, the increment on each domain iteration and
2143 * the condition on both the initial value and
2144 * the result of incrementing the iterator for each iteration of the domain
2145 * can be evaluated.
2147 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2149 BinaryOperator *ass;
2150 Decl *decl;
2151 Stmt *init;
2152 Expr *lhs, *rhs;
2153 ValueDecl *iv;
2154 isl_space *dim;
2155 isl_set *domain;
2156 isl_map *sched;
2157 isl_set *cond = NULL;
2158 isl_id *id;
2159 struct pet_scop *scop;
2160 assigned_value_cache cache(assigned_value);
2161 isl_int inc;
2162 bool is_one;
2163 bool is_unsigned;
2164 bool is_simple;
2165 bool is_virtual;
2166 isl_map *wrap = NULL;
2167 isl_pw_aff *pa, *pa_inc, *init_val;
2168 isl_set *valid_init;
2169 isl_set *valid_cond;
2170 isl_set *valid_cond_init;
2171 isl_set *valid_cond_next;
2172 isl_set *valid_inc;
2174 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2175 return extract_infinite_for(stmt);
2177 init = stmt->getInit();
2178 if (!init) {
2179 unsupported(stmt);
2180 return NULL;
2182 if ((ass = initialization_assignment(init)) != NULL) {
2183 iv = extract_induction_variable(ass);
2184 if (!iv)
2185 return NULL;
2186 lhs = ass->getLHS();
2187 rhs = ass->getRHS();
2188 } else if ((decl = initialization_declaration(init)) != NULL) {
2189 VarDecl *var = extract_induction_variable(init, decl);
2190 if (!var)
2191 return NULL;
2192 iv = var;
2193 rhs = var->getInit();
2194 lhs = create_DeclRefExpr(var);
2195 } else {
2196 unsupported(stmt->getInit());
2197 return NULL;
2200 pa_inc = extract_increment(stmt, iv);
2201 if (!pa_inc)
2202 return NULL;
2204 isl_int_init(inc);
2205 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
2206 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
2207 isl_pw_aff_free(pa_inc);
2208 unsupported(stmt->getInc());
2209 isl_int_clear(inc);
2210 return NULL;
2212 valid_inc = isl_pw_aff_domain(pa_inc);
2214 is_unsigned = iv->getType()->isUnsignedIntegerType();
2216 assigned_value.erase(iv);
2217 clear_assignments clear(assigned_value);
2218 clear.TraverseStmt(stmt->getBody());
2220 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2222 scop = extract(stmt->getBody());
2224 pa = try_extract_nested_condition(stmt->getCond());
2225 if (pa && !is_nested_allowed(pa, scop)) {
2226 isl_pw_aff_free(pa);
2227 pa = NULL;
2230 if (!pa)
2231 pa = extract_condition(stmt->getCond());
2232 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2233 cond = isl_pw_aff_non_zero_set(pa);
2234 cond = embed(cond, isl_id_copy(id));
2235 valid_cond = isl_set_coalesce(valid_cond);
2236 valid_cond = embed(valid_cond, isl_id_copy(id));
2237 valid_inc = embed(valid_inc, isl_id_copy(id));
2238 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
2239 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2241 init_val = extract_affine(rhs);
2242 valid_cond_init = enforce_subset(
2243 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
2244 isl_set_copy(valid_cond));
2245 if (is_one && !is_virtual) {
2246 isl_pw_aff_free(init_val);
2247 pa = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
2248 lhs, rhs, init);
2249 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2250 valid_init = set_project_out_by_id(valid_init, id);
2251 domain = isl_pw_aff_non_zero_set(pa);
2252 } else {
2253 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2254 domain = strided_domain(isl_id_copy(id), init_val, inc);
2257 domain = embed(domain, isl_id_copy(id));
2258 if (is_virtual) {
2259 isl_map *rev_wrap;
2260 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2261 rev_wrap = isl_map_reverse(isl_map_copy(wrap));
2262 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2263 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2264 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2266 cond = isl_set_gist(cond, isl_set_copy(domain));
2267 is_simple = is_simple_bound(cond, inc);
2268 if (!is_simple)
2269 cond = valid_for_each_iteration(cond,
2270 isl_set_copy(domain), inc);
2271 domain = isl_set_intersect(domain, cond);
2272 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2273 dim = isl_space_from_domain(isl_set_get_space(domain));
2274 dim = isl_space_add_dims(dim, isl_dim_out, 1);
2275 sched = isl_map_universe(dim);
2276 if (isl_int_is_pos(inc))
2277 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2278 else
2279 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2281 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain), inc);
2282 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2284 if (is_virtual && !is_simple) {
2285 wrap = isl_map_set_dim_id(wrap,
2286 isl_dim_out, 0, isl_id_copy(id));
2287 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2288 domain = isl_set_apply(domain, isl_map_copy(wrap));
2289 sched = isl_map_apply_domain(sched, wrap);
2290 } else
2291 isl_map_free(wrap);
2293 scop = pet_scop_embed(scop, domain, sched, id);
2294 scop = resolve_nested(scop);
2295 clear_assignment(assigned_value, iv);
2297 isl_int_clear(inc);
2299 scop = pet_scop_restrict_context(scop, valid_init);
2300 scop = pet_scop_restrict_context(scop, valid_inc);
2301 scop = pet_scop_restrict_context(scop, valid_cond_next);
2302 scop = pet_scop_restrict_context(scop, valid_cond_init);
2304 return scop;
2307 struct pet_scop *PetScan::extract(CompoundStmt *stmt)
2309 return extract(stmt->children());
2312 /* Does "id" refer to a nested access?
2314 static bool is_nested_parameter(__isl_keep isl_id *id)
2316 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2319 /* Does parameter "pos" of "space" refer to a nested access?
2321 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2323 bool nested;
2324 isl_id *id;
2326 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2327 nested = is_nested_parameter(id);
2328 isl_id_free(id);
2330 return nested;
2333 /* Does parameter "pos" of "map" refer to a nested access?
2335 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2337 bool nested;
2338 isl_id *id;
2340 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2341 nested = is_nested_parameter(id);
2342 isl_id_free(id);
2344 return nested;
2347 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2349 static int n_nested_parameter(__isl_keep isl_space *space)
2351 int n = 0;
2352 int nparam;
2354 nparam = isl_space_dim(space, isl_dim_param);
2355 for (int i = 0; i < nparam; ++i)
2356 if (is_nested_parameter(space, i))
2357 ++n;
2359 return n;
2362 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2364 static int n_nested_parameter(__isl_keep isl_map *map)
2366 isl_space *space;
2367 int n;
2369 space = isl_map_get_space(map);
2370 n = n_nested_parameter(space);
2371 isl_space_free(space);
2373 return n;
2376 /* For each nested access parameter in "space",
2377 * construct a corresponding pet_expr, place it in args and
2378 * record its position in "param2pos".
2379 * "n_arg" is the number of elements that are already in args.
2380 * The position recorded in "param2pos" takes this number into account.
2381 * If the pet_expr corresponding to a parameter is identical to
2382 * the pet_expr corresponding to an earlier parameter, then these two
2383 * parameters are made to refer to the same element in args.
2385 * Return the final number of elements in args or -1 if an error has occurred.
2387 int PetScan::extract_nested(__isl_keep isl_space *space,
2388 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
2390 int nparam;
2392 nparam = isl_space_dim(space, isl_dim_param);
2393 for (int i = 0; i < nparam; ++i) {
2394 int j;
2395 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2396 Expr *nested;
2398 if (!is_nested_parameter(id)) {
2399 isl_id_free(id);
2400 continue;
2403 nested = (Expr *) isl_id_get_user(id);
2404 args[n_arg] = extract_expr(nested);
2405 if (!args[n_arg])
2406 return -1;
2408 for (j = 0; j < n_arg; ++j)
2409 if (pet_expr_is_equal(args[j], args[n_arg]))
2410 break;
2412 if (j < n_arg) {
2413 pet_expr_free(args[n_arg]);
2414 args[n_arg] = NULL;
2415 param2pos[i] = j;
2416 } else
2417 param2pos[i] = n_arg++;
2419 isl_id_free(id);
2422 return n_arg;
2425 /* For each nested access parameter in the access relations in "expr",
2426 * construct a corresponding pet_expr, place it in expr->args and
2427 * record its position in "param2pos".
2428 * n is the number of nested access parameters.
2430 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
2431 std::map<int,int> &param2pos)
2433 isl_space *space;
2435 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
2436 expr->n_arg = n;
2437 if (!expr->args)
2438 goto error;
2440 space = isl_map_get_space(expr->acc.access);
2441 n = extract_nested(space, 0, expr->args, param2pos);
2442 isl_space_free(space);
2444 if (n < 0)
2445 goto error;
2447 expr->n_arg = n;
2448 return expr;
2449 error:
2450 pet_expr_free(expr);
2451 return NULL;
2454 /* Look for parameters in any access relation in "expr" that
2455 * refer to nested accesses. In particular, these are
2456 * parameters with no name.
2458 * If there are any such parameters, then the domain of the access
2459 * relation, which is still [] at this point, is replaced by
2460 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2461 * (after identifying identical nested accesses).
2462 * The parameters are then equated to the corresponding t dimensions
2463 * and subsequently projected out.
2464 * param2pos maps the position of the parameter to the position
2465 * of the corresponding t dimension.
2467 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
2469 int n;
2470 int nparam;
2471 int n_in;
2472 isl_space *dim;
2473 isl_map *map;
2474 std::map<int,int> param2pos;
2476 if (!expr)
2477 return expr;
2479 for (int i = 0; i < expr->n_arg; ++i) {
2480 expr->args[i] = resolve_nested(expr->args[i]);
2481 if (!expr->args[i]) {
2482 pet_expr_free(expr);
2483 return NULL;
2487 if (expr->type != pet_expr_access)
2488 return expr;
2490 n = n_nested_parameter(expr->acc.access);
2491 if (n == 0)
2492 return expr;
2494 expr = extract_nested(expr, n, param2pos);
2495 if (!expr)
2496 return NULL;
2498 n = expr->n_arg;
2499 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
2500 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
2501 dim = isl_map_get_space(expr->acc.access);
2502 dim = isl_space_domain(dim);
2503 dim = isl_space_from_domain(dim);
2504 dim = isl_space_add_dims(dim, isl_dim_out, n);
2505 map = isl_map_universe(dim);
2506 map = isl_map_domain_map(map);
2507 map = isl_map_reverse(map);
2508 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
2510 for (int i = nparam - 1; i >= 0; --i) {
2511 isl_id *id = isl_map_get_dim_id(expr->acc.access,
2512 isl_dim_param, i);
2513 if (!is_nested_parameter(id)) {
2514 isl_id_free(id);
2515 continue;
2518 expr->acc.access = isl_map_equate(expr->acc.access,
2519 isl_dim_param, i, isl_dim_in,
2520 n_in + param2pos[i]);
2521 expr->acc.access = isl_map_project_out(expr->acc.access,
2522 isl_dim_param, i, 1);
2524 isl_id_free(id);
2527 return expr;
2528 error:
2529 pet_expr_free(expr);
2530 return NULL;
2533 /* Convert a top-level pet_expr to a pet_scop with one statement.
2534 * This mainly involves resolving nested expression parameters
2535 * and setting the name of the iteration space.
2536 * The name is given by "label" if it is non-NULL. Otherwise,
2537 * it is of the form S_<n_stmt>.
2539 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
2540 __isl_take isl_id *label)
2542 struct pet_stmt *ps;
2543 SourceLocation loc = stmt->getLocStart();
2544 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2546 expr = resolve_nested(expr);
2547 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
2548 return pet_scop_from_pet_stmt(ctx, ps);
2551 /* Check if we can extract an affine expression from "expr".
2552 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2553 * We turn on autodetection so that we won't generate any warnings
2554 * and turn off nesting, so that we won't accept any non-affine constructs.
2556 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
2558 isl_pw_aff *pwaff;
2559 int save_autodetect = autodetect;
2560 bool save_nesting = nesting_enabled;
2562 autodetect = 1;
2563 nesting_enabled = false;
2565 pwaff = extract_affine(expr);
2567 autodetect = save_autodetect;
2568 nesting_enabled = save_nesting;
2570 return pwaff;
2573 /* Check whether "expr" is an affine expression.
2575 bool PetScan::is_affine(Expr *expr)
2577 isl_pw_aff *pwaff;
2579 pwaff = try_extract_affine(expr);
2580 isl_pw_aff_free(pwaff);
2582 return pwaff != NULL;
2585 /* Check whether "expr" is an affine constraint.
2586 * We turn on autodetection so that we won't generate any warnings
2587 * and turn off nesting, so that we won't accept any non-affine constructs.
2589 bool PetScan::is_affine_condition(Expr *expr)
2591 isl_pw_aff *cond;
2592 int save_autodetect = autodetect;
2593 bool save_nesting = nesting_enabled;
2595 autodetect = 1;
2596 nesting_enabled = false;
2598 cond = extract_condition(expr);
2599 isl_pw_aff_free(cond);
2601 autodetect = save_autodetect;
2602 nesting_enabled = save_nesting;
2604 return cond != NULL;
2607 /* Check if we can extract a condition from "expr".
2608 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
2609 * If allow_nested is set, then the condition may involve parameters
2610 * corresponding to nested accesses.
2611 * We turn on autodetection so that we won't generate any warnings.
2613 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
2615 isl_pw_aff *cond;
2616 int save_autodetect = autodetect;
2617 bool save_nesting = nesting_enabled;
2619 autodetect = 1;
2620 nesting_enabled = allow_nested;
2621 cond = extract_condition(expr);
2623 autodetect = save_autodetect;
2624 nesting_enabled = save_nesting;
2626 return cond;
2629 /* If the top-level expression of "stmt" is an assignment, then
2630 * return that assignment as a BinaryOperator.
2631 * Otherwise return NULL.
2633 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
2635 BinaryOperator *ass;
2637 if (!stmt)
2638 return NULL;
2639 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
2640 return NULL;
2642 ass = cast<BinaryOperator>(stmt);
2643 if(ass->getOpcode() != BO_Assign)
2644 return NULL;
2646 return ass;
2649 /* Check if the given if statement is a conditional assignement
2650 * with a non-affine condition. If so, construct a pet_scop
2651 * corresponding to this conditional assignment. Otherwise return NULL.
2653 * In particular we check if "stmt" is of the form
2655 * if (condition)
2656 * a = f(...);
2657 * else
2658 * a = g(...);
2660 * where a is some array or scalar access.
2661 * The constructed pet_scop then corresponds to the expression
2663 * a = condition ? f(...) : g(...)
2665 * All access relations in f(...) are intersected with condition
2666 * while all access relation in g(...) are intersected with the complement.
2668 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
2670 BinaryOperator *ass_then, *ass_else;
2671 isl_map *write_then, *write_else;
2672 isl_set *cond, *comp;
2673 isl_map *map;
2674 isl_pw_aff *pa;
2675 int equal;
2676 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
2677 bool save_nesting = nesting_enabled;
2679 ass_then = top_assignment_or_null(stmt->getThen());
2680 ass_else = top_assignment_or_null(stmt->getElse());
2682 if (!ass_then || !ass_else)
2683 return NULL;
2685 if (is_affine_condition(stmt->getCond()))
2686 return NULL;
2688 write_then = extract_access(ass_then->getLHS());
2689 write_else = extract_access(ass_else->getLHS());
2691 equal = isl_map_is_equal(write_then, write_else);
2692 isl_map_free(write_else);
2693 if (equal < 0 || !equal) {
2694 isl_map_free(write_then);
2695 return NULL;
2698 nesting_enabled = allow_nested;
2699 pa = extract_condition(stmt->getCond());
2700 nesting_enabled = save_nesting;
2701 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
2702 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
2703 map = isl_map_from_range(isl_set_from_pw_aff(pa));
2705 pe_cond = pet_expr_from_access(map);
2707 pe_then = extract_expr(ass_then->getRHS());
2708 pe_then = pet_expr_restrict(pe_then, cond);
2709 pe_else = extract_expr(ass_else->getRHS());
2710 pe_else = pet_expr_restrict(pe_else, comp);
2712 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
2713 pe_write = pet_expr_from_access(write_then);
2714 if (pe_write) {
2715 pe_write->acc.write = 1;
2716 pe_write->acc.read = 0;
2718 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
2719 return extract(stmt, pe);
2722 /* Create an access to a virtual array representing the result
2723 * of a condition.
2724 * Unlike other accessed data, the id of the array is NULL as
2725 * there is no ValueDecl in the program corresponding to the virtual
2726 * array.
2727 * The array starts out as a scalar, but grows along with the
2728 * statement writing to the array in pet_scop_embed.
2730 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2732 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2733 isl_id *id;
2734 char name[50];
2736 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2737 id = isl_id_alloc(ctx, name, NULL);
2738 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2739 return isl_map_universe(dim);
2742 /* Create a pet_scop with a single statement evaluating "cond"
2743 * and writing the result to a virtual scalar, as expressed by
2744 * "access".
2746 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
2747 __isl_take isl_map *access)
2749 struct pet_expr *expr, *write;
2750 struct pet_stmt *ps;
2751 SourceLocation loc = cond->getLocStart();
2752 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2754 write = pet_expr_from_access(access);
2755 if (write) {
2756 write->acc.write = 1;
2757 write->acc.read = 0;
2759 expr = extract_expr(cond);
2760 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
2761 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
2762 return pet_scop_from_pet_stmt(ctx, ps);
2765 /* Add an array with the given extent ("access") to the list
2766 * of arrays in "scop" and return the extended pet_scop.
2767 * The array is marked as attaining values 0 and 1 only.
2769 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2770 __isl_keep isl_map *access, clang::ASTContext &ast_ctx)
2772 isl_ctx *ctx = isl_map_get_ctx(access);
2773 isl_space *dim;
2774 struct pet_array **arrays;
2775 struct pet_array *array;
2777 if (!scop)
2778 return NULL;
2779 if (!ctx)
2780 goto error;
2782 arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2783 scop->n_array + 1);
2784 if (!arrays)
2785 goto error;
2786 scop->arrays = arrays;
2788 array = isl_calloc_type(ctx, struct pet_array);
2789 if (!array)
2790 goto error;
2792 array->extent = isl_map_range(isl_map_copy(access));
2793 dim = isl_space_params_alloc(ctx, 0);
2794 array->context = isl_set_universe(dim);
2795 dim = isl_space_set_alloc(ctx, 0, 1);
2796 array->value_bounds = isl_set_universe(dim);
2797 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2798 isl_dim_set, 0, 0);
2799 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2800 isl_dim_set, 0, 1);
2801 array->element_type = strdup("int");
2802 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2804 scop->arrays[scop->n_array] = array;
2805 scop->n_array++;
2807 if (!array->extent || !array->context)
2808 goto error;
2810 return scop;
2811 error:
2812 pet_scop_free(scop);
2813 return NULL;
2816 extern "C" {
2817 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
2818 void *user);
2821 /* Apply the map pointed to by "user" to the domain of the access
2822 * relation, thereby embedding it in the range of the map.
2823 * The domain of both relations is the zero-dimensional domain.
2825 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
2827 isl_map *map = (isl_map *) user;
2829 return isl_map_apply_domain(access, isl_map_copy(map));
2832 /* Apply "map" to all access relations in "expr".
2834 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
2836 return pet_expr_foreach_access(expr, &embed_access, map);
2839 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2841 static int n_nested_parameter(__isl_keep isl_set *set)
2843 isl_space *space;
2844 int n;
2846 space = isl_set_get_space(set);
2847 n = n_nested_parameter(space);
2848 isl_space_free(space);
2850 return n;
2853 /* Remove all parameters from "map" that refer to nested accesses.
2855 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
2857 int nparam;
2858 isl_space *space;
2860 space = isl_map_get_space(map);
2861 nparam = isl_space_dim(space, isl_dim_param);
2862 for (int i = nparam - 1; i >= 0; --i)
2863 if (is_nested_parameter(space, i))
2864 map = isl_map_project_out(map, isl_dim_param, i, 1);
2865 isl_space_free(space);
2867 return map;
2870 extern "C" {
2871 static __isl_give isl_map *access_remove_nested_parameters(
2872 __isl_take isl_map *access, void *user);
2875 static __isl_give isl_map *access_remove_nested_parameters(
2876 __isl_take isl_map *access, void *user)
2878 return remove_nested_parameters(access);
2881 /* Remove all nested access parameters from the schedule and all
2882 * accesses of "stmt".
2883 * There is no need to remove them from the domain as these parameters
2884 * have already been removed from the domain when this function is called.
2886 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
2888 if (!stmt)
2889 return NULL;
2890 stmt->schedule = remove_nested_parameters(stmt->schedule);
2891 stmt->body = pet_expr_foreach_access(stmt->body,
2892 &access_remove_nested_parameters, NULL);
2893 if (!stmt->schedule || !stmt->body)
2894 goto error;
2895 for (int i = 0; i < stmt->n_arg; ++i) {
2896 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
2897 &access_remove_nested_parameters, NULL);
2898 if (!stmt->args[i])
2899 goto error;
2902 return stmt;
2903 error:
2904 pet_stmt_free(stmt);
2905 return NULL;
2908 /* For each nested access parameter in the domain of "stmt",
2909 * construct a corresponding pet_expr, place it in stmt->args and
2910 * record its position in "param2pos".
2911 * n is the number of nested access parameters.
2913 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
2914 std::map<int,int> &param2pos)
2916 isl_space *space;
2917 unsigned n_arg;
2918 struct pet_expr **args;
2920 n_arg = stmt->n_arg;
2921 args = isl_realloc_array(ctx, stmt->args, struct pet_expr *, n_arg + n);
2922 if (!args)
2923 goto error;
2924 stmt->args = args;
2925 stmt->n_arg += n;
2927 space = isl_set_get_space(stmt->domain);
2928 n = extract_nested(space, n_arg, stmt->args, param2pos);
2929 isl_space_free(space);
2931 if (n < 0)
2932 goto error;
2934 stmt->n_arg = n;
2935 return stmt;
2936 error:
2937 pet_stmt_free(stmt);
2938 return NULL;
2941 /* Look for parameters in the iteration domain of "stmt" that
2942 * refer to nested accesses. In particular, these are
2943 * parameters with no name.
2945 * If there are any such parameters, then as many extra variables
2946 * (after identifying identical nested accesses) are added to the
2947 * range of the map wrapped inside the domain.
2948 * If the original domain is not a wrapped map, then a new wrapped
2949 * map is created with zero output dimensions.
2950 * The parameters are then equated to the corresponding output dimensions
2951 * and subsequently projected out, from the iteration domain,
2952 * the schedule and the access relations.
2953 * For each of the output dimensions, a corresponding argument
2954 * expression is added. Initially they are created with
2955 * a zero-dimensional domain, so they have to be embedded
2956 * in the current iteration domain.
2957 * param2pos maps the position of the parameter to the position
2958 * of the corresponding output dimension in the wrapped map.
2960 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
2962 int n;
2963 int nparam;
2964 unsigned n_arg;
2965 isl_map *map;
2966 std::map<int,int> param2pos;
2968 if (!stmt)
2969 return NULL;
2971 n = n_nested_parameter(stmt->domain);
2972 if (n == 0)
2973 return stmt;
2975 n_arg = stmt->n_arg;
2976 stmt = extract_nested(stmt, n, param2pos);
2977 if (!stmt)
2978 return NULL;
2980 n = stmt->n_arg - n_arg;
2981 nparam = isl_set_dim(stmt->domain, isl_dim_param);
2982 if (isl_set_is_wrapping(stmt->domain))
2983 map = isl_set_unwrap(stmt->domain);
2984 else
2985 map = isl_map_from_domain(stmt->domain);
2986 map = isl_map_add_dims(map, isl_dim_out, n);
2988 for (int i = nparam - 1; i >= 0; --i) {
2989 isl_id *id;
2991 if (!is_nested_parameter(map, i))
2992 continue;
2994 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
2995 isl_dim_out);
2996 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
2997 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
2998 param2pos[i]);
2999 map = isl_map_project_out(map, isl_dim_param, i, 1);
3002 stmt->domain = isl_map_wrap(map);
3004 map = isl_set_unwrap(isl_set_copy(stmt->domain));
3005 map = isl_map_from_range(isl_map_domain(map));
3006 for (int pos = n_arg; pos < stmt->n_arg; ++pos)
3007 stmt->args[pos] = embed(stmt->args[pos], map);
3008 isl_map_free(map);
3010 stmt = remove_nested_parameters(stmt);
3012 return stmt;
3013 error:
3014 pet_stmt_free(stmt);
3015 return NULL;
3018 /* For each statement in "scop", move the parameters that correspond
3019 * to nested access into the ranges of the domains and create
3020 * corresponding argument expressions.
3022 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3024 if (!scop)
3025 return NULL;
3027 for (int i = 0; i < scop->n_stmt; ++i) {
3028 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3029 if (!scop->stmts[i])
3030 goto error;
3033 return scop;
3034 error:
3035 pet_scop_free(scop);
3036 return NULL;
3039 /* Does "space" involve any parameters that refer to nested
3040 * accesses, i.e., parameters with no name?
3042 static bool has_nested(__isl_keep isl_space *space)
3044 int nparam;
3046 nparam = isl_space_dim(space, isl_dim_param);
3047 for (int i = 0; i < nparam; ++i)
3048 if (is_nested_parameter(space, i))
3049 return true;
3051 return false;
3054 /* Does "pa" involve any parameters that refer to nested
3055 * accesses, i.e., parameters with no name?
3057 static bool has_nested(__isl_keep isl_pw_aff *pa)
3059 isl_space *space;
3060 bool nested;
3062 space = isl_pw_aff_get_space(pa);
3063 nested = has_nested(space);
3064 isl_space_free(space);
3066 return nested;
3069 /* Given an access expression "expr", is the variable accessed by
3070 * "expr" assigned anywhere inside "scop"?
3072 static bool is_assigned(pet_expr *expr, pet_scop *scop)
3074 bool assigned = false;
3075 isl_id *id;
3077 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
3078 assigned = pet_scop_writes(scop, id);
3079 isl_id_free(id);
3081 return assigned;
3084 /* Are all nested access parameters in "pa" allowed given "scop".
3085 * In particular, is none of them written by anywhere inside "scop".
3087 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3089 int nparam;
3091 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3092 for (int i = 0; i < nparam; ++i) {
3093 Expr *nested;
3094 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3095 pet_expr *expr;
3096 bool allowed;
3098 if (!is_nested_parameter(id)) {
3099 isl_id_free(id);
3100 continue;
3103 nested = (Expr *) isl_id_get_user(id);
3104 expr = extract_expr(nested);
3105 allowed = expr && expr->type == pet_expr_access &&
3106 !is_assigned(expr, scop);
3108 pet_expr_free(expr);
3109 isl_id_free(id);
3111 if (!allowed)
3112 return false;
3115 return true;
3118 /* Construct a pet_scop for an if statement.
3120 * If the condition fits the pattern of a conditional assignment,
3121 * then it is handled by extract_conditional_assignment.
3122 * Otherwise, we do the following.
3124 * If the condition is affine, then the condition is added
3125 * to the iteration domains of the then branch, while the
3126 * opposite of the condition in added to the iteration domains
3127 * of the else branch, if any.
3128 * We allow the condition to be dynamic, i.e., to refer to
3129 * scalars or array elements that may be written to outside
3130 * of the given if statement. These nested accesses are then represented
3131 * as output dimensions in the wrapping iteration domain.
3132 * If it also written _inside_ the then or else branch, then
3133 * we treat the condition as non-affine.
3134 * As explained below, this will introduce an extra statement.
3135 * For aesthetic reasons, we want this statement to have a statement
3136 * number that is lower than those of the then and else branches.
3137 * In order to evaluate if will need such a statement, however, we
3138 * first construct scops for the then and else branches.
3139 * We therefore reserve a statement number if we might have to
3140 * introduce such an extra statement.
3142 * If the condition is not affine, then we create a separate
3143 * statement that writes the result of the condition to a virtual scalar.
3144 * A constraint requiring the value of this virtual scalar to be one
3145 * is added to the iteration domains of the then branch.
3146 * Similarly, a constraint requiring the value of this virtual scalar
3147 * to be zero is added to the iteration domains of the else branch, if any.
3148 * We adjust the schedules to ensure that the virtual scalar is written
3149 * before it is read.
3151 struct pet_scop *PetScan::extract(IfStmt *stmt)
3153 struct pet_scop *scop_then, *scop_else, *scop;
3154 assigned_value_cache cache(assigned_value);
3155 isl_map *test_access = NULL;
3156 isl_pw_aff *cond;
3157 int stmt_id;
3159 scop = extract_conditional_assignment(stmt);
3160 if (scop)
3161 return scop;
3163 cond = try_extract_nested_condition(stmt->getCond());
3164 if (allow_nested && (!cond || has_nested(cond)))
3165 stmt_id = n_stmt++;
3167 scop_then = extract(stmt->getThen());
3169 if (stmt->getElse()) {
3170 scop_else = extract(stmt->getElse());
3171 if (autodetect) {
3172 if (scop_then && !scop_else) {
3173 partial = true;
3174 isl_pw_aff_free(cond);
3175 return scop_then;
3177 if (!scop_then && scop_else) {
3178 partial = true;
3179 isl_pw_aff_free(cond);
3180 return scop_else;
3185 if (cond &&
3186 (!is_nested_allowed(cond, scop_then) ||
3187 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
3188 isl_pw_aff_free(cond);
3189 cond = NULL;
3191 if (allow_nested && !cond) {
3192 int save_n_stmt = n_stmt;
3193 test_access = create_test_access(ctx, n_test++);
3194 n_stmt = stmt_id;
3195 scop = extract_non_affine_condition(stmt->getCond(),
3196 isl_map_copy(test_access));
3197 n_stmt = save_n_stmt;
3198 scop = scop_add_array(scop, test_access, ast_context);
3199 if (!scop) {
3200 pet_scop_free(scop_then);
3201 pet_scop_free(scop_else);
3202 isl_map_free(test_access);
3203 return NULL;
3207 if (!scop) {
3208 isl_set *set;
3209 isl_set *valid;
3211 if (!cond)
3212 cond = extract_condition(stmt->getCond());
3213 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
3214 set = isl_pw_aff_non_zero_set(cond);
3215 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
3217 if (stmt->getElse()) {
3218 set = isl_set_subtract(isl_set_copy(valid), set);
3219 scop_else = pet_scop_restrict(scop_else, set);
3220 scop = pet_scop_add(ctx, scop, scop_else);
3221 } else
3222 isl_set_free(set);
3223 scop = resolve_nested(scop);
3224 scop = pet_scop_restrict_context(scop, valid);
3225 } else {
3226 scop = pet_scop_prefix(scop, 0);
3227 scop_then = pet_scop_prefix(scop_then, 1);
3228 scop_then = pet_scop_filter(scop_then,
3229 isl_map_copy(test_access), 1);
3230 scop = pet_scop_add(ctx, scop, scop_then);
3231 if (stmt->getElse()) {
3232 scop_else = pet_scop_prefix(scop_else, 1);
3233 scop_else = pet_scop_filter(scop_else, test_access, 0);
3234 scop = pet_scop_add(ctx, scop, scop_else);
3235 } else
3236 isl_map_free(test_access);
3239 return scop;
3242 /* Try and construct a pet_scop for a label statement.
3243 * We currently only allow labels on expression statements.
3245 struct pet_scop *PetScan::extract(LabelStmt *stmt)
3247 isl_id *label;
3248 Stmt *sub;
3250 sub = stmt->getSubStmt();
3251 if (!isa<Expr>(sub)) {
3252 unsupported(stmt);
3253 return NULL;
3256 label = isl_id_alloc(ctx, stmt->getName(), NULL);
3258 return extract(sub, extract_expr(cast<Expr>(sub)), label);
3261 /* Try and construct a pet_scop corresponding to "stmt".
3263 struct pet_scop *PetScan::extract(Stmt *stmt)
3265 if (isa<Expr>(stmt))
3266 return extract(stmt, extract_expr(cast<Expr>(stmt)));
3268 switch (stmt->getStmtClass()) {
3269 case Stmt::WhileStmtClass:
3270 return extract(cast<WhileStmt>(stmt));
3271 case Stmt::ForStmtClass:
3272 return extract_for(cast<ForStmt>(stmt));
3273 case Stmt::IfStmtClass:
3274 return extract(cast<IfStmt>(stmt));
3275 case Stmt::CompoundStmtClass:
3276 return extract(cast<CompoundStmt>(stmt));
3277 case Stmt::LabelStmtClass:
3278 return extract(cast<LabelStmt>(stmt));
3279 default:
3280 unsupported(stmt);
3283 return NULL;
3286 /* Try and construct a pet_scop corresponding to (part of)
3287 * a sequence of statements.
3289 struct pet_scop *PetScan::extract(StmtRange stmt_range)
3291 pet_scop *scop;
3292 StmtIterator i;
3293 int j;
3294 bool partial_range = false;
3296 scop = pet_scop_empty(ctx);
3297 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
3298 Stmt *child = *i;
3299 struct pet_scop *scop_i;
3300 scop_i = extract(child);
3301 if (scop && partial) {
3302 pet_scop_free(scop_i);
3303 break;
3305 scop_i = pet_scop_prefix(scop_i, j);
3306 if (autodetect) {
3307 if (scop_i)
3308 scop = pet_scop_add(ctx, scop, scop_i);
3309 else
3310 partial_range = true;
3311 if (scop->n_stmt != 0 && !scop_i)
3312 partial = true;
3313 } else {
3314 scop = pet_scop_add(ctx, scop, scop_i);
3316 if (partial)
3317 break;
3320 if (scop && partial_range)
3321 partial = true;
3323 return scop;
3326 /* Check if the scop marked by the user is exactly this Stmt
3327 * or part of this Stmt.
3328 * If so, return a pet_scop corresponding to the marked region.
3329 * Otherwise, return NULL.
3331 struct pet_scop *PetScan::scan(Stmt *stmt)
3333 SourceManager &SM = PP.getSourceManager();
3334 unsigned start_off, end_off;
3336 start_off = SM.getFileOffset(stmt->getLocStart());
3337 end_off = SM.getFileOffset(stmt->getLocEnd());
3339 if (start_off > loc.end)
3340 return NULL;
3341 if (end_off < loc.start)
3342 return NULL;
3343 if (start_off >= loc.start && end_off <= loc.end) {
3344 return extract(stmt);
3347 StmtIterator start;
3348 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
3349 Stmt *child = *start;
3350 if (!child)
3351 continue;
3352 start_off = SM.getFileOffset(child->getLocStart());
3353 end_off = SM.getFileOffset(child->getLocEnd());
3354 if (start_off < loc.start && end_off > loc.end)
3355 return scan(child);
3356 if (start_off >= loc.start)
3357 break;
3360 StmtIterator end;
3361 for (end = start; end != stmt->child_end(); ++end) {
3362 Stmt *child = *end;
3363 start_off = SM.getFileOffset(child->getLocStart());
3364 if (start_off >= loc.end)
3365 break;
3368 return extract(StmtRange(start, end));
3371 /* Set the size of index "pos" of "array" to "size".
3372 * In particular, add a constraint of the form
3374 * i_pos < size
3376 * to array->extent and a constraint of the form
3378 * size >= 0
3380 * to array->context.
3382 static struct pet_array *update_size(struct pet_array *array, int pos,
3383 __isl_take isl_pw_aff *size)
3385 isl_set *valid;
3386 isl_set *univ;
3387 isl_set *bound;
3388 isl_space *dim;
3389 isl_aff *aff;
3390 isl_pw_aff *index;
3391 isl_id *id;
3393 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
3394 array->context = isl_set_intersect(array->context, valid);
3396 dim = isl_set_get_space(array->extent);
3397 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
3398 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
3399 univ = isl_set_universe(isl_aff_get_domain_space(aff));
3400 index = isl_pw_aff_alloc(univ, aff);
3402 size = isl_pw_aff_add_dims(size, isl_dim_in,
3403 isl_set_dim(array->extent, isl_dim_set));
3404 id = isl_set_get_tuple_id(array->extent);
3405 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
3406 bound = isl_pw_aff_lt_set(index, size);
3408 array->extent = isl_set_intersect(array->extent, bound);
3410 if (!array->context || !array->extent)
3411 goto error;
3413 return array;
3414 error:
3415 pet_array_free(array);
3416 return NULL;
3419 /* Figure out the size of the array at position "pos" and all
3420 * subsequent positions from "type" and update "array" accordingly.
3422 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
3423 const Type *type, int pos)
3425 const ArrayType *atype;
3426 isl_pw_aff *size;
3428 if (!array)
3429 return NULL;
3431 if (type->isPointerType()) {
3432 type = type->getPointeeType().getTypePtr();
3433 return set_upper_bounds(array, type, pos + 1);
3435 if (!type->isArrayType())
3436 return array;
3438 type = type->getCanonicalTypeInternal().getTypePtr();
3439 atype = cast<ArrayType>(type);
3441 if (type->isConstantArrayType()) {
3442 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
3443 size = extract_affine(ca->getSize());
3444 array = update_size(array, pos, size);
3445 } else if (type->isVariableArrayType()) {
3446 const VariableArrayType *vla = cast<VariableArrayType>(atype);
3447 size = extract_affine(vla->getSizeExpr());
3448 array = update_size(array, pos, size);
3451 type = atype->getElementType().getTypePtr();
3453 return set_upper_bounds(array, type, pos + 1);
3456 /* Construct and return a pet_array corresponding to the variable "decl".
3457 * In particular, initialize array->extent to
3459 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3461 * and then call set_upper_bounds to set the upper bounds on the indices
3462 * based on the type of the variable.
3464 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
3466 struct pet_array *array;
3467 QualType qt = decl->getType();
3468 const Type *type = qt.getTypePtr();
3469 int depth = array_depth(type);
3470 QualType base = base_type(qt);
3471 string name;
3472 isl_id *id;
3473 isl_space *dim;
3475 array = isl_calloc_type(ctx, struct pet_array);
3476 if (!array)
3477 return NULL;
3479 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
3480 dim = isl_space_set_alloc(ctx, 0, depth);
3481 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
3483 array->extent = isl_set_nat_universe(dim);
3485 dim = isl_space_params_alloc(ctx, 0);
3486 array->context = isl_set_universe(dim);
3488 array = set_upper_bounds(array, type, 0);
3489 if (!array)
3490 return NULL;
3492 name = base.getAsString();
3493 array->element_type = strdup(name.c_str());
3494 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
3496 return array;
3499 /* Construct a list of pet_arrays, one for each array (or scalar)
3500 * accessed inside "scop" add this list to "scop" and return the result.
3502 * The context of "scop" is updated with the intesection of
3503 * the contexts of all arrays, i.e., constraints on the parameters
3504 * that ensure that the arrays have a valid (non-negative) size.
3506 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
3508 int i;
3509 set<ValueDecl *> arrays;
3510 set<ValueDecl *>::iterator it;
3511 int n_array;
3512 struct pet_array **scop_arrays;
3514 if (!scop)
3515 return NULL;
3517 pet_scop_collect_arrays(scop, arrays);
3518 if (arrays.size() == 0)
3519 return scop;
3521 n_array = scop->n_array;
3523 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3524 n_array + arrays.size());
3525 if (!scop_arrays)
3526 goto error;
3527 scop->arrays = scop_arrays;
3529 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3530 struct pet_array *array;
3531 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
3532 if (!scop->arrays[n_array + i])
3533 goto error;
3534 scop->n_array++;
3535 scop->context = isl_set_intersect(scop->context,
3536 isl_set_copy(array->context));
3537 if (!scop->context)
3538 goto error;
3541 return scop;
3542 error:
3543 pet_scop_free(scop);
3544 return NULL;
3547 /* Bound all parameters in scop->context to the possible values
3548 * of the corresponding C variable.
3550 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
3552 int n;
3554 if (!scop)
3555 return NULL;
3557 n = isl_set_dim(scop->context, isl_dim_param);
3558 for (int i = 0; i < n; ++i) {
3559 isl_id *id;
3560 ValueDecl *decl;
3562 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
3563 decl = (ValueDecl *) isl_id_get_user(id);
3564 isl_id_free(id);
3566 scop->context = set_parameter_bounds(scop->context, i, decl);
3568 if (!scop->context)
3569 goto error;
3572 return scop;
3573 error:
3574 pet_scop_free(scop);
3575 return NULL;
3578 /* Construct a pet_scop from the given function.
3580 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3582 pet_scop *scop;
3583 Stmt *stmt;
3585 stmt = fd->getBody();
3587 if (autodetect)
3588 scop = extract(stmt);
3589 else
3590 scop = scan(stmt);
3591 scop = pet_scop_detect_parameter_accesses(scop);
3592 scop = scan_arrays(scop);
3593 scop = add_parameter_bounds(scop);
3594 scop = pet_scop_gist(scop, value_bounds);
3596 return scop;