PetScan::extract_implicit_affine: simplify computation
[pet.git] / scan.cc
blob34ed94945b50996c32d69f3bafa7437b8c3a1986
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following
13 * disclaimer in the documentation and/or other materials provided
14 * with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
20 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 * The views and conclusions contained in the software and documentation
29 * are those of the authors and should not be interpreted as
30 * representing official policies, either expressed or implied, of
31 * Leiden University.
32 */
34 #include <set>
35 #include <map>
36 #include <iostream>
37 #include <clang/AST/ASTDiagnostic.h>
38 #include <clang/AST/Expr.h>
39 #include <clang/AST/RecursiveASTVisitor.h>
41 #include <isl/id.h>
42 #include <isl/space.h>
43 #include <isl/aff.h>
44 #include <isl/set.h>
46 #include "scan.h"
47 #include "scop.h"
48 #include "scop_plus.h"
50 #include "config.h"
52 using namespace std;
53 using namespace clang;
55 #ifdef DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION
56 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
58 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
59 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
60 VK_LValue);
62 #else
63 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
65 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
66 var, var->getInnerLocStart(), var->getType(), VK_LValue);
68 #endif
70 /* Check if the element type corresponding to the given array type
71 * has a const qualifier.
73 static bool const_base(QualType qt)
75 const Type *type = qt.getTypePtr();
77 if (type->isPointerType())
78 return const_base(type->getPointeeType());
79 if (type->isArrayType()) {
80 const ArrayType *atype;
81 type = type->getCanonicalTypeInternal().getTypePtr();
82 atype = cast<ArrayType>(type);
83 return const_base(atype->getElementType());
86 return qt.isConstQualified();
89 /* Mark "decl" as having an unknown value in "assigned_value".
91 * If no (known or unknown) value was assigned to "decl" before,
92 * then it may have been treated as a parameter before and may
93 * therefore appear in a value assigned to another variable.
94 * If so, this assignment needs to be turned into an unknown value too.
96 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
97 ValueDecl *decl)
99 map<ValueDecl *, isl_pw_aff *>::iterator it;
101 it = assigned_value.find(decl);
103 assigned_value[decl] = NULL;
105 if (it == assigned_value.end())
106 return;
108 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
109 isl_pw_aff *pa = it->second;
110 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
112 for (int i = 0; i < nparam; ++i) {
113 isl_id *id;
115 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
116 continue;
117 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
118 if (isl_id_get_user(id) == decl)
119 it->second = NULL;
120 isl_id_free(id);
125 /* Look for any assignments to scalar variables in part of the parse
126 * tree and set assigned_value to NULL for each of them.
127 * Also reset assigned_value if the address of a scalar variable
128 * is being taken. As an exception, if the address is passed to a function
129 * that is declared to receive a const pointer, then assigned_value is
130 * not reset.
132 * This ensures that we won't use any previously stored value
133 * in the current subtree and its parents.
135 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
136 map<ValueDecl *, isl_pw_aff *> &assigned_value;
137 set<UnaryOperator *> skip;
139 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
140 assigned_value(assigned_value) {}
142 /* Check for "address of" operators whose value is passed
143 * to a const pointer argument and add them to "skip", so that
144 * we can skip them in VisitUnaryOperator.
146 bool VisitCallExpr(CallExpr *expr) {
147 FunctionDecl *fd;
148 fd = expr->getDirectCallee();
149 if (!fd)
150 return true;
151 for (int i = 0; i < expr->getNumArgs(); ++i) {
152 Expr *arg = expr->getArg(i);
153 UnaryOperator *op;
154 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
155 ImplicitCastExpr *ice;
156 ice = cast<ImplicitCastExpr>(arg);
157 arg = ice->getSubExpr();
159 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
160 continue;
161 op = cast<UnaryOperator>(arg);
162 if (op->getOpcode() != UO_AddrOf)
163 continue;
164 if (const_base(fd->getParamDecl(i)->getType()))
165 skip.insert(op);
167 return true;
170 bool VisitUnaryOperator(UnaryOperator *expr) {
171 Expr *arg;
172 DeclRefExpr *ref;
173 ValueDecl *decl;
175 if (expr->getOpcode() != UO_AddrOf)
176 return true;
177 if (skip.find(expr) != skip.end())
178 return true;
180 arg = expr->getSubExpr();
181 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
182 return true;
183 ref = cast<DeclRefExpr>(arg);
184 decl = ref->getDecl();
185 clear_assignment(assigned_value, decl);
186 return true;
189 bool VisitBinaryOperator(BinaryOperator *expr) {
190 Expr *lhs;
191 DeclRefExpr *ref;
192 ValueDecl *decl;
194 if (!expr->isAssignmentOp())
195 return true;
196 lhs = expr->getLHS();
197 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
198 return true;
199 ref = cast<DeclRefExpr>(lhs);
200 decl = ref->getDecl();
201 clear_assignment(assigned_value, decl);
202 return true;
206 /* Keep a copy of the currently assigned values.
208 * Any variable that is assigned a value inside the current scope
209 * is removed again when we leave the scope (either because it wasn't
210 * stored in the cache or because it has a different value in the cache).
212 struct assigned_value_cache {
213 map<ValueDecl *, isl_pw_aff *> &assigned_value;
214 map<ValueDecl *, isl_pw_aff *> cache;
216 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
217 assigned_value(assigned_value), cache(assigned_value) {}
218 ~assigned_value_cache() {
219 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
220 for (it = assigned_value.begin(); it != assigned_value.end();
221 ++it) {
222 if (!it->second ||
223 (cache.find(it->first) != cache.end() &&
224 cache[it->first] != it->second))
225 cache[it->first] = NULL;
227 assigned_value = cache;
231 /* Insert an expression into the collection of expressions,
232 * provided it is not already in there.
233 * The isl_pw_affs are freed in the destructor.
235 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
237 std::set<isl_pw_aff *>::iterator it;
239 if (expressions.find(expr) == expressions.end())
240 expressions.insert(expr);
241 else
242 isl_pw_aff_free(expr);
245 PetScan::~PetScan()
247 std::set<isl_pw_aff *>::iterator it;
249 for (it = expressions.begin(); it != expressions.end(); ++it)
250 isl_pw_aff_free(*it);
252 isl_union_map_free(value_bounds);
255 /* Called if we found something we (currently) cannot handle.
256 * We'll provide more informative warnings later.
258 * We only actually complain if autodetect is false.
260 void PetScan::unsupported(Stmt *stmt, const char *msg)
262 if (autodetect)
263 return;
265 SourceLocation loc = stmt->getLocStart();
266 DiagnosticsEngine &diag = PP.getDiagnostics();
267 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
268 msg ? msg : "unsupported");
269 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
272 /* Extract an integer from "expr" and store it in "v".
274 int PetScan::extract_int(IntegerLiteral *expr, isl_int *v)
276 const Type *type = expr->getType().getTypePtr();
277 int is_signed = type->hasSignedIntegerRepresentation();
279 if (is_signed) {
280 int64_t i = expr->getValue().getSExtValue();
281 isl_int_set_si(*v, i);
282 } else {
283 uint64_t i = expr->getValue().getZExtValue();
284 isl_int_set_ui(*v, i);
287 return 0;
290 /* Extract an integer from "expr" and store it in "v".
291 * Return -1 if "expr" does not (obviously) represent an integer.
293 int PetScan::extract_int(clang::ParenExpr *expr, isl_int *v)
295 return extract_int(expr->getSubExpr(), v);
298 /* Extract an integer from "expr" and store it in "v".
299 * Return -1 if "expr" does not (obviously) represent an integer.
301 int PetScan::extract_int(clang::Expr *expr, isl_int *v)
303 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
304 return extract_int(cast<IntegerLiteral>(expr), v);
305 if (expr->getStmtClass() == Stmt::ParenExprClass)
306 return extract_int(cast<ParenExpr>(expr), v);
308 unsupported(expr);
309 return -1;
312 /* Extract an affine expression from the IntegerLiteral "expr".
314 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
316 isl_space *dim = isl_space_params_alloc(ctx, 0);
317 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
318 isl_aff *aff = isl_aff_zero_on_domain(ls);
319 isl_set *dom = isl_set_universe(dim);
320 isl_int v;
322 isl_int_init(v);
323 extract_int(expr, &v);
324 aff = isl_aff_add_constant(aff, v);
325 isl_int_clear(v);
327 return isl_pw_aff_alloc(dom, aff);
330 /* Extract an affine expression from the APInt "val".
332 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
334 isl_space *dim = isl_space_params_alloc(ctx, 0);
335 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
336 isl_aff *aff = isl_aff_zero_on_domain(ls);
337 isl_set *dom = isl_set_universe(dim);
338 isl_int v;
340 isl_int_init(v);
341 isl_int_set_ui(v, val.getZExtValue());
342 aff = isl_aff_add_constant(aff, v);
343 isl_int_clear(v);
345 return isl_pw_aff_alloc(dom, aff);
348 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
350 return extract_affine(expr->getSubExpr());
353 /* Extract an affine expression from the DeclRefExpr "expr".
355 * If the variable has been assigned a value, then we check whether
356 * we know what (affine) value was assigned.
357 * If so, we return this value. Otherwise we convert "expr"
358 * to an extra parameter (provided nesting_enabled is set).
360 * Otherwise, we simply return an expression that is equal
361 * to a parameter corresponding to the referenced variable.
363 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
365 ValueDecl *decl = expr->getDecl();
366 const Type *type = decl->getType().getTypePtr();
367 isl_id *id;
368 isl_space *dim;
369 isl_aff *aff;
370 isl_set *dom;
372 if (!type->isIntegerType()) {
373 unsupported(expr);
374 return NULL;
377 if (assigned_value.find(decl) != assigned_value.end()) {
378 if (assigned_value[decl])
379 return isl_pw_aff_copy(assigned_value[decl]);
380 else
381 return nested_access(expr);
384 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
385 dim = isl_space_params_alloc(ctx, 1);
387 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
389 dom = isl_set_universe(isl_space_copy(dim));
390 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
391 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
393 return isl_pw_aff_alloc(dom, aff);
396 /* Extract an affine expression from an integer division operation.
397 * In particular, if "expr" is lhs/rhs, then return
399 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
401 * The second argument (rhs) is required to be a (positive) integer constant.
403 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
405 Expr *rhs_expr;
406 isl_pw_aff *lhs, *lhs_f, *lhs_c;
407 isl_pw_aff *res;
408 isl_int v;
409 isl_set *cond;
411 rhs_expr = expr->getRHS();
412 isl_int_init(v);
413 if (extract_int(rhs_expr, &v) < 0) {
414 isl_int_clear(v);
415 return NULL;
418 lhs = extract_affine(expr->getLHS());
419 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
421 lhs = isl_pw_aff_scale_down(lhs, v);
422 isl_int_clear(v);
424 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(lhs));
425 lhs_c = isl_pw_aff_ceil(lhs);
426 res = isl_pw_aff_cond(isl_set_indicator_function(cond), lhs_f, lhs_c);
428 return res;
431 /* Extract an affine expression from a modulo operation.
432 * In particular, if "expr" is lhs/rhs, then return
434 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
436 * The second argument (rhs) is required to be a (positive) integer constant.
438 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
440 Expr *rhs_expr;
441 isl_pw_aff *lhs, *lhs_f, *lhs_c;
442 isl_pw_aff *res;
443 isl_int v;
444 isl_set *cond;
446 rhs_expr = expr->getRHS();
447 if (rhs_expr->getStmtClass() != Stmt::IntegerLiteralClass) {
448 unsupported(expr);
449 return NULL;
452 lhs = extract_affine(expr->getLHS());
453 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
455 isl_int_init(v);
456 extract_int(cast<IntegerLiteral>(rhs_expr), &v);
457 res = isl_pw_aff_scale_down(isl_pw_aff_copy(lhs), v);
459 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(res));
460 lhs_c = isl_pw_aff_ceil(res);
461 res = isl_pw_aff_cond(isl_set_indicator_function(cond), lhs_f, lhs_c);
463 res = isl_pw_aff_scale(res, v);
464 isl_int_clear(v);
466 res = isl_pw_aff_sub(lhs, res);
468 return res;
471 /* Extract an affine expression from a multiplication operation.
472 * This is only allowed if at least one of the two arguments
473 * is a (piecewise) constant.
475 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
477 isl_pw_aff *lhs;
478 isl_pw_aff *rhs;
480 lhs = extract_affine(expr->getLHS());
481 rhs = extract_affine(expr->getRHS());
483 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
484 isl_pw_aff_free(lhs);
485 isl_pw_aff_free(rhs);
486 unsupported(expr);
487 return NULL;
490 return isl_pw_aff_mul(lhs, rhs);
493 /* Extract an affine expression from an addition or subtraction operation.
495 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
497 isl_pw_aff *lhs;
498 isl_pw_aff *rhs;
500 lhs = extract_affine(expr->getLHS());
501 rhs = extract_affine(expr->getRHS());
503 switch (expr->getOpcode()) {
504 case BO_Add:
505 return isl_pw_aff_add(lhs, rhs);
506 case BO_Sub:
507 return isl_pw_aff_sub(lhs, rhs);
508 default:
509 isl_pw_aff_free(lhs);
510 isl_pw_aff_free(rhs);
511 return NULL;
516 /* Compute
518 * pwaff mod 2^width
520 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
521 unsigned width)
523 isl_int mod;
525 isl_int_init(mod);
526 isl_int_set_si(mod, 1);
527 isl_int_mul_2exp(mod, mod, width);
529 pwaff = isl_pw_aff_mod(pwaff, mod);
531 isl_int_clear(mod);
533 return pwaff;
536 /* Extract an affine expression from a boolean expression.
537 * In particular, return the expression "expr ? 1 : 0".
539 __isl_give isl_pw_aff *PetScan::extract_implicit_affine(Expr *expr)
541 isl_set *cond = extract_condition(expr);
542 return isl_set_indicator_function(cond);
545 /* Extract an affine expression from some binary operations.
546 * If the result of the expression is unsigned, then we wrap it
547 * based on the size of the type.
549 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
551 isl_pw_aff *res;
553 switch (expr->getOpcode()) {
554 case BO_Add:
555 case BO_Sub:
556 res = extract_affine_add(expr);
557 break;
558 case BO_Div:
559 res = extract_affine_div(expr);
560 break;
561 case BO_Rem:
562 res = extract_affine_mod(expr);
563 break;
564 case BO_Mul:
565 res = extract_affine_mul(expr);
566 break;
567 case BO_LT:
568 case BO_LE:
569 case BO_GT:
570 case BO_GE:
571 case BO_EQ:
572 case BO_NE:
573 case BO_LAnd:
574 case BO_LOr:
575 res = extract_implicit_affine(expr);
576 break;
577 default:
578 unsupported(expr);
579 return NULL;
582 if (expr->getType()->isUnsignedIntegerType())
583 res = wrap(res, ast_context.getIntWidth(expr->getType()));
585 return res;
588 /* Extract an affine expression from a negation operation.
590 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
592 if (expr->getOpcode() == UO_Minus)
593 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
594 if (expr->getOpcode() == UO_LNot)
595 return extract_implicit_affine(expr);
597 unsupported(expr);
598 return NULL;
601 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
603 return extract_affine(expr->getSubExpr());
606 /* Extract an affine expression from some special function calls.
607 * In particular, we handle "min", "max", "ceild" and "floord".
608 * In case of the latter two, the second argument needs to be
609 * a (positive) integer constant.
611 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
613 FunctionDecl *fd;
614 string name;
615 isl_pw_aff *aff1, *aff2;
617 fd = expr->getDirectCallee();
618 if (!fd) {
619 unsupported(expr);
620 return NULL;
623 name = fd->getDeclName().getAsString();
624 if (!(expr->getNumArgs() == 2 && name == "min") &&
625 !(expr->getNumArgs() == 2 && name == "max") &&
626 !(expr->getNumArgs() == 2 && name == "floord") &&
627 !(expr->getNumArgs() == 2 && name == "ceild")) {
628 unsupported(expr);
629 return NULL;
632 if (name == "min" || name == "max") {
633 aff1 = extract_affine(expr->getArg(0));
634 aff2 = extract_affine(expr->getArg(1));
636 if (name == "min")
637 aff1 = isl_pw_aff_min(aff1, aff2);
638 else
639 aff1 = isl_pw_aff_max(aff1, aff2);
640 } else if (name == "floord" || name == "ceild") {
641 isl_int v;
642 Expr *arg2 = expr->getArg(1);
644 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
645 unsupported(expr);
646 return NULL;
648 aff1 = extract_affine(expr->getArg(0));
649 isl_int_init(v);
650 extract_int(cast<IntegerLiteral>(arg2), &v);
651 aff1 = isl_pw_aff_scale_down(aff1, v);
652 isl_int_clear(v);
653 if (name == "floord")
654 aff1 = isl_pw_aff_floor(aff1);
655 else
656 aff1 = isl_pw_aff_ceil(aff1);
657 } else {
658 unsupported(expr);
659 return NULL;
662 return aff1;
666 /* This method is called when we come across an access that is
667 * nested in what is supposed to be an affine expression.
668 * If nesting is allowed, we return a new parameter that corresponds
669 * to this nested access. Otherwise, we simply complain.
671 * The new parameter is resolved in resolve_nested.
673 isl_pw_aff *PetScan::nested_access(Expr *expr)
675 isl_id *id;
676 isl_space *dim;
677 isl_aff *aff;
678 isl_set *dom;
680 if (!nesting_enabled) {
681 unsupported(expr);
682 return NULL;
685 id = isl_id_alloc(ctx, NULL, expr);
686 dim = isl_space_params_alloc(ctx, 1);
688 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
690 dom = isl_set_universe(isl_space_copy(dim));
691 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
692 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
694 return isl_pw_aff_alloc(dom, aff);
697 /* Affine expressions are not supposed to contain array accesses,
698 * but if nesting is allowed, we return a parameter corresponding
699 * to the array access.
701 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
703 return nested_access(expr);
706 /* Extract an affine expression from a conditional operation.
708 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
710 isl_set *cond;
711 isl_pw_aff *lhs, *rhs;
713 cond = extract_condition(expr->getCond());
714 lhs = extract_affine(expr->getTrueExpr());
715 rhs = extract_affine(expr->getFalseExpr());
717 return isl_pw_aff_cond(isl_set_indicator_function(cond), lhs, rhs);
720 /* Extract an affine expression, if possible, from "expr".
721 * Otherwise return NULL.
723 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
725 switch (expr->getStmtClass()) {
726 case Stmt::ImplicitCastExprClass:
727 return extract_affine(cast<ImplicitCastExpr>(expr));
728 case Stmt::IntegerLiteralClass:
729 return extract_affine(cast<IntegerLiteral>(expr));
730 case Stmt::DeclRefExprClass:
731 return extract_affine(cast<DeclRefExpr>(expr));
732 case Stmt::BinaryOperatorClass:
733 return extract_affine(cast<BinaryOperator>(expr));
734 case Stmt::UnaryOperatorClass:
735 return extract_affine(cast<UnaryOperator>(expr));
736 case Stmt::ParenExprClass:
737 return extract_affine(cast<ParenExpr>(expr));
738 case Stmt::CallExprClass:
739 return extract_affine(cast<CallExpr>(expr));
740 case Stmt::ArraySubscriptExprClass:
741 return extract_affine(cast<ArraySubscriptExpr>(expr));
742 case Stmt::ConditionalOperatorClass:
743 return extract_affine(cast<ConditionalOperator>(expr));
744 default:
745 unsupported(expr);
747 return NULL;
750 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
752 return extract_access(expr->getSubExpr());
755 /* Return the depth of an array of the given type.
757 static int array_depth(const Type *type)
759 if (type->isPointerType())
760 return 1 + array_depth(type->getPointeeType().getTypePtr());
761 if (type->isArrayType()) {
762 const ArrayType *atype;
763 type = type->getCanonicalTypeInternal().getTypePtr();
764 atype = cast<ArrayType>(type);
765 return 1 + array_depth(atype->getElementType().getTypePtr());
767 return 0;
770 /* Return the element type of the given array type.
772 static QualType base_type(QualType qt)
774 const Type *type = qt.getTypePtr();
776 if (type->isPointerType())
777 return base_type(type->getPointeeType());
778 if (type->isArrayType()) {
779 const ArrayType *atype;
780 type = type->getCanonicalTypeInternal().getTypePtr();
781 atype = cast<ArrayType>(type);
782 return base_type(atype->getElementType());
784 return qt;
787 /* Extract an access relation from a reference to a variable.
788 * If the variable has name "A" and its type corresponds to an
789 * array of depth d, then the returned access relation is of the
790 * form
792 * { [] -> A[i_1,...,i_d] }
794 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
796 ValueDecl *decl = expr->getDecl();
797 int depth = array_depth(decl->getType().getTypePtr());
798 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
799 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
800 isl_map *access_rel;
802 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
804 access_rel = isl_map_universe(dim);
806 return access_rel;
809 /* Extract an access relation from an integer contant.
810 * If the value of the constant is "v", then the returned access relation
811 * is
813 * { [] -> [v] }
815 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
817 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
820 /* Try and extract an access relation from the given Expr.
821 * Return NULL if it doesn't work out.
823 __isl_give isl_map *PetScan::extract_access(Expr *expr)
825 switch (expr->getStmtClass()) {
826 case Stmt::ImplicitCastExprClass:
827 return extract_access(cast<ImplicitCastExpr>(expr));
828 case Stmt::DeclRefExprClass:
829 return extract_access(cast<DeclRefExpr>(expr));
830 case Stmt::ArraySubscriptExprClass:
831 return extract_access(cast<ArraySubscriptExpr>(expr));
832 default:
833 unsupported(expr);
835 return NULL;
838 /* Assign the affine expression "index" to the output dimension "pos" of "map"
839 * and return the result.
841 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
842 __isl_take isl_pw_aff *index)
844 isl_map *index_map;
845 int len = isl_map_dim(map, isl_dim_out);
846 isl_id *id;
848 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
849 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
850 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
851 id = isl_map_get_tuple_id(map, isl_dim_out);
852 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
854 map = isl_map_intersect(map, index_map);
856 return map;
859 /* Extract an access relation from the given array subscript expression.
860 * If nesting is allowed in general, then we turn it on while
861 * examining the index expression.
863 * We first extract an access relation from the base.
864 * This will result in an access relation with a range that corresponds
865 * to the array being accessed and with earlier indices filled in already.
866 * We then extract the current index and fill that in as well.
867 * The position of the current index is based on the type of base.
868 * If base is the actual array variable, then the depth of this type
869 * will be the same as the depth of the array and we will fill in
870 * the first array index.
871 * Otherwise, the depth of the base type will be smaller and we will fill
872 * in a later index.
874 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
876 Expr *base = expr->getBase();
877 Expr *idx = expr->getIdx();
878 isl_pw_aff *index;
879 isl_map *base_access;
880 isl_map *access;
881 int depth = array_depth(base->getType().getTypePtr());
882 int pos;
883 bool save_nesting = nesting_enabled;
885 nesting_enabled = allow_nested;
887 base_access = extract_access(base);
888 index = extract_affine(idx);
890 nesting_enabled = save_nesting;
892 pos = isl_map_dim(base_access, isl_dim_out) - depth;
893 access = set_index(base_access, pos, index);
895 return access;
898 /* Check if "expr" calls function "minmax" with two arguments and if so
899 * make lhs and rhs refer to these two arguments.
901 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
903 CallExpr *call;
904 FunctionDecl *fd;
905 string name;
907 if (expr->getStmtClass() != Stmt::CallExprClass)
908 return false;
910 call = cast<CallExpr>(expr);
911 fd = call->getDirectCallee();
912 if (!fd)
913 return false;
915 if (call->getNumArgs() != 2)
916 return false;
918 name = fd->getDeclName().getAsString();
919 if (name != minmax)
920 return false;
922 lhs = call->getArg(0);
923 rhs = call->getArg(1);
925 return true;
928 /* Check if "expr" is of the form min(lhs, rhs) and if so make
929 * lhs and rhs refer to the two arguments.
931 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
933 return is_minmax(expr, "min", lhs, rhs);
936 /* Check if "expr" is of the form max(lhs, rhs) and if so make
937 * lhs and rhs refer to the two arguments.
939 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
941 return is_minmax(expr, "max", lhs, rhs);
944 /* Extract a set of values satisfying the comparison "LHS op RHS"
945 * "comp" is the original statement that "LHS op RHS" is derived from
946 * and is used for diagnostics.
948 * If the comparison is of the form
950 * a <= min(b,c)
952 * then the set is constructed as the intersection of the set corresponding
953 * to the comparisons
955 * a <= b and a <= c
957 * A similar optimization is performed for max(a,b) <= c.
958 * We do this because that will lead to simpler representations of the set.
959 * If isl is ever enhanced to explicitly deal with min and max expressions,
960 * this optimization can be removed.
962 __isl_give isl_set *PetScan::extract_comparison(BinaryOperatorKind op,
963 Expr *LHS, Expr *RHS, Stmt *comp)
965 isl_pw_aff *lhs;
966 isl_pw_aff *rhs;
967 isl_set *cond;
969 if (op == BO_GT)
970 return extract_comparison(BO_LT, RHS, LHS, comp);
971 if (op == BO_GE)
972 return extract_comparison(BO_LE, RHS, LHS, comp);
974 if (op == BO_LT || op == BO_LE) {
975 Expr *expr1, *expr2;
976 isl_set *set1, *set2;
977 if (is_min(RHS, expr1, expr2)) {
978 set1 = extract_comparison(op, LHS, expr1, comp);
979 set2 = extract_comparison(op, LHS, expr2, comp);
980 return isl_set_intersect(set1, set2);
982 if (is_max(LHS, expr1, expr2)) {
983 set1 = extract_comparison(op, expr1, RHS, comp);
984 set2 = extract_comparison(op, expr2, RHS, comp);
985 return isl_set_intersect(set1, set2);
989 lhs = extract_affine(LHS);
990 rhs = extract_affine(RHS);
992 switch (op) {
993 case BO_LT:
994 cond = isl_pw_aff_lt_set(lhs, rhs);
995 break;
996 case BO_LE:
997 cond = isl_pw_aff_le_set(lhs, rhs);
998 break;
999 case BO_EQ:
1000 cond = isl_pw_aff_eq_set(lhs, rhs);
1001 break;
1002 case BO_NE:
1003 cond = isl_pw_aff_ne_set(lhs, rhs);
1004 break;
1005 default:
1006 isl_pw_aff_free(lhs);
1007 isl_pw_aff_free(rhs);
1008 unsupported(comp);
1009 return NULL;
1012 cond = isl_set_coalesce(cond);
1014 return cond;
1017 __isl_give isl_set *PetScan::extract_comparison(BinaryOperator *comp)
1019 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1020 comp->getRHS(), comp);
1023 /* Extract a set of values satisfying the negation (logical not)
1024 * of a subexpression.
1026 __isl_give isl_set *PetScan::extract_boolean(UnaryOperator *op)
1028 isl_set *cond;
1030 cond = extract_condition(op->getSubExpr());
1032 return isl_set_complement(cond);
1035 /* Extract a set of values satisfying the union (logical or)
1036 * or intersection (logical and) of two subexpressions.
1038 __isl_give isl_set *PetScan::extract_boolean(BinaryOperator *comp)
1040 isl_set *lhs;
1041 isl_set *rhs;
1042 isl_set *cond;
1044 lhs = extract_condition(comp->getLHS());
1045 rhs = extract_condition(comp->getRHS());
1047 switch (comp->getOpcode()) {
1048 case BO_LAnd:
1049 cond = isl_set_intersect(lhs, rhs);
1050 break;
1051 case BO_LOr:
1052 cond = isl_set_union(lhs, rhs);
1053 break;
1054 default:
1055 isl_set_free(lhs);
1056 isl_set_free(rhs);
1057 unsupported(comp);
1058 return NULL;
1061 return cond;
1064 __isl_give isl_set *PetScan::extract_condition(UnaryOperator *expr)
1066 switch (expr->getOpcode()) {
1067 case UO_LNot:
1068 return extract_boolean(expr);
1069 default:
1070 unsupported(expr);
1071 return NULL;
1075 /* Extract a set of values satisfying the condition "expr != 0".
1077 __isl_give isl_set *PetScan::extract_implicit_condition(Expr *expr)
1079 return isl_pw_aff_non_zero_set(extract_affine(expr));
1082 /* Extract a set of values satisfying the condition expressed by "expr".
1084 * If the expression doesn't look like a condition, we assume it
1085 * is an affine expression and return the condition "expr != 0".
1087 __isl_give isl_set *PetScan::extract_condition(Expr *expr)
1089 BinaryOperator *comp;
1091 if (!expr)
1092 return isl_set_universe(isl_space_params_alloc(ctx, 0));
1094 if (expr->getStmtClass() == Stmt::ParenExprClass)
1095 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1097 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1098 return extract_condition(cast<UnaryOperator>(expr));
1100 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1101 return extract_implicit_condition(expr);
1103 comp = cast<BinaryOperator>(expr);
1104 switch (comp->getOpcode()) {
1105 case BO_LT:
1106 case BO_LE:
1107 case BO_GT:
1108 case BO_GE:
1109 case BO_EQ:
1110 case BO_NE:
1111 return extract_comparison(comp);
1112 case BO_LAnd:
1113 case BO_LOr:
1114 return extract_boolean(comp);
1115 default:
1116 return extract_implicit_condition(expr);
1120 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1122 switch (kind) {
1123 case UO_Minus:
1124 return pet_op_minus;
1125 default:
1126 return pet_op_last;
1130 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1132 switch (kind) {
1133 case BO_AddAssign:
1134 return pet_op_add_assign;
1135 case BO_SubAssign:
1136 return pet_op_sub_assign;
1137 case BO_MulAssign:
1138 return pet_op_mul_assign;
1139 case BO_DivAssign:
1140 return pet_op_div_assign;
1141 case BO_Assign:
1142 return pet_op_assign;
1143 case BO_Add:
1144 return pet_op_add;
1145 case BO_Sub:
1146 return pet_op_sub;
1147 case BO_Mul:
1148 return pet_op_mul;
1149 case BO_Div:
1150 return pet_op_div;
1151 case BO_EQ:
1152 return pet_op_eq;
1153 case BO_LE:
1154 return pet_op_le;
1155 case BO_LT:
1156 return pet_op_lt;
1157 case BO_GT:
1158 return pet_op_gt;
1159 default:
1160 return pet_op_last;
1164 /* Construct a pet_expr representing a unary operator expression.
1166 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1168 struct pet_expr *arg;
1169 enum pet_op_type op;
1171 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1172 if (op == pet_op_last) {
1173 unsupported(expr);
1174 return NULL;
1177 arg = extract_expr(expr->getSubExpr());
1179 return pet_expr_new_unary(ctx, op, arg);
1182 /* Mark the given access pet_expr as a write.
1183 * If a scalar is being accessed, then mark its value
1184 * as unknown in assigned_value.
1186 void PetScan::mark_write(struct pet_expr *access)
1188 isl_id *id;
1189 ValueDecl *decl;
1191 access->acc.write = 1;
1192 access->acc.read = 0;
1194 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1195 return;
1197 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1198 decl = (ValueDecl *) isl_id_get_user(id);
1199 clear_assignment(assigned_value, decl);
1200 isl_id_free(id);
1203 /* Construct a pet_expr representing a binary operator expression.
1205 * If the top level operator is an assignment and the LHS is an access,
1206 * then we mark that access as a write. If the operator is a compound
1207 * assignment, the access is marked as both a read and a write.
1209 * If "expr" assigns something to a scalar variable, then we mark
1210 * the variable as having been assigned. If, furthermore, the expression
1211 * is affine, then keep track of this value in assigned_value
1212 * so that we can plug it in when we later come across the same variable.
1214 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1216 struct pet_expr *lhs, *rhs;
1217 enum pet_op_type op;
1219 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1220 if (op == pet_op_last) {
1221 unsupported(expr);
1222 return NULL;
1225 lhs = extract_expr(expr->getLHS());
1226 rhs = extract_expr(expr->getRHS());
1228 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1229 mark_write(lhs);
1230 if (expr->isCompoundAssignmentOp())
1231 lhs->acc.read = 1;
1234 if (expr->getOpcode() == BO_Assign &&
1235 lhs && lhs->type == pet_expr_access &&
1236 isl_map_dim(lhs->acc.access, isl_dim_out) == 0) {
1237 isl_id *id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1238 ValueDecl *decl = (ValueDecl *) isl_id_get_user(id);
1239 Expr *rhs = expr->getRHS();
1240 isl_pw_aff *pa = try_extract_affine(rhs);
1241 clear_assignment(assigned_value, decl);
1242 if (pa) {
1243 assigned_value[decl] = pa;
1244 insert_expression(pa);
1246 isl_id_free(id);
1249 return pet_expr_new_binary(ctx, op, lhs, rhs);
1252 /* Construct a pet_expr representing a conditional operation.
1254 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1256 struct pet_expr *cond, *lhs, *rhs;
1258 cond = extract_expr(expr->getCond());
1259 lhs = extract_expr(expr->getTrueExpr());
1260 rhs = extract_expr(expr->getFalseExpr());
1262 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1265 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1267 return extract_expr(expr->getSubExpr());
1270 /* Construct a pet_expr representing a floating point value.
1272 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1274 return pet_expr_new_double(ctx, expr->getValueAsApproximateDouble());
1277 /* Extract an access relation from "expr" and then convert it into
1278 * a pet_expr.
1280 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1282 isl_map *access;
1283 struct pet_expr *pe;
1285 switch (expr->getStmtClass()) {
1286 case Stmt::ArraySubscriptExprClass:
1287 access = extract_access(cast<ArraySubscriptExpr>(expr));
1288 break;
1289 case Stmt::DeclRefExprClass:
1290 access = extract_access(cast<DeclRefExpr>(expr));
1291 break;
1292 case Stmt::IntegerLiteralClass:
1293 access = extract_access(cast<IntegerLiteral>(expr));
1294 break;
1295 default:
1296 unsupported(expr);
1297 return NULL;
1300 pe = pet_expr_from_access(access);
1302 return pe;
1305 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1307 return extract_expr(expr->getSubExpr());
1310 /* Construct a pet_expr representing a function call.
1312 * If we are passing along a pointer to an array element
1313 * or an entire row or even higher dimensional slice of an array,
1314 * then the function being called may write into the array.
1316 * We assume here that if the function is declared to take a pointer
1317 * to a const type, then the function will perform a read
1318 * and that otherwise, it will perform a write.
1320 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1322 struct pet_expr *res = NULL;
1323 FunctionDecl *fd;
1324 string name;
1326 fd = expr->getDirectCallee();
1327 if (!fd) {
1328 unsupported(expr);
1329 return NULL;
1332 name = fd->getDeclName().getAsString();
1333 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1334 if (!res)
1335 return NULL;
1337 for (int i = 0; i < expr->getNumArgs(); ++i) {
1338 Expr *arg = expr->getArg(i);
1339 int is_addr = 0;
1340 pet_expr *main_arg;
1342 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1343 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1344 arg = ice->getSubExpr();
1346 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1347 UnaryOperator *op = cast<UnaryOperator>(arg);
1348 if (op->getOpcode() == UO_AddrOf) {
1349 is_addr = 1;
1350 arg = op->getSubExpr();
1353 res->args[i] = PetScan::extract_expr(arg);
1354 main_arg = res->args[i];
1355 if (is_addr)
1356 res->args[i] = pet_expr_new_unary(ctx,
1357 pet_op_address_of, res->args[i]);
1358 if (!res->args[i])
1359 goto error;
1360 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1361 array_depth(arg->getType().getTypePtr()) > 0)
1362 is_addr = 1;
1363 if (is_addr && main_arg->type == pet_expr_access) {
1364 ParmVarDecl *parm;
1365 if (!fd->hasPrototype()) {
1366 unsupported(expr, "prototype required");
1367 goto error;
1369 parm = fd->getParamDecl(i);
1370 if (!const_base(parm->getType()))
1371 mark_write(main_arg);
1375 return res;
1376 error:
1377 pet_expr_free(res);
1378 return NULL;
1381 /* Try and onstruct a pet_expr representing "expr".
1383 struct pet_expr *PetScan::extract_expr(Expr *expr)
1385 switch (expr->getStmtClass()) {
1386 case Stmt::UnaryOperatorClass:
1387 return extract_expr(cast<UnaryOperator>(expr));
1388 case Stmt::CompoundAssignOperatorClass:
1389 case Stmt::BinaryOperatorClass:
1390 return extract_expr(cast<BinaryOperator>(expr));
1391 case Stmt::ImplicitCastExprClass:
1392 return extract_expr(cast<ImplicitCastExpr>(expr));
1393 case Stmt::ArraySubscriptExprClass:
1394 case Stmt::DeclRefExprClass:
1395 case Stmt::IntegerLiteralClass:
1396 return extract_access_expr(expr);
1397 case Stmt::FloatingLiteralClass:
1398 return extract_expr(cast<FloatingLiteral>(expr));
1399 case Stmt::ParenExprClass:
1400 return extract_expr(cast<ParenExpr>(expr));
1401 case Stmt::ConditionalOperatorClass:
1402 return extract_expr(cast<ConditionalOperator>(expr));
1403 case Stmt::CallExprClass:
1404 return extract_expr(cast<CallExpr>(expr));
1405 default:
1406 unsupported(expr);
1408 return NULL;
1411 /* Check if the given initialization statement is an assignment.
1412 * If so, return that assignment. Otherwise return NULL.
1414 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1416 BinaryOperator *ass;
1418 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1419 return NULL;
1421 ass = cast<BinaryOperator>(init);
1422 if (ass->getOpcode() != BO_Assign)
1423 return NULL;
1425 return ass;
1428 /* Check if the given initialization statement is a declaration
1429 * of a single variable.
1430 * If so, return that declaration. Otherwise return NULL.
1432 Decl *PetScan::initialization_declaration(Stmt *init)
1434 DeclStmt *decl;
1436 if (init->getStmtClass() != Stmt::DeclStmtClass)
1437 return NULL;
1439 decl = cast<DeclStmt>(init);
1441 if (!decl->isSingleDecl())
1442 return NULL;
1444 return decl->getSingleDecl();
1447 /* Given the assignment operator in the initialization of a for loop,
1448 * extract the induction variable, i.e., the (integer)variable being
1449 * assigned.
1451 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1453 Expr *lhs;
1454 DeclRefExpr *ref;
1455 ValueDecl *decl;
1456 const Type *type;
1458 lhs = init->getLHS();
1459 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1460 unsupported(init);
1461 return NULL;
1464 ref = cast<DeclRefExpr>(lhs);
1465 decl = ref->getDecl();
1466 type = decl->getType().getTypePtr();
1468 if (!type->isIntegerType()) {
1469 unsupported(lhs);
1470 return NULL;
1473 return decl;
1476 /* Given the initialization statement of a for loop and the single
1477 * declaration in this initialization statement,
1478 * extract the induction variable, i.e., the (integer) variable being
1479 * declared.
1481 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1483 VarDecl *vd;
1485 vd = cast<VarDecl>(decl);
1487 const QualType type = vd->getType();
1488 if (!type->isIntegerType()) {
1489 unsupported(init);
1490 return NULL;
1493 if (!vd->getInit()) {
1494 unsupported(init);
1495 return NULL;
1498 return vd;
1501 /* Check that op is of the form iv++ or iv--.
1502 * "inc" is accordingly set to 1 or -1.
1504 bool PetScan::check_unary_increment(UnaryOperator *op, clang::ValueDecl *iv,
1505 isl_int &inc)
1507 Expr *sub;
1508 DeclRefExpr *ref;
1510 if (!op->isIncrementDecrementOp()) {
1511 unsupported(op);
1512 return false;
1515 if (op->isIncrementOp())
1516 isl_int_set_si(inc, 1);
1517 else
1518 isl_int_set_si(inc, -1);
1520 sub = op->getSubExpr();
1521 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1522 unsupported(op);
1523 return false;
1526 ref = cast<DeclRefExpr>(sub);
1527 if (ref->getDecl() != iv) {
1528 unsupported(op);
1529 return false;
1532 return true;
1535 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1536 * has a single constant expression on a universe domain, then
1537 * put this constant in *user.
1539 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1540 void *user)
1542 isl_int *inc = (isl_int *)user;
1543 int res = 0;
1545 if (!isl_set_plain_is_universe(set) || !isl_aff_is_cst(aff))
1546 res = -1;
1547 else
1548 isl_aff_get_constant(aff, inc);
1550 isl_set_free(set);
1551 isl_aff_free(aff);
1553 return res;
1556 /* Check if op is of the form
1558 * iv = iv + inc
1560 * with inc a constant and set "inc" accordingly.
1562 * We extract an affine expression from the RHS and the subtract iv.
1563 * The result should be a constant.
1565 bool PetScan::check_binary_increment(BinaryOperator *op, clang::ValueDecl *iv,
1566 isl_int &inc)
1568 Expr *lhs;
1569 DeclRefExpr *ref;
1570 isl_id *id;
1571 isl_space *dim;
1572 isl_aff *aff;
1573 isl_pw_aff *val;
1575 if (op->getOpcode() != BO_Assign) {
1576 unsupported(op);
1577 return false;
1580 lhs = op->getLHS();
1581 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1582 unsupported(op);
1583 return false;
1586 ref = cast<DeclRefExpr>(lhs);
1587 if (ref->getDecl() != iv) {
1588 unsupported(op);
1589 return false;
1592 val = extract_affine(op->getRHS());
1594 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1596 dim = isl_space_params_alloc(ctx, 1);
1597 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1598 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1599 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1601 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1603 if (isl_pw_aff_foreach_piece(val, &extract_cst, &inc) < 0) {
1604 isl_pw_aff_free(val);
1605 unsupported(op);
1606 return false;
1609 isl_pw_aff_free(val);
1611 return true;
1614 /* Check that op is of the form iv += cst or iv -= cst.
1615 * "inc" is set to cst or -cst accordingly.
1617 bool PetScan::check_compound_increment(CompoundAssignOperator *op,
1618 clang::ValueDecl *iv, isl_int &inc)
1620 Expr *lhs, *rhs;
1621 DeclRefExpr *ref;
1622 bool neg = false;
1624 BinaryOperatorKind opcode;
1626 opcode = op->getOpcode();
1627 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1628 unsupported(op);
1629 return false;
1631 if (opcode == BO_SubAssign)
1632 neg = true;
1634 lhs = op->getLHS();
1635 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1636 unsupported(op);
1637 return false;
1640 ref = cast<DeclRefExpr>(lhs);
1641 if (ref->getDecl() != iv) {
1642 unsupported(op);
1643 return false;
1646 rhs = op->getRHS();
1648 if (rhs->getStmtClass() == Stmt::UnaryOperatorClass) {
1649 UnaryOperator *op = cast<UnaryOperator>(rhs);
1650 if (op->getOpcode() != UO_Minus) {
1651 unsupported(op);
1652 return false;
1655 neg = !neg;
1657 rhs = op->getSubExpr();
1660 if (rhs->getStmtClass() != Stmt::IntegerLiteralClass) {
1661 unsupported(op);
1662 return false;
1665 extract_int(cast<IntegerLiteral>(rhs), &inc);
1666 if (neg)
1667 isl_int_neg(inc, inc);
1669 return true;
1672 /* Check that the increment of the given for loop increments
1673 * (or decrements) the induction variable "iv".
1674 * "up" is set to true if the induction variable is incremented.
1676 bool PetScan::check_increment(ForStmt *stmt, ValueDecl *iv, isl_int &v)
1678 Stmt *inc = stmt->getInc();
1680 if (!inc) {
1681 unsupported(stmt);
1682 return false;
1685 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1686 return check_unary_increment(cast<UnaryOperator>(inc), iv, v);
1687 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1688 return check_compound_increment(
1689 cast<CompoundAssignOperator>(inc), iv, v);
1690 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1691 return check_binary_increment(cast<BinaryOperator>(inc), iv, v);
1693 unsupported(inc);
1694 return false;
1697 /* Embed the given iteration domain in an extra outer loop
1698 * with induction variable "var".
1699 * If this variable appeared as a parameter in the constraints,
1700 * it is replaced by the new outermost dimension.
1702 static __isl_give isl_set *embed(__isl_take isl_set *set,
1703 __isl_take isl_id *var)
1705 int pos;
1707 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1708 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1709 if (pos >= 0) {
1710 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1711 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1714 isl_id_free(var);
1715 return set;
1718 /* Construct a pet_scop for an infinite loop around the given body.
1720 * We extract a pet_scop for the body and then embed it in a loop with
1721 * iteration domain
1723 * { [t] : t >= 0 }
1725 * and schedule
1727 * { [t] -> [t] }
1729 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1731 isl_id *id;
1732 isl_space *dim;
1733 isl_set *domain;
1734 isl_map *sched;
1735 struct pet_scop *scop;
1737 scop = extract(body);
1738 if (!scop)
1739 return NULL;
1741 id = isl_id_alloc(ctx, "t", NULL);
1742 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1743 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
1744 dim = isl_space_from_domain(isl_set_get_space(domain));
1745 dim = isl_space_add_dims(dim, isl_dim_out, 1);
1746 sched = isl_map_universe(dim);
1747 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
1748 scop = pet_scop_embed(scop, domain, sched, id);
1750 return scop;
1753 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1755 * for (;;)
1756 * body
1759 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1761 return extract_infinite_loop(stmt->getBody());
1764 /* Check if the while loop is of the form
1766 * while (1)
1767 * body
1769 * If so, construct a scop for an infinite loop around body.
1770 * Otherwise, fail.
1772 struct pet_scop *PetScan::extract(WhileStmt *stmt)
1774 Expr *cond;
1775 isl_set *set;
1776 int is_universe;
1778 cond = stmt->getCond();
1779 if (!cond) {
1780 unsupported(stmt);
1781 return NULL;
1784 set = extract_condition(cond);
1785 is_universe = isl_set_plain_is_universe(set);
1786 isl_set_free(set);
1788 if (!is_universe) {
1789 unsupported(stmt);
1790 return NULL;
1793 return extract_infinite_loop(stmt->getBody());
1796 /* Check whether "cond" expresses a simple loop bound
1797 * on the only set dimension.
1798 * In particular, if "up" is set then "cond" should contain only
1799 * upper bounds on the set dimension.
1800 * Otherwise, it should contain only lower bounds.
1802 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
1804 if (isl_int_is_pos(inc))
1805 return !isl_set_dim_has_lower_bound(cond, isl_dim_set, 0);
1806 else
1807 return !isl_set_dim_has_upper_bound(cond, isl_dim_set, 0);
1810 /* Extend a condition on a given iteration of a loop to one that
1811 * imposes the same condition on all previous iterations.
1812 * "domain" expresses the lower [upper] bound on the iterations
1813 * when inc is positive [negative].
1815 * In particular, we construct the condition (when inc is positive)
1817 * forall i' : (domain(i') and i' <= i) => cond(i')
1819 * which is equivalent to
1821 * not exists i' : domain(i') and i' <= i and not cond(i')
1823 * We construct this set by negating cond, applying a map
1825 * { [i'] -> [i] : domain(i') and i' <= i }
1827 * and then negating the result again.
1829 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
1830 __isl_take isl_set *domain, isl_int inc)
1832 isl_map *previous_to_this;
1834 if (isl_int_is_pos(inc))
1835 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
1836 else
1837 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
1839 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
1841 cond = isl_set_complement(cond);
1842 cond = isl_set_apply(cond, previous_to_this);
1843 cond = isl_set_complement(cond);
1845 return cond;
1848 /* Construct a domain of the form
1850 * [id] -> { [] : exists a: id = init + a * inc and a >= 0 }
1852 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
1853 __isl_take isl_pw_aff *init, isl_int inc)
1855 isl_aff *aff;
1856 isl_space *dim;
1857 isl_set *set;
1859 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
1860 dim = isl_pw_aff_get_domain_space(init);
1861 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1862 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
1863 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
1865 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
1866 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1867 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1868 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1870 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
1872 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
1874 return isl_set_project_out(set, isl_dim_set, 0, 1);
1877 static unsigned get_type_size(ValueDecl *decl)
1879 return decl->getASTContext().getIntWidth(decl->getType());
1882 /* Assuming "cond" represents a simple bound on a loop where the loop
1883 * iterator "iv" is incremented (or decremented) by one, check if wrapping
1884 * is possible.
1886 * Under the given assumptions, wrapping is only possible if "cond" allows
1887 * for the last value before wrapping, i.e., 2^width - 1 in case of an
1888 * increasing iterator and 0 in case of a decreasing iterator.
1890 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
1892 bool cw;
1893 isl_int limit;
1894 isl_set *test;
1896 test = isl_set_copy(cond);
1898 isl_int_init(limit);
1899 if (isl_int_is_neg(inc))
1900 isl_int_set_si(limit, 0);
1901 else {
1902 isl_int_set_si(limit, 1);
1903 isl_int_mul_2exp(limit, limit, get_type_size(iv));
1904 isl_int_sub_ui(limit, limit, 1);
1907 test = isl_set_fix(cond, isl_dim_set, 0, limit);
1908 cw = !isl_set_is_empty(test);
1909 isl_set_free(test);
1911 isl_int_clear(limit);
1913 return cw;
1916 /* Given a one-dimensional space, construct the following mapping on this
1917 * space
1919 * { [v] -> [v mod 2^width] }
1921 * where width is the number of bits used to represent the values
1922 * of the unsigned variable "iv".
1924 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
1925 ValueDecl *iv)
1927 isl_int mod;
1928 isl_aff *aff;
1929 isl_map *map;
1931 isl_int_init(mod);
1932 isl_int_set_si(mod, 1);
1933 isl_int_mul_2exp(mod, mod, get_type_size(iv));
1935 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1936 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1937 aff = isl_aff_mod(aff, mod);
1939 isl_int_clear(mod);
1941 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
1942 map = isl_map_reverse(map);
1945 /* Construct a pet_scop for a for statement.
1946 * The for loop is required to be of the form
1948 * for (i = init; condition; ++i)
1950 * or
1952 * for (i = init; condition; --i)
1954 * The initialization of the for loop should either be an assignment
1955 * to an integer variable, or a declaration of such a variable with
1956 * initialization.
1958 * The condition is allowed to contain nested accesses, provided
1959 * they are not being written to inside the body of the loop.
1961 * We extract a pet_scop for the body and then embed it in a loop with
1962 * iteration domain and schedule
1964 * { [i] : i >= init and condition' }
1965 * { [i] -> [i] }
1967 * or
1969 * { [i] : i <= init and condition' }
1970 * { [i] -> [-i] }
1972 * Where condition' is equal to condition if the latter is
1973 * a simple upper [lower] bound and a condition that is extended
1974 * to apply to all previous iterations otherwise.
1976 * If the stride of the loop is not 1, then "i >= init" is replaced by
1978 * (exists a: i = init + stride * a and a >= 0)
1980 * If the loop iterator i is unsigned, then wrapping may occur.
1981 * During the computation, we work with a virtual iterator that
1982 * does not wrap. However, the condition in the code applies
1983 * to the wrapped value, so we need to change condition(i)
1984 * into condition([i % 2^width]).
1985 * After computing the virtual domain and schedule, we apply
1986 * the function { [v] -> [v % 2^width] } to the domain and the domain
1987 * of the schedule. In order not to lose any information, we also
1988 * need to intersect the domain of the schedule with the virtual domain
1989 * first, since some iterations in the wrapped domain may be scheduled
1990 * several times, typically an infinite number of times.
1991 * Note that there is no need to perform this final wrapping
1992 * if the loop condition (after wrapping) is simple.
1994 * Wrapping on unsigned iterators can be avoided entirely if
1995 * loop condition is simple, the loop iterator is incremented
1996 * [decremented] by one and the last value before wrapping cannot
1997 * possibly satisfy the loop condition.
1999 * Before extracting a pet_scop from the body we remove all
2000 * assignments in assigned_value to variables that are assigned
2001 * somewhere in the body of the loop.
2003 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2005 BinaryOperator *ass;
2006 Decl *decl;
2007 Stmt *init;
2008 Expr *lhs, *rhs;
2009 ValueDecl *iv;
2010 isl_space *dim;
2011 isl_set *domain;
2012 isl_map *sched;
2013 isl_set *cond = NULL;
2014 isl_id *id;
2015 struct pet_scop *scop;
2016 assigned_value_cache cache(assigned_value);
2017 isl_int inc;
2018 bool is_one;
2019 bool is_unsigned;
2020 bool is_simple;
2021 isl_map *wrap = NULL;
2023 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2024 return extract_infinite_for(stmt);
2026 init = stmt->getInit();
2027 if (!init) {
2028 unsupported(stmt);
2029 return NULL;
2031 if ((ass = initialization_assignment(init)) != NULL) {
2032 iv = extract_induction_variable(ass);
2033 if (!iv)
2034 return NULL;
2035 lhs = ass->getLHS();
2036 rhs = ass->getRHS();
2037 } else if ((decl = initialization_declaration(init)) != NULL) {
2038 VarDecl *var = extract_induction_variable(init, decl);
2039 if (!var)
2040 return NULL;
2041 iv = var;
2042 rhs = var->getInit();
2043 lhs = create_DeclRefExpr(var);
2044 } else {
2045 unsupported(stmt->getInit());
2046 return NULL;
2049 isl_int_init(inc);
2050 if (!check_increment(stmt, iv, inc)) {
2051 isl_int_clear(inc);
2052 return NULL;
2055 is_unsigned = iv->getType()->isUnsignedIntegerType();
2057 assigned_value.erase(iv);
2058 clear_assignments clear(assigned_value);
2059 clear.TraverseStmt(stmt->getBody());
2061 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2063 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
2064 if (is_one)
2065 domain = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
2066 lhs, rhs, init);
2067 else {
2068 isl_pw_aff *lb = extract_affine(rhs);
2069 domain = strided_domain(isl_id_copy(id), lb, inc);
2072 scop = extract(stmt->getBody());
2074 cond = try_extract_nested_condition(stmt->getCond());
2075 if (cond && !is_nested_allowed(cond, scop)) {
2076 isl_set_free(cond);
2077 cond = NULL;
2080 if (!cond)
2081 cond = extract_condition(stmt->getCond());
2082 cond = embed(cond, isl_id_copy(id));
2083 domain = embed(domain, isl_id_copy(id));
2084 is_simple = is_simple_bound(cond, inc);
2085 if (is_unsigned &&
2086 (!is_simple || !is_one || can_wrap(cond, iv, inc))) {
2087 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2088 cond = isl_set_apply(cond, isl_map_reverse(isl_map_copy(wrap)));
2089 is_simple = is_simple && is_simple_bound(cond, inc);
2091 if (!is_simple)
2092 cond = valid_for_each_iteration(cond,
2093 isl_set_copy(domain), inc);
2094 domain = isl_set_intersect(domain, cond);
2095 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2096 dim = isl_space_from_domain(isl_set_get_space(domain));
2097 dim = isl_space_add_dims(dim, isl_dim_out, 1);
2098 sched = isl_map_universe(dim);
2099 if (isl_int_is_pos(inc))
2100 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2101 else
2102 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2104 if (is_unsigned && !is_simple) {
2105 wrap = isl_map_set_dim_id(wrap,
2106 isl_dim_out, 0, isl_id_copy(id));
2107 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2108 domain = isl_set_apply(domain, isl_map_copy(wrap));
2109 sched = isl_map_apply_domain(sched, wrap);
2110 } else
2111 isl_map_free(wrap);
2113 scop = pet_scop_embed(scop, domain, sched, id);
2114 scop = resolve_nested(scop);
2115 clear_assignment(assigned_value, iv);
2117 isl_int_clear(inc);
2118 return scop;
2121 struct pet_scop *PetScan::extract(CompoundStmt *stmt)
2123 return extract(stmt->children());
2126 /* Does "id" refer to a nested access?
2128 static bool is_nested_parameter(__isl_keep isl_id *id)
2130 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2133 /* Does parameter "pos" of "space" refer to a nested access?
2135 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2137 bool nested;
2138 isl_id *id;
2140 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2141 nested = is_nested_parameter(id);
2142 isl_id_free(id);
2144 return nested;
2147 /* Does parameter "pos" of "map" refer to a nested access?
2149 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2151 bool nested;
2152 isl_id *id;
2154 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2155 nested = is_nested_parameter(id);
2156 isl_id_free(id);
2158 return nested;
2161 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2163 static int n_nested_parameter(__isl_keep isl_space *space)
2165 int n = 0;
2166 int nparam;
2168 nparam = isl_space_dim(space, isl_dim_param);
2169 for (int i = 0; i < nparam; ++i)
2170 if (is_nested_parameter(space, i))
2171 ++n;
2173 return n;
2176 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2178 static int n_nested_parameter(__isl_keep isl_map *map)
2180 isl_space *space;
2181 int n;
2183 space = isl_map_get_space(map);
2184 n = n_nested_parameter(space);
2185 isl_space_free(space);
2187 return n;
2190 /* For each nested access parameter in "space",
2191 * construct a corresponding pet_expr, place it in args and
2192 * record its position in "param2pos".
2193 * "n_arg" is the number of elements that are already in args.
2194 * The position recorded in "param2pos" takes this number into account.
2195 * If the pet_expr corresponding to a parameter is identical to
2196 * the pet_expr corresponding to an earlier parameter, then these two
2197 * parameters are made to refer to the same element in args.
2199 * Return the final number of elements in args or -1 if an error has occurred.
2201 int PetScan::extract_nested(__isl_keep isl_space *space,
2202 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
2204 int nparam;
2206 nparam = isl_space_dim(space, isl_dim_param);
2207 for (int i = 0; i < nparam; ++i) {
2208 int j;
2209 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2210 Expr *nested;
2212 if (!is_nested_parameter(id)) {
2213 isl_id_free(id);
2214 continue;
2217 nested = (Expr *) isl_id_get_user(id);
2218 args[n_arg] = extract_expr(nested);
2219 if (!args[n_arg])
2220 return -1;
2222 for (j = 0; j < n_arg; ++j)
2223 if (pet_expr_is_equal(args[j], args[n_arg]))
2224 break;
2226 if (j < n_arg) {
2227 pet_expr_free(args[n_arg]);
2228 args[n_arg] = NULL;
2229 param2pos[i] = j;
2230 } else
2231 param2pos[i] = n_arg++;
2233 isl_id_free(id);
2236 return n_arg;
2239 /* For each nested access parameter in the access relations in "expr",
2240 * construct a corresponding pet_expr, place it in expr->args and
2241 * record its position in "param2pos".
2242 * n is the number of nested access parameters.
2244 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
2245 std::map<int,int> &param2pos)
2247 isl_space *space;
2249 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
2250 expr->n_arg = n;
2251 if (!expr->args)
2252 goto error;
2254 space = isl_map_get_space(expr->acc.access);
2255 n = extract_nested(space, 0, expr->args, param2pos);
2256 isl_space_free(space);
2258 if (n < 0)
2259 goto error;
2261 expr->n_arg = n;
2262 return expr;
2263 error:
2264 pet_expr_free(expr);
2265 return NULL;
2268 /* Look for parameters in any access relation in "expr" that
2269 * refer to nested accesses. In particular, these are
2270 * parameters with no name.
2272 * If there are any such parameters, then the domain of the access
2273 * relation, which is still [] at this point, is replaced by
2274 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2275 * (after identifying identical nested accesses).
2276 * The parameters are then equated to the corresponding t dimensions
2277 * and subsequently projected out.
2278 * param2pos maps the position of the parameter to the position
2279 * of the corresponding t dimension.
2281 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
2283 int n;
2284 int nparam;
2285 int n_in;
2286 isl_space *dim;
2287 isl_map *map;
2288 std::map<int,int> param2pos;
2290 if (!expr)
2291 return expr;
2293 for (int i = 0; i < expr->n_arg; ++i) {
2294 expr->args[i] = resolve_nested(expr->args[i]);
2295 if (!expr->args[i]) {
2296 pet_expr_free(expr);
2297 return NULL;
2301 if (expr->type != pet_expr_access)
2302 return expr;
2304 n = n_nested_parameter(expr->acc.access);
2305 if (n == 0)
2306 return expr;
2308 expr = extract_nested(expr, n, param2pos);
2309 if (!expr)
2310 return NULL;
2312 n = expr->n_arg;
2313 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
2314 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
2315 dim = isl_map_get_space(expr->acc.access);
2316 dim = isl_space_domain(dim);
2317 dim = isl_space_from_domain(dim);
2318 dim = isl_space_add_dims(dim, isl_dim_out, n);
2319 map = isl_map_universe(dim);
2320 map = isl_map_domain_map(map);
2321 map = isl_map_reverse(map);
2322 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
2324 for (int i = nparam - 1; i >= 0; --i) {
2325 isl_id *id = isl_map_get_dim_id(expr->acc.access,
2326 isl_dim_param, i);
2327 if (!is_nested_parameter(id)) {
2328 isl_id_free(id);
2329 continue;
2332 expr->acc.access = isl_map_equate(expr->acc.access,
2333 isl_dim_param, i, isl_dim_in,
2334 n_in + param2pos[i]);
2335 expr->acc.access = isl_map_project_out(expr->acc.access,
2336 isl_dim_param, i, 1);
2338 isl_id_free(id);
2341 return expr;
2342 error:
2343 pet_expr_free(expr);
2344 return NULL;
2347 /* Convert a top-level pet_expr to a pet_scop with one statement.
2348 * This mainly involves resolving nested expression parameters
2349 * and setting the name of the iteration space.
2350 * The name is given by "label" if it is non-NULL. Otherwise,
2351 * it is of the form S_<n_stmt>.
2353 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
2354 __isl_take isl_id *label)
2356 struct pet_stmt *ps;
2357 SourceLocation loc = stmt->getLocStart();
2358 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2360 expr = resolve_nested(expr);
2361 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
2362 return pet_scop_from_pet_stmt(ctx, ps);
2365 /* Check if we can extract an affine expression from "expr".
2366 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2367 * We turn on autodetection so that we won't generate any warnings
2368 * and turn off nesting, so that we won't accept any non-affine constructs.
2370 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
2372 isl_pw_aff *pwaff;
2373 int save_autodetect = autodetect;
2374 bool save_nesting = nesting_enabled;
2376 autodetect = 1;
2377 nesting_enabled = false;
2379 pwaff = extract_affine(expr);
2381 autodetect = save_autodetect;
2382 nesting_enabled = save_nesting;
2384 return pwaff;
2387 /* Check whether "expr" is an affine expression.
2389 bool PetScan::is_affine(Expr *expr)
2391 isl_pw_aff *pwaff;
2393 pwaff = try_extract_affine(expr);
2394 isl_pw_aff_free(pwaff);
2396 return pwaff != NULL;
2399 /* Check whether "expr" is an affine constraint.
2400 * We turn on autodetection so that we won't generate any warnings
2401 * and turn off nesting, so that we won't accept any non-affine constructs.
2403 bool PetScan::is_affine_condition(Expr *expr)
2405 isl_set *set;
2406 int save_autodetect = autodetect;
2407 bool save_nesting = nesting_enabled;
2409 autodetect = 1;
2410 nesting_enabled = false;
2412 set = extract_condition(expr);
2413 isl_set_free(set);
2415 autodetect = save_autodetect;
2416 nesting_enabled = save_nesting;
2418 return set != NULL;
2421 /* Check if we can extract a condition from "expr".
2422 * Return the condition as an isl_set if we can and NULL otherwise.
2423 * If allow_nested is set, then the condition may involve parameters
2424 * corresponding to nested accesses.
2425 * We turn on autodetection so that we won't generate any warnings.
2427 __isl_give isl_set *PetScan::try_extract_nested_condition(Expr *expr)
2429 isl_set *set;
2430 int save_autodetect = autodetect;
2431 bool save_nesting = nesting_enabled;
2433 autodetect = 1;
2434 nesting_enabled = allow_nested;
2435 set = extract_condition(expr);
2437 autodetect = save_autodetect;
2438 nesting_enabled = save_nesting;
2440 return set;
2443 /* If the top-level expression of "stmt" is an assignment, then
2444 * return that assignment as a BinaryOperator.
2445 * Otherwise return NULL.
2447 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
2449 BinaryOperator *ass;
2451 if (!stmt)
2452 return NULL;
2453 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
2454 return NULL;
2456 ass = cast<BinaryOperator>(stmt);
2457 if(ass->getOpcode() != BO_Assign)
2458 return NULL;
2460 return ass;
2463 /* Check if the given if statement is a conditional assignement
2464 * with a non-affine condition. If so, construct a pet_scop
2465 * corresponding to this conditional assignment. Otherwise return NULL.
2467 * In particular we check if "stmt" is of the form
2469 * if (condition)
2470 * a = f(...);
2471 * else
2472 * a = g(...);
2474 * where a is some array or scalar access.
2475 * The constructed pet_scop then corresponds to the expression
2477 * a = condition ? f(...) : g(...)
2479 * All access relations in f(...) are intersected with condition
2480 * while all access relation in g(...) are intersected with the complement.
2482 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
2484 BinaryOperator *ass_then, *ass_else;
2485 isl_map *write_then, *write_else;
2486 isl_set *cond, *comp;
2487 isl_map *map, *map_true, *map_false;
2488 int equal;
2489 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
2490 bool save_nesting = nesting_enabled;
2492 ass_then = top_assignment_or_null(stmt->getThen());
2493 ass_else = top_assignment_or_null(stmt->getElse());
2495 if (!ass_then || !ass_else)
2496 return NULL;
2498 if (is_affine_condition(stmt->getCond()))
2499 return NULL;
2501 write_then = extract_access(ass_then->getLHS());
2502 write_else = extract_access(ass_else->getLHS());
2504 equal = isl_map_is_equal(write_then, write_else);
2505 isl_map_free(write_else);
2506 if (equal < 0 || !equal) {
2507 isl_map_free(write_then);
2508 return NULL;
2511 nesting_enabled = allow_nested;
2512 cond = extract_condition(stmt->getCond());
2513 nesting_enabled = save_nesting;
2514 comp = isl_set_complement(isl_set_copy(cond));
2515 map_true = isl_map_from_domain(isl_set_from_params(isl_set_copy(cond)));
2516 map_true = isl_map_add_dims(map_true, isl_dim_out, 1);
2517 map_true = isl_map_fix_si(map_true, isl_dim_out, 0, 1);
2518 map_false = isl_map_from_domain(isl_set_from_params(isl_set_copy(comp)));
2519 map_false = isl_map_add_dims(map_false, isl_dim_out, 1);
2520 map_false = isl_map_fix_si(map_false, isl_dim_out, 0, 0);
2521 map = isl_map_union_disjoint(map_true, map_false);
2523 pe_cond = pet_expr_from_access(map);
2525 pe_then = extract_expr(ass_then->getRHS());
2526 pe_then = pet_expr_restrict(pe_then, cond);
2527 pe_else = extract_expr(ass_else->getRHS());
2528 pe_else = pet_expr_restrict(pe_else, comp);
2530 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
2531 pe_write = pet_expr_from_access(write_then);
2532 if (pe_write) {
2533 pe_write->acc.write = 1;
2534 pe_write->acc.read = 0;
2536 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
2537 return extract(stmt, pe);
2540 /* Create an access to a virtual array representing the result
2541 * of a condition.
2542 * Unlike other accessed data, the id of the array is NULL as
2543 * there is no ValueDecl in the program corresponding to the virtual
2544 * array.
2545 * The array starts out as a scalar, but grows along with the
2546 * statement writing to the array in pet_scop_embed.
2548 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2550 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2551 isl_id *id;
2552 char name[50];
2554 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2555 id = isl_id_alloc(ctx, name, NULL);
2556 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2557 return isl_map_universe(dim);
2560 /* Create a pet_scop with a single statement evaluating "cond"
2561 * and writing the result to a virtual scalar, as expressed by
2562 * "access".
2564 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
2565 __isl_take isl_map *access)
2567 struct pet_expr *expr, *write;
2568 struct pet_stmt *ps;
2569 SourceLocation loc = cond->getLocStart();
2570 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2572 write = pet_expr_from_access(access);
2573 if (write) {
2574 write->acc.write = 1;
2575 write->acc.read = 0;
2577 expr = extract_expr(cond);
2578 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
2579 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
2580 return pet_scop_from_pet_stmt(ctx, ps);
2583 /* Add an array with the given extent ("access") to the list
2584 * of arrays in "scop" and return the extended pet_scop.
2585 * The array is marked as attaining values 0 and 1 only.
2587 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2588 __isl_keep isl_map *access, clang::ASTContext &ast_ctx)
2590 isl_ctx *ctx = isl_map_get_ctx(access);
2591 isl_space *dim;
2592 struct pet_array **arrays;
2593 struct pet_array *array;
2595 if (!scop)
2596 return NULL;
2597 if (!ctx)
2598 goto error;
2600 arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2601 scop->n_array + 1);
2602 if (!arrays)
2603 goto error;
2604 scop->arrays = arrays;
2606 array = isl_calloc_type(ctx, struct pet_array);
2607 if (!array)
2608 goto error;
2610 array->extent = isl_map_range(isl_map_copy(access));
2611 dim = isl_space_params_alloc(ctx, 0);
2612 array->context = isl_set_universe(dim);
2613 dim = isl_space_set_alloc(ctx, 0, 1);
2614 array->value_bounds = isl_set_universe(dim);
2615 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2616 isl_dim_set, 0, 0);
2617 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2618 isl_dim_set, 0, 1);
2619 array->element_type = strdup("int");
2620 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2622 scop->arrays[scop->n_array] = array;
2623 scop->n_array++;
2625 if (!array->extent || !array->context)
2626 goto error;
2628 return scop;
2629 error:
2630 pet_scop_free(scop);
2631 return NULL;
2634 extern "C" {
2635 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
2636 void *user);
2639 /* Apply the map pointed to by "user" to the domain of the access
2640 * relation, thereby embedding it in the range of the map.
2641 * The domain of both relations is the zero-dimensional domain.
2643 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
2645 isl_map *map = (isl_map *) user;
2647 return isl_map_apply_domain(access, isl_map_copy(map));
2650 /* Apply "map" to all access relations in "expr".
2652 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
2654 return pet_expr_foreach_access(expr, &embed_access, map);
2657 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2659 static int n_nested_parameter(__isl_keep isl_set *set)
2661 isl_space *space;
2662 int n;
2664 space = isl_set_get_space(set);
2665 n = n_nested_parameter(space);
2666 isl_space_free(space);
2668 return n;
2671 /* Remove all parameters from "map" that refer to nested accesses.
2673 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
2675 int nparam;
2676 isl_space *space;
2678 space = isl_map_get_space(map);
2679 nparam = isl_space_dim(space, isl_dim_param);
2680 for (int i = nparam - 1; i >= 0; --i)
2681 if (is_nested_parameter(space, i))
2682 map = isl_map_project_out(map, isl_dim_param, i, 1);
2683 isl_space_free(space);
2685 return map;
2688 extern "C" {
2689 static __isl_give isl_map *access_remove_nested_parameters(
2690 __isl_take isl_map *access, void *user);
2693 static __isl_give isl_map *access_remove_nested_parameters(
2694 __isl_take isl_map *access, void *user)
2696 return remove_nested_parameters(access);
2699 /* Remove all nested access parameters from the schedule and all
2700 * accesses of "stmt".
2701 * There is no need to remove them from the domain as these parameters
2702 * have already been removed from the domain when this function is called.
2704 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
2706 if (!stmt)
2707 return NULL;
2708 stmt->schedule = remove_nested_parameters(stmt->schedule);
2709 stmt->body = pet_expr_foreach_access(stmt->body,
2710 &access_remove_nested_parameters, NULL);
2711 if (!stmt->schedule || !stmt->body)
2712 goto error;
2713 for (int i = 0; i < stmt->n_arg; ++i) {
2714 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
2715 &access_remove_nested_parameters, NULL);
2716 if (!stmt->args[i])
2717 goto error;
2720 return stmt;
2721 error:
2722 pet_stmt_free(stmt);
2723 return NULL;
2726 /* For each nested access parameter in the domain of "stmt",
2727 * construct a corresponding pet_expr, place it in stmt->args and
2728 * record its position in "param2pos".
2729 * n is the number of nested access parameters.
2731 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
2732 std::map<int,int> &param2pos)
2734 isl_space *space;
2735 unsigned n_arg;
2736 struct pet_expr **args;
2738 n_arg = stmt->n_arg;
2739 args = isl_realloc_array(ctx, stmt->args, struct pet_expr *, n_arg + n);
2740 if (!args)
2741 goto error;
2742 stmt->args = args;
2743 stmt->n_arg += n;
2745 space = isl_set_get_space(stmt->domain);
2746 n = extract_nested(space, n_arg, stmt->args, param2pos);
2747 isl_space_free(space);
2749 if (n < 0)
2750 goto error;
2752 stmt->n_arg = n;
2753 return stmt;
2754 error:
2755 pet_stmt_free(stmt);
2756 return NULL;
2759 /* Look for parameters in the iteration domain of "stmt" that
2760 * refer to nested accesses. In particular, these are
2761 * parameters with no name.
2763 * If there are any such parameters, then as many extra variables
2764 * (after identifying identical nested accesses) are added to the
2765 * range of the map wrapped inside the domain.
2766 * If the original domain is not a wrapped map, then a new wrapped
2767 * map is created with zero output dimensions.
2768 * The parameters are then equated to the corresponding output dimensions
2769 * and subsequently projected out, from the iteration domain,
2770 * the schedule and the access relations.
2771 * For each of the output dimensions, a corresponding argument
2772 * expression is added. Initially they are created with
2773 * a zero-dimensional domain, so they have to be embedded
2774 * in the current iteration domain.
2775 * param2pos maps the position of the parameter to the position
2776 * of the corresponding output dimension in the wrapped map.
2778 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
2780 int n;
2781 int nparam;
2782 unsigned n_arg;
2783 isl_map *map;
2784 std::map<int,int> param2pos;
2786 if (!stmt)
2787 return NULL;
2789 n = n_nested_parameter(stmt->domain);
2790 if (n == 0)
2791 return stmt;
2793 n_arg = stmt->n_arg;
2794 stmt = extract_nested(stmt, n, param2pos);
2795 if (!stmt)
2796 return NULL;
2798 n = stmt->n_arg - n_arg;
2799 nparam = isl_set_dim(stmt->domain, isl_dim_param);
2800 if (isl_set_is_wrapping(stmt->domain))
2801 map = isl_set_unwrap(stmt->domain);
2802 else
2803 map = isl_map_from_domain(stmt->domain);
2804 map = isl_map_add_dims(map, isl_dim_out, n);
2806 for (int i = nparam - 1; i >= 0; --i) {
2807 isl_id *id;
2809 if (!is_nested_parameter(map, i))
2810 continue;
2812 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
2813 isl_dim_out);
2814 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
2815 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
2816 param2pos[i]);
2817 map = isl_map_project_out(map, isl_dim_param, i, 1);
2820 stmt->domain = isl_map_wrap(map);
2822 map = isl_set_unwrap(isl_set_copy(stmt->domain));
2823 map = isl_map_from_range(isl_map_domain(map));
2824 for (int pos = n_arg; pos < stmt->n_arg; ++pos)
2825 stmt->args[pos] = embed(stmt->args[pos], map);
2826 isl_map_free(map);
2828 stmt = remove_nested_parameters(stmt);
2830 return stmt;
2831 error:
2832 pet_stmt_free(stmt);
2833 return NULL;
2836 /* For each statement in "scop", move the parameters that correspond
2837 * to nested access into the ranges of the domains and create
2838 * corresponding argument expressions.
2840 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
2842 if (!scop)
2843 return NULL;
2845 for (int i = 0; i < scop->n_stmt; ++i) {
2846 scop->stmts[i] = resolve_nested(scop->stmts[i]);
2847 if (!scop->stmts[i])
2848 goto error;
2851 return scop;
2852 error:
2853 pet_scop_free(scop);
2854 return NULL;
2857 /* Does "space" involve any parameters that refer to nested
2858 * accesses, i.e., parameters with no name?
2860 static bool has_nested(__isl_keep isl_space *space)
2862 int nparam;
2864 nparam = isl_space_dim(space, isl_dim_param);
2865 for (int i = 0; i < nparam; ++i)
2866 if (is_nested_parameter(space, i))
2867 return true;
2869 return false;
2872 /* Does "set" involve any parameters that refer to nested
2873 * accesses, i.e., parameters with no name?
2875 static bool has_nested(__isl_keep isl_set *set)
2877 isl_space *space;
2878 bool nested;
2880 space = isl_set_get_space(set);
2881 nested = has_nested(space);
2882 isl_space_free(space);
2884 return nested;
2887 /* Given an access expression "expr", is the variable accessed by
2888 * "expr" assigned anywhere inside "scop"?
2890 static bool is_assigned(pet_expr *expr, pet_scop *scop)
2892 bool assigned = false;
2893 isl_id *id;
2895 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
2896 assigned = pet_scop_writes(scop, id);
2897 isl_id_free(id);
2899 return assigned;
2902 /* Are all nested access parameters in "set" allowed given "scop".
2903 * In particular, is none of them written by anywhere inside "scop".
2905 bool PetScan::is_nested_allowed(__isl_keep isl_set *set, pet_scop *scop)
2907 int nparam;
2909 nparam = isl_set_dim(set, isl_dim_param);
2910 for (int i = 0; i < nparam; ++i) {
2911 Expr *nested;
2912 isl_id *id = isl_set_get_dim_id(set, isl_dim_param, i);
2913 pet_expr *expr;
2914 bool allowed;
2916 if (!is_nested_parameter(id)) {
2917 isl_id_free(id);
2918 continue;
2921 nested = (Expr *) isl_id_get_user(id);
2922 expr = extract_expr(nested);
2923 allowed = expr && expr->type == pet_expr_access &&
2924 !is_assigned(expr, scop);
2926 pet_expr_free(expr);
2927 isl_id_free(id);
2929 if (!allowed)
2930 return false;
2933 return true;
2936 /* Construct a pet_scop for an if statement.
2938 * If the condition fits the pattern of a conditional assignment,
2939 * then it is handled by extract_conditional_assignment.
2940 * Otherwise, we do the following.
2942 * If the condition is affine, then the condition is added
2943 * to the iteration domains of the then branch, while the
2944 * opposite of the condition in added to the iteration domains
2945 * of the else branch, if any.
2946 * We allow the condition to be dynamic, i.e., to refer to
2947 * scalars or array elements that may be written to outside
2948 * of the given if statement. These nested accesses are then represented
2949 * as output dimensions in the wrapping iteration domain.
2950 * If it also written _inside_ the then or else branch, then
2951 * we treat the condition as non-affine.
2952 * As explained below, this will introduce an extra statement.
2953 * For aesthetic reasons, we want this statement to have a statement
2954 * number that is lower than those of the then and else branches.
2955 * In order to evaluate if will need such a statement, however, we
2956 * first construct scops for the then and else branches.
2957 * We therefore reserve a statement number if we might have to
2958 * introduce such an extra statement.
2960 * If the condition is not affine, then we create a separate
2961 * statement that writes the result of the condition to a virtual scalar.
2962 * A constraint requiring the value of this virtual scalar to be one
2963 * is added to the iteration domains of the then branch.
2964 * Similarly, a constraint requiring the value of this virtual scalar
2965 * to be zero is added to the iteration domains of the else branch, if any.
2966 * We adjust the schedules to ensure that the virtual scalar is written
2967 * before it is read.
2969 struct pet_scop *PetScan::extract(IfStmt *stmt)
2971 struct pet_scop *scop_then, *scop_else, *scop;
2972 assigned_value_cache cache(assigned_value);
2973 isl_map *test_access = NULL;
2974 isl_set *cond;
2975 int stmt_id;
2977 scop = extract_conditional_assignment(stmt);
2978 if (scop)
2979 return scop;
2981 cond = try_extract_nested_condition(stmt->getCond());
2982 if (allow_nested && (!cond || has_nested(cond)))
2983 stmt_id = n_stmt++;
2985 scop_then = extract(stmt->getThen());
2987 if (stmt->getElse()) {
2988 scop_else = extract(stmt->getElse());
2989 if (autodetect) {
2990 if (scop_then && !scop_else) {
2991 partial = true;
2992 isl_set_free(cond);
2993 return scop_then;
2995 if (!scop_then && scop_else) {
2996 partial = true;
2997 isl_set_free(cond);
2998 return scop_else;
3003 if (cond &&
3004 (!is_nested_allowed(cond, scop_then) ||
3005 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
3006 isl_set_free(cond);
3007 cond = NULL;
3009 if (allow_nested && !cond) {
3010 int save_n_stmt = n_stmt;
3011 test_access = create_test_access(ctx, n_test++);
3012 n_stmt = stmt_id;
3013 scop = extract_non_affine_condition(stmt->getCond(),
3014 isl_map_copy(test_access));
3015 n_stmt = save_n_stmt;
3016 scop = scop_add_array(scop, test_access, ast_context);
3017 if (!scop) {
3018 pet_scop_free(scop_then);
3019 pet_scop_free(scop_else);
3020 isl_map_free(test_access);
3021 return NULL;
3025 if (!scop) {
3026 if (!cond)
3027 cond = extract_condition(stmt->getCond());
3028 scop = pet_scop_restrict(scop_then, isl_set_copy(cond));
3030 if (stmt->getElse()) {
3031 cond = isl_set_complement(cond);
3032 scop_else = pet_scop_restrict(scop_else, cond);
3033 scop = pet_scop_add(ctx, scop, scop_else);
3034 } else
3035 isl_set_free(cond);
3036 scop = resolve_nested(scop);
3037 } else {
3038 scop = pet_scop_prefix(scop, 0);
3039 scop_then = pet_scop_prefix(scop_then, 1);
3040 scop_then = pet_scop_filter(scop_then,
3041 isl_map_copy(test_access), 1);
3042 scop = pet_scop_add(ctx, scop, scop_then);
3043 if (stmt->getElse()) {
3044 scop_else = pet_scop_prefix(scop_else, 1);
3045 scop_else = pet_scop_filter(scop_else, test_access, 0);
3046 scop = pet_scop_add(ctx, scop, scop_else);
3047 } else
3048 isl_map_free(test_access);
3051 return scop;
3054 /* Try and construct a pet_scop for a label statement.
3055 * We currently only allow labels on expression statements.
3057 struct pet_scop *PetScan::extract(LabelStmt *stmt)
3059 isl_id *label;
3060 Stmt *sub;
3062 sub = stmt->getSubStmt();
3063 if (!isa<Expr>(sub)) {
3064 unsupported(stmt);
3065 return NULL;
3068 label = isl_id_alloc(ctx, stmt->getName(), NULL);
3070 return extract(sub, extract_expr(cast<Expr>(sub)), label);
3073 /* Try and construct a pet_scop corresponding to "stmt".
3075 struct pet_scop *PetScan::extract(Stmt *stmt)
3077 if (isa<Expr>(stmt))
3078 return extract(stmt, extract_expr(cast<Expr>(stmt)));
3080 switch (stmt->getStmtClass()) {
3081 case Stmt::WhileStmtClass:
3082 return extract(cast<WhileStmt>(stmt));
3083 case Stmt::ForStmtClass:
3084 return extract_for(cast<ForStmt>(stmt));
3085 case Stmt::IfStmtClass:
3086 return extract(cast<IfStmt>(stmt));
3087 case Stmt::CompoundStmtClass:
3088 return extract(cast<CompoundStmt>(stmt));
3089 case Stmt::LabelStmtClass:
3090 return extract(cast<LabelStmt>(stmt));
3091 default:
3092 unsupported(stmt);
3095 return NULL;
3098 /* Try and construct a pet_scop corresponding to (part of)
3099 * a sequence of statements.
3101 struct pet_scop *PetScan::extract(StmtRange stmt_range)
3103 pet_scop *scop;
3104 StmtIterator i;
3105 int j;
3106 bool partial_range = false;
3108 scop = pet_scop_empty(ctx);
3109 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
3110 Stmt *child = *i;
3111 struct pet_scop *scop_i;
3112 scop_i = extract(child);
3113 if (scop && partial) {
3114 pet_scop_free(scop_i);
3115 break;
3117 scop_i = pet_scop_prefix(scop_i, j);
3118 if (autodetect) {
3119 if (scop_i)
3120 scop = pet_scop_add(ctx, scop, scop_i);
3121 else
3122 partial_range = true;
3123 if (scop->n_stmt != 0 && !scop_i)
3124 partial = true;
3125 } else {
3126 scop = pet_scop_add(ctx, scop, scop_i);
3128 if (partial)
3129 break;
3132 if (scop && partial_range)
3133 partial = true;
3135 return scop;
3138 /* Check if the scop marked by the user is exactly this Stmt
3139 * or part of this Stmt.
3140 * If so, return a pet_scop corresponding to the marked region.
3141 * Otherwise, return NULL.
3143 struct pet_scop *PetScan::scan(Stmt *stmt)
3145 SourceManager &SM = PP.getSourceManager();
3146 unsigned start_off, end_off;
3148 start_off = SM.getFileOffset(stmt->getLocStart());
3149 end_off = SM.getFileOffset(stmt->getLocEnd());
3151 if (start_off > loc.end)
3152 return NULL;
3153 if (end_off < loc.start)
3154 return NULL;
3155 if (start_off >= loc.start && end_off <= loc.end) {
3156 return extract(stmt);
3159 StmtIterator start;
3160 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
3161 Stmt *child = *start;
3162 if (!child)
3163 continue;
3164 start_off = SM.getFileOffset(child->getLocStart());
3165 end_off = SM.getFileOffset(child->getLocEnd());
3166 if (start_off < loc.start && end_off > loc.end)
3167 return scan(child);
3168 if (start_off >= loc.start)
3169 break;
3172 StmtIterator end;
3173 for (end = start; end != stmt->child_end(); ++end) {
3174 Stmt *child = *end;
3175 start_off = SM.getFileOffset(child->getLocStart());
3176 if (start_off >= loc.end)
3177 break;
3180 return extract(StmtRange(start, end));
3183 /* Set the size of index "pos" of "array" to "size".
3184 * In particular, add a constraint of the form
3186 * i_pos < size
3188 * to array->extent and a constraint of the form
3190 * size >= 0
3192 * to array->context.
3194 static struct pet_array *update_size(struct pet_array *array, int pos,
3195 __isl_take isl_pw_aff *size)
3197 isl_set *valid;
3198 isl_set *univ;
3199 isl_set *bound;
3200 isl_space *dim;
3201 isl_aff *aff;
3202 isl_pw_aff *index;
3203 isl_id *id;
3205 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
3206 array->context = isl_set_intersect(array->context, valid);
3208 dim = isl_set_get_space(array->extent);
3209 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
3210 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
3211 univ = isl_set_universe(isl_aff_get_domain_space(aff));
3212 index = isl_pw_aff_alloc(univ, aff);
3214 size = isl_pw_aff_add_dims(size, isl_dim_in,
3215 isl_set_dim(array->extent, isl_dim_set));
3216 id = isl_set_get_tuple_id(array->extent);
3217 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
3218 bound = isl_pw_aff_lt_set(index, size);
3220 array->extent = isl_set_intersect(array->extent, bound);
3222 if (!array->context || !array->extent)
3223 goto error;
3225 return array;
3226 error:
3227 pet_array_free(array);
3228 return NULL;
3231 /* Figure out the size of the array at position "pos" and all
3232 * subsequent positions from "type" and update "array" accordingly.
3234 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
3235 const Type *type, int pos)
3237 const ArrayType *atype;
3238 isl_pw_aff *size;
3240 if (!array)
3241 return NULL;
3243 if (type->isPointerType()) {
3244 type = type->getPointeeType().getTypePtr();
3245 return set_upper_bounds(array, type, pos + 1);
3247 if (!type->isArrayType())
3248 return array;
3250 type = type->getCanonicalTypeInternal().getTypePtr();
3251 atype = cast<ArrayType>(type);
3253 if (type->isConstantArrayType()) {
3254 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
3255 size = extract_affine(ca->getSize());
3256 array = update_size(array, pos, size);
3257 } else if (type->isVariableArrayType()) {
3258 const VariableArrayType *vla = cast<VariableArrayType>(atype);
3259 size = extract_affine(vla->getSizeExpr());
3260 array = update_size(array, pos, size);
3263 type = atype->getElementType().getTypePtr();
3265 return set_upper_bounds(array, type, pos + 1);
3268 /* Construct and return a pet_array corresponding to the variable "decl".
3269 * In particular, initialize array->extent to
3271 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3273 * and then call set_upper_bounds to set the upper bounds on the indices
3274 * based on the type of the variable.
3276 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
3278 struct pet_array *array;
3279 QualType qt = decl->getType();
3280 const Type *type = qt.getTypePtr();
3281 int depth = array_depth(type);
3282 QualType base = base_type(qt);
3283 string name;
3284 isl_id *id;
3285 isl_space *dim;
3287 array = isl_calloc_type(ctx, struct pet_array);
3288 if (!array)
3289 return NULL;
3291 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
3292 dim = isl_space_set_alloc(ctx, 0, depth);
3293 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
3295 array->extent = isl_set_nat_universe(dim);
3297 dim = isl_space_params_alloc(ctx, 0);
3298 array->context = isl_set_universe(dim);
3300 array = set_upper_bounds(array, type, 0);
3301 if (!array)
3302 return NULL;
3304 name = base.getAsString();
3305 array->element_type = strdup(name.c_str());
3306 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
3308 return array;
3311 /* Construct a list of pet_arrays, one for each array (or scalar)
3312 * accessed inside "scop" add this list to "scop" and return the result.
3314 * The context of "scop" is updated with the intesection of
3315 * the contexts of all arrays, i.e., constraints on the parameters
3316 * that ensure that the arrays have a valid (non-negative) size.
3318 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
3320 int i;
3321 set<ValueDecl *> arrays;
3322 set<ValueDecl *>::iterator it;
3323 int n_array;
3324 struct pet_array **scop_arrays;
3326 if (!scop)
3327 return NULL;
3329 pet_scop_collect_arrays(scop, arrays);
3330 if (arrays.size() == 0)
3331 return scop;
3333 n_array = scop->n_array;
3335 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3336 n_array + arrays.size());
3337 if (!scop_arrays)
3338 goto error;
3339 scop->arrays = scop_arrays;
3341 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3342 struct pet_array *array;
3343 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
3344 if (!scop->arrays[n_array + i])
3345 goto error;
3346 scop->n_array++;
3347 scop->context = isl_set_intersect(scop->context,
3348 isl_set_copy(array->context));
3349 if (!scop->context)
3350 goto error;
3353 return scop;
3354 error:
3355 pet_scop_free(scop);
3356 return NULL;
3359 /* Construct a pet_scop from the given function.
3361 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3363 pet_scop *scop;
3364 Stmt *stmt;
3366 stmt = fd->getBody();
3368 if (autodetect)
3369 scop = extract(stmt);
3370 else
3371 scop = scan(stmt);
3372 scop = pet_scop_detect_parameter_accesses(scop);
3373 scop = scan_arrays(scop);
3374 scop = pet_scop_gist(scop, value_bounds);
3376 return scop;