cache values in assigned_value instead of expressions
[pet.git] / scan.cc
blobe9043b6257a8820bce7e8645a454f233e91ee989
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;
56 /* Check if the element type corresponding to the given array type
57 * has a const qualifier.
59 static bool const_base(QualType qt)
61 const Type *type = qt.getTypePtr();
63 if (type->isPointerType())
64 return const_base(type->getPointeeType());
65 if (type->isArrayType()) {
66 const ArrayType *atype;
67 type = type->getCanonicalTypeInternal().getTypePtr();
68 atype = cast<ArrayType>(type);
69 return const_base(atype->getElementType());
72 return qt.isConstQualified();
75 /* Mark "decl" as having an unknown value in "assigned_value".
77 * If no (known or unknown) value was assigned to "decl" before,
78 * then it may have been treated as a parameter before and may
79 * therefore appear in a value assigned to another variable.
80 * If so, this assignment needs to be turned into an unknown value too.
82 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
83 ValueDecl *decl)
85 map<ValueDecl *, isl_pw_aff *>::iterator it;
87 it = assigned_value.find(decl);
89 assigned_value[decl] = NULL;
91 if (it == assigned_value.end())
92 return;
94 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
95 isl_pw_aff *pa = it->second;
96 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
98 for (int i = 0; i < nparam; ++i) {
99 isl_id *id;
101 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
102 continue;
103 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
104 if (isl_id_get_user(id) == decl)
105 it->second = NULL;
106 isl_id_free(id);
111 /* Look for any assignments to scalar variables in part of the parse
112 * tree and set assigned_value to NULL for each of them.
113 * Also reset assigned_value if the address of a scalar variable
114 * is being taken. As an exception, if the address is passed to a function
115 * that is declared to receive a const pointer, then assigned_value is
116 * not reset.
118 * This ensures that we won't use any previously stored value
119 * in the current subtree and its parents.
121 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
122 map<ValueDecl *, isl_pw_aff *> &assigned_value;
123 set<UnaryOperator *> skip;
125 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
126 assigned_value(assigned_value) {}
128 /* Check for "address of" operators whose value is passed
129 * to a const pointer argument and add them to "skip", so that
130 * we can skip them in VisitUnaryOperator.
132 bool VisitCallExpr(CallExpr *expr) {
133 FunctionDecl *fd;
134 fd = expr->getDirectCallee();
135 if (!fd)
136 return true;
137 for (int i = 0; i < expr->getNumArgs(); ++i) {
138 Expr *arg = expr->getArg(i);
139 UnaryOperator *op;
140 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
141 ImplicitCastExpr *ice;
142 ice = cast<ImplicitCastExpr>(arg);
143 arg = ice->getSubExpr();
145 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
146 continue;
147 op = cast<UnaryOperator>(arg);
148 if (op->getOpcode() != UO_AddrOf)
149 continue;
150 if (const_base(fd->getParamDecl(i)->getType()))
151 skip.insert(op);
153 return true;
156 bool VisitUnaryOperator(UnaryOperator *expr) {
157 Expr *arg;
158 DeclRefExpr *ref;
159 ValueDecl *decl;
161 if (expr->getOpcode() != UO_AddrOf)
162 return true;
163 if (skip.find(expr) != skip.end())
164 return true;
166 arg = expr->getSubExpr();
167 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
168 return true;
169 ref = cast<DeclRefExpr>(arg);
170 decl = ref->getDecl();
171 clear_assignment(assigned_value, decl);
172 return true;
175 bool VisitBinaryOperator(BinaryOperator *expr) {
176 Expr *lhs;
177 DeclRefExpr *ref;
178 ValueDecl *decl;
180 if (!expr->isAssignmentOp())
181 return true;
182 lhs = expr->getLHS();
183 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
184 return true;
185 ref = cast<DeclRefExpr>(lhs);
186 decl = ref->getDecl();
187 clear_assignment(assigned_value, decl);
188 return true;
192 /* Keep a copy of the currently assigned values.
194 * Any variable that is assigned a value inside the current scope
195 * is removed again when we leave the scope (either because it wasn't
196 * stored in the cache or because it has a different value in the cache).
198 struct assigned_value_cache {
199 map<ValueDecl *, isl_pw_aff *> &assigned_value;
200 map<ValueDecl *, isl_pw_aff *> cache;
202 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
203 assigned_value(assigned_value), cache(assigned_value) {}
204 ~assigned_value_cache() {
205 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
206 for (it = assigned_value.begin(); it != assigned_value.end();
207 ++it) {
208 if (!it->second ||
209 (cache.find(it->first) != cache.end() &&
210 cache[it->first] != it->second))
211 cache[it->first] = NULL;
213 assigned_value = cache;
217 /* Insert an expression into the collection of expressions,
218 * provided it is not already in there.
219 * The isl_pw_affs are freed in the destructor.
221 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
223 std::set<isl_pw_aff *>::iterator it;
225 if (expressions.find(expr) == expressions.end())
226 expressions.insert(expr);
227 else
228 isl_pw_aff_free(expr);
231 PetScan::~PetScan()
233 std::set<isl_pw_aff *>::iterator it;
235 for (it = expressions.begin(); it != expressions.end(); ++it)
236 isl_pw_aff_free(*it);
239 /* Called if we found something we (currently) cannot handle.
240 * We'll provide more informative warnings later.
242 * We only actually complain if autodetect is false.
244 void PetScan::unsupported(Stmt *stmt)
246 if (autodetect)
247 return;
249 SourceLocation loc = stmt->getLocStart();
250 DiagnosticsEngine &diag = PP.getDiagnostics();
251 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
252 "unsupported");
253 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
256 /* Extract an integer from "expr" and store it in "v".
258 int PetScan::extract_int(IntegerLiteral *expr, isl_int *v)
260 const Type *type = expr->getType().getTypePtr();
261 int is_signed = type->hasSignedIntegerRepresentation();
263 if (is_signed) {
264 int64_t i = expr->getValue().getSExtValue();
265 isl_int_set_si(*v, i);
266 } else {
267 uint64_t i = expr->getValue().getZExtValue();
268 isl_int_set_ui(*v, i);
271 return 0;
274 /* Extract an integer from "expr" and store it in "v".
275 * Return -1 if "expr" does not (obviously) represent an integer.
277 int PetScan::extract_int(clang::ParenExpr *expr, isl_int *v)
279 return extract_int(expr->getSubExpr(), v);
282 /* Extract an integer from "expr" and store it in "v".
283 * Return -1 if "expr" does not (obviously) represent an integer.
285 int PetScan::extract_int(clang::Expr *expr, isl_int *v)
287 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
288 return extract_int(cast<IntegerLiteral>(expr), v);
289 if (expr->getStmtClass() == Stmt::ParenExprClass)
290 return extract_int(cast<ParenExpr>(expr), v);
292 unsupported(expr);
293 return -1;
296 /* Extract an affine expression from the IntegerLiteral "expr".
298 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
300 isl_space *dim = isl_space_params_alloc(ctx, 0);
301 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
302 isl_aff *aff = isl_aff_zero_on_domain(ls);
303 isl_set *dom = isl_set_universe(dim);
304 isl_int v;
306 isl_int_init(v);
307 extract_int(expr, &v);
308 aff = isl_aff_add_constant(aff, v);
309 isl_int_clear(v);
311 return isl_pw_aff_alloc(dom, aff);
314 /* Extract an affine expression from the APInt "val".
316 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
318 isl_space *dim = isl_space_params_alloc(ctx, 0);
319 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
320 isl_aff *aff = isl_aff_zero_on_domain(ls);
321 isl_set *dom = isl_set_universe(dim);
322 isl_int v;
324 isl_int_init(v);
325 isl_int_set_ui(v, val.getZExtValue());
326 aff = isl_aff_add_constant(aff, v);
327 isl_int_clear(v);
329 return isl_pw_aff_alloc(dom, aff);
332 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
334 return extract_affine(expr->getSubExpr());
337 /* Extract an affine expression from the DeclRefExpr "expr".
339 * If the variable has been assigned a value, then we check whether
340 * we know what (affine) value was assigned.
341 * If so, we return this value. Otherwise we convert "expr"
342 * to an extra parameter (provided nesting_enabled is set).
344 * Otherwise, we simply return an expression that is equal
345 * to a parameter corresponding to the referenced variable.
347 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
349 ValueDecl *decl = expr->getDecl();
350 const Type *type = decl->getType().getTypePtr();
351 isl_id *id;
352 isl_space *dim;
353 isl_aff *aff;
354 isl_set *dom;
356 if (!type->isIntegerType()) {
357 unsupported(expr);
358 return NULL;
361 if (assigned_value.find(decl) != assigned_value.end()) {
362 if (assigned_value[decl])
363 return isl_pw_aff_copy(assigned_value[decl]);
364 else
365 return nested_access(expr);
368 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
369 dim = isl_space_params_alloc(ctx, 1);
371 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
373 dom = isl_set_universe(isl_space_copy(dim));
374 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
375 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
377 return isl_pw_aff_alloc(dom, aff);
380 /* Extract an affine expression from an integer division operation.
381 * In particular, if "expr" is lhs/rhs, then return
383 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
385 * The second argument (rhs) is required to be a (positive) integer constant.
387 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
389 Expr *rhs_expr;
390 isl_pw_aff *lhs, *lhs_f, *lhs_c;
391 isl_pw_aff *res;
392 isl_int v;
393 isl_set *cond;
395 rhs_expr = expr->getRHS();
396 isl_int_init(v);
397 if (extract_int(rhs_expr, &v) < 0) {
398 isl_int_clear(v);
399 return NULL;
402 lhs = extract_affine(expr->getLHS());
403 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
405 lhs = isl_pw_aff_scale_down(lhs, v);
406 isl_int_clear(v);
408 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(lhs));
409 lhs_c = isl_pw_aff_ceil(lhs);
410 res = isl_pw_aff_cond(cond, lhs_f, lhs_c);
412 return res;
415 /* Extract an affine expression from a modulo operation.
416 * In particular, if "expr" is lhs/rhs, then return
418 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
420 * The second argument (rhs) is required to be a (positive) integer constant.
422 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
424 Expr *rhs_expr;
425 isl_pw_aff *lhs, *lhs_f, *lhs_c;
426 isl_pw_aff *res;
427 isl_int v;
428 isl_set *cond;
430 rhs_expr = expr->getRHS();
431 if (rhs_expr->getStmtClass() != Stmt::IntegerLiteralClass) {
432 unsupported(expr);
433 return NULL;
436 lhs = extract_affine(expr->getLHS());
437 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
439 isl_int_init(v);
440 extract_int(cast<IntegerLiteral>(rhs_expr), &v);
441 res = isl_pw_aff_scale_down(isl_pw_aff_copy(lhs), v);
443 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(res));
444 lhs_c = isl_pw_aff_ceil(res);
445 res = isl_pw_aff_cond(cond, lhs_f, lhs_c);
447 res = isl_pw_aff_scale(res, v);
448 isl_int_clear(v);
450 res = isl_pw_aff_sub(lhs, res);
452 return res;
455 /* Extract an affine expression from a multiplication operation.
456 * This is only allowed if at least one of the two arguments
457 * is a (piecewise) constant.
459 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
461 isl_pw_aff *lhs;
462 isl_pw_aff *rhs;
464 lhs = extract_affine(expr->getLHS());
465 rhs = extract_affine(expr->getRHS());
467 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
468 isl_pw_aff_free(lhs);
469 isl_pw_aff_free(rhs);
470 unsupported(expr);
471 return NULL;
474 return isl_pw_aff_mul(lhs, rhs);
477 /* Extract an affine expression from an addition or subtraction operation.
479 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
481 isl_pw_aff *lhs;
482 isl_pw_aff *rhs;
484 lhs = extract_affine(expr->getLHS());
485 rhs = extract_affine(expr->getRHS());
487 switch (expr->getOpcode()) {
488 case BO_Add:
489 return isl_pw_aff_add(lhs, rhs);
490 case BO_Sub:
491 return isl_pw_aff_sub(lhs, rhs);
492 default:
493 isl_pw_aff_free(lhs);
494 isl_pw_aff_free(rhs);
495 return NULL;
500 /* Compute
502 * pwaff mod 2^width
504 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
505 unsigned width)
507 isl_int mod;
509 isl_int_init(mod);
510 isl_int_set_si(mod, 1);
511 isl_int_mul_2exp(mod, mod, width);
513 pwaff = isl_pw_aff_mod(pwaff, mod);
515 isl_int_clear(mod);
517 return pwaff;
520 /* Extract an affine expression from a boolean expression.
521 * In particular, return the expression "expr ? 1 : 0".
523 __isl_give isl_pw_aff *PetScan::extract_implicit_affine(Expr *expr)
525 isl_set *cond = extract_condition(expr);
526 isl_space *space = isl_set_get_space(cond);
527 isl_local_space *ls = isl_local_space_from_space(space);
528 isl_aff *zero = isl_aff_zero_on_domain(isl_local_space_copy(ls));
529 isl_aff *one = isl_aff_zero_on_domain(ls);
530 one = isl_aff_add_constant_si(one, 1);
531 return isl_pw_aff_cond(cond, isl_pw_aff_from_aff(one),
532 isl_pw_aff_from_aff(zero));
535 /* Extract an affine expression from some binary operations.
536 * If the result of the expression is unsigned, then we wrap it
537 * based on the size of the type.
539 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
541 isl_pw_aff *res;
543 switch (expr->getOpcode()) {
544 case BO_Add:
545 case BO_Sub:
546 res = extract_affine_add(expr);
547 break;
548 case BO_Div:
549 res = extract_affine_div(expr);
550 break;
551 case BO_Rem:
552 res = extract_affine_mod(expr);
553 break;
554 case BO_Mul:
555 res = extract_affine_mul(expr);
556 break;
557 case BO_LT:
558 case BO_LE:
559 case BO_GT:
560 case BO_GE:
561 case BO_EQ:
562 case BO_NE:
563 case BO_LAnd:
564 case BO_LOr:
565 res = extract_implicit_affine(expr);
566 break;
567 default:
568 unsupported(expr);
569 return NULL;
572 if (expr->getType()->isUnsignedIntegerType())
573 res = wrap(res, ast_context.getIntWidth(expr->getType()));
575 return res;
578 /* Extract an affine expression from a negation operation.
580 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
582 if (expr->getOpcode() == UO_Minus)
583 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
584 if (expr->getOpcode() == UO_LNot)
585 return extract_implicit_affine(expr);
587 unsupported(expr);
588 return NULL;
591 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
593 return extract_affine(expr->getSubExpr());
596 /* Extract an affine expression from some special function calls.
597 * In particular, we handle "min", "max", "ceild" and "floord".
598 * In case of the latter two, the second argument needs to be
599 * a (positive) integer constant.
601 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
603 FunctionDecl *fd;
604 string name;
605 isl_pw_aff *aff1, *aff2;
607 fd = expr->getDirectCallee();
608 if (!fd) {
609 unsupported(expr);
610 return NULL;
613 name = fd->getDeclName().getAsString();
614 if (!(expr->getNumArgs() == 2 && name == "min") &&
615 !(expr->getNumArgs() == 2 && name == "max") &&
616 !(expr->getNumArgs() == 2 && name == "floord") &&
617 !(expr->getNumArgs() == 2 && name == "ceild")) {
618 unsupported(expr);
619 return NULL;
622 if (name == "min" || name == "max") {
623 aff1 = extract_affine(expr->getArg(0));
624 aff2 = extract_affine(expr->getArg(1));
626 if (name == "min")
627 aff1 = isl_pw_aff_min(aff1, aff2);
628 else
629 aff1 = isl_pw_aff_max(aff1, aff2);
630 } else if (name == "floord" || name == "ceild") {
631 isl_int v;
632 Expr *arg2 = expr->getArg(1);
634 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
635 unsupported(expr);
636 return NULL;
638 aff1 = extract_affine(expr->getArg(0));
639 isl_int_init(v);
640 extract_int(cast<IntegerLiteral>(arg2), &v);
641 aff1 = isl_pw_aff_scale_down(aff1, v);
642 isl_int_clear(v);
643 if (name == "floord")
644 aff1 = isl_pw_aff_floor(aff1);
645 else
646 aff1 = isl_pw_aff_ceil(aff1);
647 } else {
648 unsupported(expr);
649 return NULL;
652 return aff1;
656 /* This method is called when we come across an access that is
657 * nested in what is supposed to be an affine expression.
658 * If nesting is allowed, we return a new parameter that corresponds
659 * to this nested access. Otherwise, we simply complain.
661 * The new parameter is resolved in resolve_nested.
663 isl_pw_aff *PetScan::nested_access(Expr *expr)
665 isl_id *id;
666 isl_space *dim;
667 isl_aff *aff;
668 isl_set *dom;
670 if (!nesting_enabled) {
671 unsupported(expr);
672 return NULL;
675 id = isl_id_alloc(ctx, NULL, expr);
676 dim = isl_space_params_alloc(ctx, 1);
678 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
680 dom = isl_set_universe(isl_space_copy(dim));
681 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
682 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
684 return isl_pw_aff_alloc(dom, aff);
687 /* Affine expressions are not supposed to contain array accesses,
688 * but if nesting is allowed, we return a parameter corresponding
689 * to the array access.
691 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
693 return nested_access(expr);
696 /* Extract an affine expression from a conditional operation.
698 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
700 isl_set *cond;
701 isl_pw_aff *lhs, *rhs;
703 cond = extract_condition(expr->getCond());
704 lhs = extract_affine(expr->getTrueExpr());
705 rhs = extract_affine(expr->getFalseExpr());
707 return isl_pw_aff_cond(cond, lhs, rhs);
710 /* Extract an affine expression, if possible, from "expr".
711 * Otherwise return NULL.
713 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
715 switch (expr->getStmtClass()) {
716 case Stmt::ImplicitCastExprClass:
717 return extract_affine(cast<ImplicitCastExpr>(expr));
718 case Stmt::IntegerLiteralClass:
719 return extract_affine(cast<IntegerLiteral>(expr));
720 case Stmt::DeclRefExprClass:
721 return extract_affine(cast<DeclRefExpr>(expr));
722 case Stmt::BinaryOperatorClass:
723 return extract_affine(cast<BinaryOperator>(expr));
724 case Stmt::UnaryOperatorClass:
725 return extract_affine(cast<UnaryOperator>(expr));
726 case Stmt::ParenExprClass:
727 return extract_affine(cast<ParenExpr>(expr));
728 case Stmt::CallExprClass:
729 return extract_affine(cast<CallExpr>(expr));
730 case Stmt::ArraySubscriptExprClass:
731 return extract_affine(cast<ArraySubscriptExpr>(expr));
732 case Stmt::ConditionalOperatorClass:
733 return extract_affine(cast<ConditionalOperator>(expr));
734 default:
735 unsupported(expr);
737 return NULL;
740 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
742 return extract_access(expr->getSubExpr());
745 /* Return the depth of an array of the given type.
747 static int array_depth(const Type *type)
749 if (type->isPointerType())
750 return 1 + array_depth(type->getPointeeType().getTypePtr());
751 if (type->isArrayType()) {
752 const ArrayType *atype;
753 type = type->getCanonicalTypeInternal().getTypePtr();
754 atype = cast<ArrayType>(type);
755 return 1 + array_depth(atype->getElementType().getTypePtr());
757 return 0;
760 /* Return the element type of the given array type.
762 static QualType base_type(QualType qt)
764 const Type *type = qt.getTypePtr();
766 if (type->isPointerType())
767 return base_type(type->getPointeeType());
768 if (type->isArrayType()) {
769 const ArrayType *atype;
770 type = type->getCanonicalTypeInternal().getTypePtr();
771 atype = cast<ArrayType>(type);
772 return base_type(atype->getElementType());
774 return qt;
777 /* Extract an access relation from a reference to a variable.
778 * If the variable has name "A" and its type corresponds to an
779 * array of depth d, then the returned access relation is of the
780 * form
782 * { [] -> A[i_1,...,i_d] }
784 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
786 ValueDecl *decl = expr->getDecl();
787 int depth = array_depth(decl->getType().getTypePtr());
788 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
789 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
790 isl_map *access_rel;
792 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
794 access_rel = isl_map_universe(dim);
796 return access_rel;
799 /* Extract an access relation from an integer contant.
800 * If the value of the constant is "v", then the returned access relation
801 * is
803 * { [] -> [v] }
805 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
807 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
810 /* Try and extract an access relation from the given Expr.
811 * Return NULL if it doesn't work out.
813 __isl_give isl_map *PetScan::extract_access(Expr *expr)
815 switch (expr->getStmtClass()) {
816 case Stmt::ImplicitCastExprClass:
817 return extract_access(cast<ImplicitCastExpr>(expr));
818 case Stmt::DeclRefExprClass:
819 return extract_access(cast<DeclRefExpr>(expr));
820 case Stmt::ArraySubscriptExprClass:
821 return extract_access(cast<ArraySubscriptExpr>(expr));
822 default:
823 unsupported(expr);
825 return NULL;
828 /* Assign the affine expression "index" to the output dimension "pos" of "map"
829 * and return the result.
831 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
832 __isl_take isl_pw_aff *index)
834 isl_map *index_map;
835 int len = isl_map_dim(map, isl_dim_out);
836 isl_id *id;
838 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
839 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
840 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
841 id = isl_map_get_tuple_id(map, isl_dim_out);
842 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
844 map = isl_map_intersect(map, index_map);
846 return map;
849 /* Extract an access relation from the given array subscript expression.
850 * If nesting is allowed in general, then we turn it on while
851 * examining the index expression.
853 * We first extract an access relation from the base.
854 * This will result in an access relation with a range that corresponds
855 * to the array being accessed and with earlier indices filled in already.
856 * We then extract the current index and fill that in as well.
857 * The position of the current index is based on the type of base.
858 * If base is the actual array variable, then the depth of this type
859 * will be the same as the depth of the array and we will fill in
860 * the first array index.
861 * Otherwise, the depth of the base type will be smaller and we will fill
862 * in a later index.
864 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
866 Expr *base = expr->getBase();
867 Expr *idx = expr->getIdx();
868 isl_pw_aff *index;
869 isl_map *base_access;
870 isl_map *access;
871 int depth = array_depth(base->getType().getTypePtr());
872 int pos;
873 bool save_nesting = nesting_enabled;
875 nesting_enabled = allow_nested;
877 base_access = extract_access(base);
878 index = extract_affine(idx);
880 nesting_enabled = save_nesting;
882 pos = isl_map_dim(base_access, isl_dim_out) - depth;
883 access = set_index(base_access, pos, index);
885 return access;
888 /* Check if "expr" calls function "minmax" with two arguments and if so
889 * make lhs and rhs refer to these two arguments.
891 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
893 CallExpr *call;
894 FunctionDecl *fd;
895 string name;
897 if (expr->getStmtClass() != Stmt::CallExprClass)
898 return false;
900 call = cast<CallExpr>(expr);
901 fd = call->getDirectCallee();
902 if (!fd)
903 return false;
905 if (call->getNumArgs() != 2)
906 return false;
908 name = fd->getDeclName().getAsString();
909 if (name != minmax)
910 return false;
912 lhs = call->getArg(0);
913 rhs = call->getArg(1);
915 return true;
918 /* Check if "expr" is of the form min(lhs, rhs) and if so make
919 * lhs and rhs refer to the two arguments.
921 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
923 return is_minmax(expr, "min", lhs, rhs);
926 /* Check if "expr" is of the form max(lhs, rhs) and if so make
927 * lhs and rhs refer to the two arguments.
929 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
931 return is_minmax(expr, "max", lhs, rhs);
934 /* Extract a set of values satisfying the comparison "LHS op RHS"
935 * "comp" is the original statement that "LHS op RHS" is derived from
936 * and is used for diagnostics.
938 * If the comparison is of the form
940 * a <= min(b,c)
942 * then the set is constructed as the intersection of the set corresponding
943 * to the comparisons
945 * a <= b and a <= c
947 * A similar optimization is performed for max(a,b) <= c.
948 * We do this because that will lead to simpler representations of the set.
949 * If isl is ever enhanced to explicitly deal with min and max expressions,
950 * this optimization can be removed.
952 __isl_give isl_set *PetScan::extract_comparison(BinaryOperatorKind op,
953 Expr *LHS, Expr *RHS, Stmt *comp)
955 isl_pw_aff *lhs;
956 isl_pw_aff *rhs;
957 isl_set *cond;
959 if (op == BO_GT)
960 return extract_comparison(BO_LT, RHS, LHS, comp);
961 if (op == BO_GE)
962 return extract_comparison(BO_LE, RHS, LHS, comp);
964 if (op == BO_LT || op == BO_LE) {
965 Expr *expr1, *expr2;
966 isl_set *set1, *set2;
967 if (is_min(RHS, expr1, expr2)) {
968 set1 = extract_comparison(op, LHS, expr1, comp);
969 set2 = extract_comparison(op, LHS, expr2, comp);
970 return isl_set_intersect(set1, set2);
972 if (is_max(LHS, expr1, expr2)) {
973 set1 = extract_comparison(op, expr1, RHS, comp);
974 set2 = extract_comparison(op, expr2, RHS, comp);
975 return isl_set_intersect(set1, set2);
979 lhs = extract_affine(LHS);
980 rhs = extract_affine(RHS);
982 switch (op) {
983 case BO_LT:
984 cond = isl_pw_aff_lt_set(lhs, rhs);
985 break;
986 case BO_LE:
987 cond = isl_pw_aff_le_set(lhs, rhs);
988 break;
989 case BO_EQ:
990 cond = isl_pw_aff_eq_set(lhs, rhs);
991 break;
992 case BO_NE:
993 cond = isl_pw_aff_ne_set(lhs, rhs);
994 break;
995 default:
996 isl_pw_aff_free(lhs);
997 isl_pw_aff_free(rhs);
998 unsupported(comp);
999 return NULL;
1002 cond = isl_set_coalesce(cond);
1004 return cond;
1007 __isl_give isl_set *PetScan::extract_comparison(BinaryOperator *comp)
1009 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1010 comp->getRHS(), comp);
1013 /* Extract a set of values satisfying the negation (logical not)
1014 * of a subexpression.
1016 __isl_give isl_set *PetScan::extract_boolean(UnaryOperator *op)
1018 isl_set *cond;
1020 cond = extract_condition(op->getSubExpr());
1022 return isl_set_complement(cond);
1025 /* Extract a set of values satisfying the union (logical or)
1026 * or intersection (logical and) of two subexpressions.
1028 __isl_give isl_set *PetScan::extract_boolean(BinaryOperator *comp)
1030 isl_set *lhs;
1031 isl_set *rhs;
1032 isl_set *cond;
1034 lhs = extract_condition(comp->getLHS());
1035 rhs = extract_condition(comp->getRHS());
1037 switch (comp->getOpcode()) {
1038 case BO_LAnd:
1039 cond = isl_set_intersect(lhs, rhs);
1040 break;
1041 case BO_LOr:
1042 cond = isl_set_union(lhs, rhs);
1043 break;
1044 default:
1045 isl_set_free(lhs);
1046 isl_set_free(rhs);
1047 unsupported(comp);
1048 return NULL;
1051 return cond;
1054 __isl_give isl_set *PetScan::extract_condition(UnaryOperator *expr)
1056 switch (expr->getOpcode()) {
1057 case UO_LNot:
1058 return extract_boolean(expr);
1059 default:
1060 unsupported(expr);
1061 return NULL;
1065 /* Extract a set of values satisfying the condition "expr != 0".
1067 __isl_give isl_set *PetScan::extract_implicit_condition(Expr *expr)
1069 return isl_pw_aff_non_zero_set(extract_affine(expr));
1072 /* Extract a set of values satisfying the condition expressed by "expr".
1074 * If the expression doesn't look like a condition, we assume it
1075 * is an affine expression and return the condition "expr != 0".
1077 __isl_give isl_set *PetScan::extract_condition(Expr *expr)
1079 BinaryOperator *comp;
1081 if (!expr)
1082 return isl_set_universe(isl_space_params_alloc(ctx, 0));
1084 if (expr->getStmtClass() == Stmt::ParenExprClass)
1085 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1087 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1088 return extract_condition(cast<UnaryOperator>(expr));
1090 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1091 return extract_implicit_condition(expr);
1093 comp = cast<BinaryOperator>(expr);
1094 switch (comp->getOpcode()) {
1095 case BO_LT:
1096 case BO_LE:
1097 case BO_GT:
1098 case BO_GE:
1099 case BO_EQ:
1100 case BO_NE:
1101 return extract_comparison(comp);
1102 case BO_LAnd:
1103 case BO_LOr:
1104 return extract_boolean(comp);
1105 default:
1106 return extract_implicit_condition(expr);
1110 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1112 switch (kind) {
1113 case UO_Minus:
1114 return pet_op_minus;
1115 default:
1116 return pet_op_last;
1120 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1122 switch (kind) {
1123 case BO_AddAssign:
1124 return pet_op_add_assign;
1125 case BO_SubAssign:
1126 return pet_op_sub_assign;
1127 case BO_MulAssign:
1128 return pet_op_mul_assign;
1129 case BO_DivAssign:
1130 return pet_op_div_assign;
1131 case BO_Assign:
1132 return pet_op_assign;
1133 case BO_Add:
1134 return pet_op_add;
1135 case BO_Sub:
1136 return pet_op_sub;
1137 case BO_Mul:
1138 return pet_op_mul;
1139 case BO_Div:
1140 return pet_op_div;
1141 case BO_EQ:
1142 return pet_op_eq;
1143 case BO_LE:
1144 return pet_op_le;
1145 case BO_LT:
1146 return pet_op_lt;
1147 case BO_GT:
1148 return pet_op_gt;
1149 default:
1150 return pet_op_last;
1154 /* Construct a pet_expr representing a unary operator expression.
1156 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1158 struct pet_expr *arg;
1159 enum pet_op_type op;
1161 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1162 if (op == pet_op_last) {
1163 unsupported(expr);
1164 return NULL;
1167 arg = extract_expr(expr->getSubExpr());
1169 return pet_expr_new_unary(ctx, op, arg);
1172 /* Mark the given access pet_expr as a write.
1173 * If a scalar is being accessed, then mark its value
1174 * as unknown in assigned_value.
1176 void PetScan::mark_write(struct pet_expr *access)
1178 isl_id *id;
1179 ValueDecl *decl;
1181 access->acc.write = 1;
1182 access->acc.read = 0;
1184 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1185 return;
1187 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1188 decl = (ValueDecl *) isl_id_get_user(id);
1189 clear_assignment(assigned_value, decl);
1190 isl_id_free(id);
1193 /* Construct a pet_expr representing a binary operator expression.
1195 * If the top level operator is an assignment and the LHS is an access,
1196 * then we mark that access as a write. If the operator is a compound
1197 * assignment, the access is marked as both a read and a write.
1199 * If "expr" assigns something to a scalar variable, then we mark
1200 * the variable as having been assigned. If, furthermore, the expression
1201 * is affine, then keep track of this value in assigned_value
1202 * so that we can plug it in when we later come across the same variable.
1204 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1206 struct pet_expr *lhs, *rhs;
1207 enum pet_op_type op;
1209 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1210 if (op == pet_op_last) {
1211 unsupported(expr);
1212 return NULL;
1215 lhs = extract_expr(expr->getLHS());
1216 rhs = extract_expr(expr->getRHS());
1218 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1219 mark_write(lhs);
1220 if (expr->isCompoundAssignmentOp())
1221 lhs->acc.read = 1;
1224 if (expr->getOpcode() == BO_Assign &&
1225 lhs && lhs->type == pet_expr_access &&
1226 isl_map_dim(lhs->acc.access, isl_dim_out) == 0) {
1227 isl_id *id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1228 ValueDecl *decl = (ValueDecl *) isl_id_get_user(id);
1229 Expr *rhs = expr->getRHS();
1230 isl_pw_aff *pa = try_extract_affine(rhs);
1231 clear_assignment(assigned_value, decl);
1232 if (pa) {
1233 assigned_value[decl] = pa;
1234 insert_expression(pa);
1236 isl_id_free(id);
1239 return pet_expr_new_binary(ctx, op, lhs, rhs);
1242 /* Construct a pet_expr representing a conditional operation.
1244 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1246 struct pet_expr *cond, *lhs, *rhs;
1248 cond = extract_expr(expr->getCond());
1249 lhs = extract_expr(expr->getTrueExpr());
1250 rhs = extract_expr(expr->getFalseExpr());
1252 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1255 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1257 return extract_expr(expr->getSubExpr());
1260 /* Construct a pet_expr representing a floating point value.
1262 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1264 return pet_expr_new_double(ctx, expr->getValueAsApproximateDouble());
1267 /* Extract an access relation from "expr" and then convert it into
1268 * a pet_expr.
1270 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1272 isl_map *access;
1273 struct pet_expr *pe;
1275 switch (expr->getStmtClass()) {
1276 case Stmt::ArraySubscriptExprClass:
1277 access = extract_access(cast<ArraySubscriptExpr>(expr));
1278 break;
1279 case Stmt::DeclRefExprClass:
1280 access = extract_access(cast<DeclRefExpr>(expr));
1281 break;
1282 case Stmt::IntegerLiteralClass:
1283 access = extract_access(cast<IntegerLiteral>(expr));
1284 break;
1285 default:
1286 unsupported(expr);
1287 return NULL;
1290 pe = pet_expr_from_access(access);
1292 return pe;
1295 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1297 return extract_expr(expr->getSubExpr());
1300 /* Construct a pet_expr representing a function call.
1302 * If we are passing along a pointer to an array element
1303 * or an entire row or even higher dimensional slice of an array,
1304 * then the function being called may write into the array.
1306 * We assume here that if the function is declared to take a pointer
1307 * to a const type, then the function will perform a read
1308 * and that otherwise, it will perform a write.
1310 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1312 struct pet_expr *res = NULL;
1313 FunctionDecl *fd;
1314 string name;
1316 fd = expr->getDirectCallee();
1317 if (!fd) {
1318 unsupported(expr);
1319 return NULL;
1322 name = fd->getDeclName().getAsString();
1323 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1324 if (!res)
1325 return NULL;
1327 for (int i = 0; i < expr->getNumArgs(); ++i) {
1328 Expr *arg = expr->getArg(i);
1329 int is_addr = 0;
1331 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1332 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1333 arg = ice->getSubExpr();
1335 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1336 UnaryOperator *op = cast<UnaryOperator>(arg);
1337 if (op->getOpcode() == UO_AddrOf) {
1338 is_addr = 1;
1339 arg = op->getSubExpr();
1342 res->args[i] = PetScan::extract_expr(arg);
1343 if (!res->args[i])
1344 goto error;
1345 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1346 array_depth(arg->getType().getTypePtr()) > 0)
1347 is_addr = 1;
1348 if (is_addr && res->args[i]->type == pet_expr_access) {
1349 ParmVarDecl *parm = fd->getParamDecl(i);
1350 if (!const_base(parm->getType()))
1351 mark_write(res->args[i]);
1355 return res;
1356 error:
1357 pet_expr_free(res);
1358 return NULL;
1361 /* Try and onstruct a pet_expr representing "expr".
1363 struct pet_expr *PetScan::extract_expr(Expr *expr)
1365 switch (expr->getStmtClass()) {
1366 case Stmt::UnaryOperatorClass:
1367 return extract_expr(cast<UnaryOperator>(expr));
1368 case Stmt::CompoundAssignOperatorClass:
1369 case Stmt::BinaryOperatorClass:
1370 return extract_expr(cast<BinaryOperator>(expr));
1371 case Stmt::ImplicitCastExprClass:
1372 return extract_expr(cast<ImplicitCastExpr>(expr));
1373 case Stmt::ArraySubscriptExprClass:
1374 case Stmt::DeclRefExprClass:
1375 case Stmt::IntegerLiteralClass:
1376 return extract_access_expr(expr);
1377 case Stmt::FloatingLiteralClass:
1378 return extract_expr(cast<FloatingLiteral>(expr));
1379 case Stmt::ParenExprClass:
1380 return extract_expr(cast<ParenExpr>(expr));
1381 case Stmt::ConditionalOperatorClass:
1382 return extract_expr(cast<ConditionalOperator>(expr));
1383 case Stmt::CallExprClass:
1384 return extract_expr(cast<CallExpr>(expr));
1385 default:
1386 unsupported(expr);
1388 return NULL;
1391 /* Check if the given initialization statement is an assignment.
1392 * If so, return that assignment. Otherwise return NULL.
1394 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1396 BinaryOperator *ass;
1398 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1399 return NULL;
1401 ass = cast<BinaryOperator>(init);
1402 if (ass->getOpcode() != BO_Assign)
1403 return NULL;
1405 return ass;
1408 /* Check if the given initialization statement is a declaration
1409 * of a single variable.
1410 * If so, return that declaration. Otherwise return NULL.
1412 Decl *PetScan::initialization_declaration(Stmt *init)
1414 DeclStmt *decl;
1416 if (init->getStmtClass() != Stmt::DeclStmtClass)
1417 return NULL;
1419 decl = cast<DeclStmt>(init);
1421 if (!decl->isSingleDecl())
1422 return NULL;
1424 return decl->getSingleDecl();
1427 /* Given the assignment operator in the initialization of a for loop,
1428 * extract the induction variable, i.e., the (integer)variable being
1429 * assigned.
1431 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1433 Expr *lhs;
1434 DeclRefExpr *ref;
1435 ValueDecl *decl;
1436 const Type *type;
1438 lhs = init->getLHS();
1439 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1440 unsupported(init);
1441 return NULL;
1444 ref = cast<DeclRefExpr>(lhs);
1445 decl = ref->getDecl();
1446 type = decl->getType().getTypePtr();
1448 if (!type->isIntegerType()) {
1449 unsupported(lhs);
1450 return NULL;
1453 return decl;
1456 /* Given the initialization statement of a for loop and the single
1457 * declaration in this initialization statement,
1458 * extract the induction variable, i.e., the (integer) variable being
1459 * declared.
1461 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1463 VarDecl *vd;
1465 vd = cast<VarDecl>(decl);
1467 const QualType type = vd->getType();
1468 if (!type->isIntegerType()) {
1469 unsupported(init);
1470 return NULL;
1473 if (!vd->getInit()) {
1474 unsupported(init);
1475 return NULL;
1478 return vd;
1481 /* Check that op is of the form iv++ or iv--.
1482 * "inc" is accordingly set to 1 or -1.
1484 bool PetScan::check_unary_increment(UnaryOperator *op, clang::ValueDecl *iv,
1485 isl_int &inc)
1487 Expr *sub;
1488 DeclRefExpr *ref;
1490 if (!op->isIncrementDecrementOp()) {
1491 unsupported(op);
1492 return false;
1495 if (op->isIncrementOp())
1496 isl_int_set_si(inc, 1);
1497 else
1498 isl_int_set_si(inc, -1);
1500 sub = op->getSubExpr();
1501 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1502 unsupported(op);
1503 return false;
1506 ref = cast<DeclRefExpr>(sub);
1507 if (ref->getDecl() != iv) {
1508 unsupported(op);
1509 return false;
1512 return true;
1515 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1516 * has a single constant expression on a universe domain, then
1517 * put this constant in *user.
1519 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1520 void *user)
1522 isl_int *inc = (isl_int *)user;
1523 int res = 0;
1525 if (!isl_set_plain_is_universe(set) || !isl_aff_is_cst(aff))
1526 res = -1;
1527 else
1528 isl_aff_get_constant(aff, inc);
1530 isl_set_free(set);
1531 isl_aff_free(aff);
1533 return res;
1536 /* Check if op is of the form
1538 * iv = iv + inc
1540 * with inc a constant and set "inc" accordingly.
1542 * We extract an affine expression from the RHS and the subtract iv.
1543 * The result should be a constant.
1545 bool PetScan::check_binary_increment(BinaryOperator *op, clang::ValueDecl *iv,
1546 isl_int &inc)
1548 Expr *lhs;
1549 DeclRefExpr *ref;
1550 isl_id *id;
1551 isl_space *dim;
1552 isl_aff *aff;
1553 isl_pw_aff *val;
1555 if (op->getOpcode() != BO_Assign) {
1556 unsupported(op);
1557 return false;
1560 lhs = op->getLHS();
1561 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1562 unsupported(op);
1563 return false;
1566 ref = cast<DeclRefExpr>(lhs);
1567 if (ref->getDecl() != iv) {
1568 unsupported(op);
1569 return false;
1572 val = extract_affine(op->getRHS());
1574 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1576 dim = isl_space_params_alloc(ctx, 1);
1577 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1578 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1579 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1581 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1583 if (isl_pw_aff_foreach_piece(val, &extract_cst, &inc) < 0) {
1584 isl_pw_aff_free(val);
1585 unsupported(op);
1586 return false;
1589 isl_pw_aff_free(val);
1591 return true;
1594 /* Check that op is of the form iv += cst or iv -= cst.
1595 * "inc" is set to cst or -cst accordingly.
1597 bool PetScan::check_compound_increment(CompoundAssignOperator *op,
1598 clang::ValueDecl *iv, isl_int &inc)
1600 Expr *lhs, *rhs;
1601 DeclRefExpr *ref;
1602 bool neg = false;
1604 BinaryOperatorKind opcode;
1606 opcode = op->getOpcode();
1607 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1608 unsupported(op);
1609 return false;
1611 if (opcode == BO_SubAssign)
1612 neg = true;
1614 lhs = op->getLHS();
1615 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1616 unsupported(op);
1617 return false;
1620 ref = cast<DeclRefExpr>(lhs);
1621 if (ref->getDecl() != iv) {
1622 unsupported(op);
1623 return false;
1626 rhs = op->getRHS();
1628 if (rhs->getStmtClass() == Stmt::UnaryOperatorClass) {
1629 UnaryOperator *op = cast<UnaryOperator>(rhs);
1630 if (op->getOpcode() != UO_Minus) {
1631 unsupported(op);
1632 return false;
1635 neg = !neg;
1637 rhs = op->getSubExpr();
1640 if (rhs->getStmtClass() != Stmt::IntegerLiteralClass) {
1641 unsupported(op);
1642 return false;
1645 extract_int(cast<IntegerLiteral>(rhs), &inc);
1646 if (neg)
1647 isl_int_neg(inc, inc);
1649 return true;
1652 /* Check that the increment of the given for loop increments
1653 * (or decrements) the induction variable "iv".
1654 * "up" is set to true if the induction variable is incremented.
1656 bool PetScan::check_increment(ForStmt *stmt, ValueDecl *iv, isl_int &v)
1658 Stmt *inc = stmt->getInc();
1660 if (!inc) {
1661 unsupported(stmt);
1662 return false;
1665 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1666 return check_unary_increment(cast<UnaryOperator>(inc), iv, v);
1667 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1668 return check_compound_increment(
1669 cast<CompoundAssignOperator>(inc), iv, v);
1670 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1671 return check_binary_increment(cast<BinaryOperator>(inc), iv, v);
1673 unsupported(inc);
1674 return false;
1677 /* Embed the given iteration domain in an extra outer loop
1678 * with induction variable "var".
1679 * If this variable appeared as a parameter in the constraints,
1680 * it is replaced by the new outermost dimension.
1682 static __isl_give isl_set *embed(__isl_take isl_set *set,
1683 __isl_take isl_id *var)
1685 int pos;
1687 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1688 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1689 if (pos >= 0) {
1690 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1691 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1694 isl_id_free(var);
1695 return set;
1698 /* Construct a pet_scop for an infinite loop around the given body.
1700 * We extract a pet_scop for the body and then embed it in a loop with
1701 * iteration domain
1703 * { [t] : t >= 0 }
1705 * and schedule
1707 * { [t] -> [t] }
1709 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1711 isl_id *id;
1712 isl_space *dim;
1713 isl_set *domain;
1714 isl_map *sched;
1715 struct pet_scop *scop;
1717 scop = extract(body);
1718 if (!scop)
1719 return NULL;
1721 id = isl_id_alloc(ctx, "t", NULL);
1722 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1723 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
1724 dim = isl_space_from_domain(isl_set_get_space(domain));
1725 dim = isl_space_add_dims(dim, isl_dim_out, 1);
1726 sched = isl_map_universe(dim);
1727 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
1728 scop = pet_scop_embed(scop, domain, sched, id);
1730 return scop;
1733 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1735 * for (;;)
1736 * body
1739 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1741 return extract_infinite_loop(stmt->getBody());
1744 /* Check if the while loop is of the form
1746 * while (1)
1747 * body
1749 * If so, construct a scop for an infinite loop around body.
1750 * Otherwise, fail.
1752 struct pet_scop *PetScan::extract(WhileStmt *stmt)
1754 Expr *cond;
1755 isl_set *set;
1756 int is_universe;
1758 cond = stmt->getCond();
1759 if (!cond) {
1760 unsupported(stmt);
1761 return NULL;
1764 set = extract_condition(cond);
1765 is_universe = isl_set_plain_is_universe(set);
1766 isl_set_free(set);
1768 if (!is_universe) {
1769 unsupported(stmt);
1770 return NULL;
1773 return extract_infinite_loop(stmt->getBody());
1776 /* Check whether "cond" expresses a simple loop bound
1777 * on the only set dimension.
1778 * In particular, if "up" is set then "cond" should contain only
1779 * upper bounds on the set dimension.
1780 * Otherwise, it should contain only lower bounds.
1782 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
1784 if (isl_int_is_pos(inc))
1785 return !isl_set_dim_has_lower_bound(cond, isl_dim_set, 0);
1786 else
1787 return !isl_set_dim_has_upper_bound(cond, isl_dim_set, 0);
1790 /* Extend a condition on a given iteration of a loop to one that
1791 * imposes the same condition on all previous iterations.
1792 * "domain" expresses the lower [upper] bound on the iterations
1793 * when inc is positive [negative].
1795 * In particular, we construct the condition (when inc is positive)
1797 * forall i' : (domain(i') and i' <= i) => cond(i')
1799 * which is equivalent to
1801 * not exists i' : domain(i') and i' <= i and not cond(i')
1803 * We construct this set by negating cond, applying a map
1805 * { [i'] -> [i] : domain(i') and i' <= i }
1807 * and then negating the result again.
1809 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
1810 __isl_take isl_set *domain, isl_int inc)
1812 isl_map *previous_to_this;
1814 if (isl_int_is_pos(inc))
1815 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
1816 else
1817 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
1819 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
1821 cond = isl_set_complement(cond);
1822 cond = isl_set_apply(cond, previous_to_this);
1823 cond = isl_set_complement(cond);
1825 return cond;
1828 /* Construct a domain of the form
1830 * [id] -> { [] : exists a: id = init + a * inc and a >= 0 }
1832 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
1833 __isl_take isl_pw_aff *init, isl_int inc)
1835 isl_aff *aff;
1836 isl_space *dim;
1837 isl_set *set;
1839 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
1840 dim = isl_pw_aff_get_domain_space(init);
1841 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1842 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
1843 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
1845 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
1846 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1847 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1848 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1850 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
1852 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
1854 return isl_set_project_out(set, isl_dim_set, 0, 1);
1857 static unsigned get_type_size(ValueDecl *decl)
1859 return decl->getASTContext().getIntWidth(decl->getType());
1862 /* Assuming "cond" represents a simple bound on a loop where the loop
1863 * iterator "iv" is incremented (or decremented) by one, check if wrapping
1864 * is possible.
1866 * Under the given assumptions, wrapping is only possible if "cond" allows
1867 * for the last value before wrapping, i.e., 2^width - 1 in case of an
1868 * increasing iterator and 0 in case of a decreasing iterator.
1870 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
1872 bool cw;
1873 isl_int limit;
1874 isl_set *test;
1876 test = isl_set_copy(cond);
1878 isl_int_init(limit);
1879 if (isl_int_is_neg(inc))
1880 isl_int_set_si(limit, 0);
1881 else {
1882 isl_int_set_si(limit, 1);
1883 isl_int_mul_2exp(limit, limit, get_type_size(iv));
1884 isl_int_sub_ui(limit, limit, 1);
1887 test = isl_set_fix(cond, isl_dim_set, 0, limit);
1888 cw = !isl_set_is_empty(test);
1889 isl_set_free(test);
1891 isl_int_clear(limit);
1893 return cw;
1896 /* Given a one-dimensional space, construct the following mapping on this
1897 * space
1899 * { [v] -> [v mod 2^width] }
1901 * where width is the number of bits used to represent the values
1902 * of the unsigned variable "iv".
1904 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
1905 ValueDecl *iv)
1907 isl_int mod;
1908 isl_aff *aff;
1909 isl_map *map;
1911 isl_int_init(mod);
1912 isl_int_set_si(mod, 1);
1913 isl_int_mul_2exp(mod, mod, get_type_size(iv));
1915 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1916 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1917 aff = isl_aff_mod(aff, mod);
1919 isl_int_clear(mod);
1921 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
1922 map = isl_map_reverse(map);
1925 /* Construct a pet_scop for a for statement.
1926 * The for loop is required to be of the form
1928 * for (i = init; condition; ++i)
1930 * or
1932 * for (i = init; condition; --i)
1934 * The initialization of the for loop should either be an assignment
1935 * to an integer variable, or a declaration of such a variable with
1936 * initialization.
1938 * The condition is allowed to contain nested accesses, provided
1939 * they are not being written to inside the body of the loop.
1941 * We extract a pet_scop for the body and then embed it in a loop with
1942 * iteration domain and schedule
1944 * { [i] : i >= init and condition' }
1945 * { [i] -> [i] }
1947 * or
1949 * { [i] : i <= init and condition' }
1950 * { [i] -> [-i] }
1952 * Where condition' is equal to condition if the latter is
1953 * a simple upper [lower] bound and a condition that is extended
1954 * to apply to all previous iterations otherwise.
1956 * If the stride of the loop is not 1, then "i >= init" is replaced by
1958 * (exists a: i = init + stride * a and a >= 0)
1960 * If the loop iterator i is unsigned, then wrapping may occur.
1961 * During the computation, we work with a virtual iterator that
1962 * does not wrap. However, the condition in the code applies
1963 * to the wrapped value, so we need to change condition(i)
1964 * into condition([i % 2^width]).
1965 * After computing the virtual domain and schedule, we apply
1966 * the function { [v] -> [v % 2^width] } to the domain and the domain
1967 * of the schedule. In order not to lose any information, we also
1968 * need to intersect the domain of the schedule with the virtual domain
1969 * first, since some iterations in the wrapped domain may be scheduled
1970 * several times, typically an infinite number of times.
1971 * Note that there is no need to perform this final wrapping
1972 * if the loop condition (after wrapping) is simple.
1974 * Wrapping on unsigned iterators can be avoided entirely if
1975 * loop condition is simple, the loop iterator is incremented
1976 * [decremented] by one and the last value before wrapping cannot
1977 * possibly satisfy the loop condition.
1979 * Before extracting a pet_scop from the body we remove all
1980 * assignments in assigned_value to variables that are assigned
1981 * somewhere in the body of the loop.
1983 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
1985 BinaryOperator *ass;
1986 Decl *decl;
1987 Stmt *init;
1988 Expr *lhs, *rhs;
1989 ValueDecl *iv;
1990 isl_space *dim;
1991 isl_set *domain;
1992 isl_map *sched;
1993 isl_set *cond = NULL;
1994 isl_id *id;
1995 struct pet_scop *scop;
1996 assigned_value_cache cache(assigned_value);
1997 isl_int inc;
1998 bool is_one;
1999 bool is_unsigned;
2000 bool is_simple;
2001 isl_map *wrap = NULL;
2003 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2004 return extract_infinite_for(stmt);
2006 init = stmt->getInit();
2007 if (!init) {
2008 unsupported(stmt);
2009 return NULL;
2011 if ((ass = initialization_assignment(init)) != NULL) {
2012 iv = extract_induction_variable(ass);
2013 if (!iv)
2014 return NULL;
2015 lhs = ass->getLHS();
2016 rhs = ass->getRHS();
2017 } else if ((decl = initialization_declaration(init)) != NULL) {
2018 VarDecl *var = extract_induction_variable(init, decl);
2019 if (!var)
2020 return NULL;
2021 iv = var;
2022 rhs = var->getInit();
2023 lhs = DeclRefExpr::Create(iv->getASTContext(),
2024 var->getQualifierLoc(), iv, var->getInnerLocStart(),
2025 var->getType(), VK_LValue);
2026 } else {
2027 unsupported(stmt->getInit());
2028 return NULL;
2031 isl_int_init(inc);
2032 if (!check_increment(stmt, iv, inc)) {
2033 isl_int_clear(inc);
2034 return NULL;
2037 is_unsigned = iv->getType()->isUnsignedIntegerType();
2039 assigned_value.erase(iv);
2040 clear_assignments clear(assigned_value);
2041 clear.TraverseStmt(stmt->getBody());
2043 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2045 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
2046 if (is_one)
2047 domain = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
2048 lhs, rhs, init);
2049 else {
2050 isl_pw_aff *lb = extract_affine(rhs);
2051 domain = strided_domain(isl_id_copy(id), lb, inc);
2054 scop = extract(stmt->getBody());
2056 cond = try_extract_nested_condition(stmt->getCond());
2057 if (cond && !is_nested_allowed(cond, scop)) {
2058 isl_set_free(cond);
2059 cond = NULL;
2062 if (!cond)
2063 cond = extract_condition(stmt->getCond());
2064 cond = embed(cond, isl_id_copy(id));
2065 domain = embed(domain, isl_id_copy(id));
2066 is_simple = is_simple_bound(cond, inc);
2067 if (is_unsigned &&
2068 (!is_simple || !is_one || can_wrap(cond, iv, inc))) {
2069 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2070 cond = isl_set_apply(cond, isl_map_reverse(isl_map_copy(wrap)));
2071 is_simple = is_simple && is_simple_bound(cond, inc);
2073 if (!is_simple)
2074 cond = valid_for_each_iteration(cond,
2075 isl_set_copy(domain), inc);
2076 domain = isl_set_intersect(domain, cond);
2077 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2078 dim = isl_space_from_domain(isl_set_get_space(domain));
2079 dim = isl_space_add_dims(dim, isl_dim_out, 1);
2080 sched = isl_map_universe(dim);
2081 if (isl_int_is_pos(inc))
2082 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2083 else
2084 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2086 if (is_unsigned && !is_simple) {
2087 wrap = isl_map_set_dim_id(wrap,
2088 isl_dim_out, 0, isl_id_copy(id));
2089 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2090 domain = isl_set_apply(domain, isl_map_copy(wrap));
2091 sched = isl_map_apply_domain(sched, wrap);
2092 } else
2093 isl_map_free(wrap);
2095 scop = pet_scop_embed(scop, domain, sched, id);
2096 scop = resolve_nested(scop);
2097 clear_assignment(assigned_value, iv);
2099 isl_int_clear(inc);
2100 return scop;
2103 struct pet_scop *PetScan::extract(CompoundStmt *stmt)
2105 return extract(stmt->children());
2108 /* Does "id" refer to a nested access?
2110 static bool is_nested_parameter(__isl_keep isl_id *id)
2112 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2115 /* Does parameter "pos" of "space" refer to a nested access?
2117 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2119 bool nested;
2120 isl_id *id;
2122 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2123 nested = is_nested_parameter(id);
2124 isl_id_free(id);
2126 return nested;
2129 /* Does parameter "pos" of "map" refer to a nested access?
2131 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2133 bool nested;
2134 isl_id *id;
2136 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2137 nested = is_nested_parameter(id);
2138 isl_id_free(id);
2140 return nested;
2143 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2145 static int n_nested_parameter(__isl_keep isl_space *space)
2147 int n = 0;
2148 int nparam;
2150 nparam = isl_space_dim(space, isl_dim_param);
2151 for (int i = 0; i < nparam; ++i)
2152 if (is_nested_parameter(space, i))
2153 ++n;
2155 return n;
2158 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2160 static int n_nested_parameter(__isl_keep isl_map *map)
2162 isl_space *space;
2163 int n;
2165 space = isl_map_get_space(map);
2166 n = n_nested_parameter(space);
2167 isl_space_free(space);
2169 return n;
2172 /* For each nested access parameter in "space",
2173 * construct a corresponding pet_expr, place it in args and
2174 * record its position in "param2pos".
2175 * "n_arg" is the number of elements that are already in args.
2176 * The position recorded in "param2pos" takes this number into account.
2177 * If the pet_expr corresponding to a parameter is identical to
2178 * the pet_expr corresponding to an earlier parameter, then these two
2179 * parameters are made to refer to the same element in args.
2181 * Return the final number of elements in args or -1 if an error has occurred.
2183 int PetScan::extract_nested(__isl_keep isl_space *space,
2184 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
2186 int nparam;
2188 nparam = isl_space_dim(space, isl_dim_param);
2189 for (int i = 0; i < nparam; ++i) {
2190 int j;
2191 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2192 Expr *nested;
2194 if (!is_nested_parameter(id)) {
2195 isl_id_free(id);
2196 continue;
2199 nested = (Expr *) isl_id_get_user(id);
2200 args[n_arg] = extract_expr(nested);
2201 if (!args[n_arg])
2202 return -1;
2204 for (j = 0; j < n_arg; ++j)
2205 if (pet_expr_is_equal(args[j], args[n_arg]))
2206 break;
2208 if (j < n_arg) {
2209 pet_expr_free(args[n_arg]);
2210 args[n_arg] = NULL;
2211 param2pos[i] = j;
2212 } else
2213 param2pos[i] = n_arg++;
2215 isl_id_free(id);
2218 return n_arg;
2221 /* For each nested access parameter in the access relations in "expr",
2222 * construct a corresponding pet_expr, place it in expr->args and
2223 * record its position in "param2pos".
2224 * n is the number of nested access parameters.
2226 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
2227 std::map<int,int> &param2pos)
2229 isl_space *space;
2231 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
2232 expr->n_arg = n;
2233 if (!expr->args)
2234 goto error;
2236 space = isl_map_get_space(expr->acc.access);
2237 n = extract_nested(space, 0, expr->args, param2pos);
2238 isl_space_free(space);
2240 if (n < 0)
2241 goto error;
2243 expr->n_arg = n;
2244 return expr;
2245 error:
2246 pet_expr_free(expr);
2247 return NULL;
2250 /* Look for parameters in any access relation in "expr" that
2251 * refer to nested accesses. In particular, these are
2252 * parameters with no name.
2254 * If there are any such parameters, then the domain of the access
2255 * relation, which is still [] at this point, is replaced by
2256 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2257 * (after identifying identical nested accesses).
2258 * The parameters are then equated to the corresponding t dimensions
2259 * and subsequently projected out.
2260 * param2pos maps the position of the parameter to the position
2261 * of the corresponding t dimension.
2263 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
2265 int n;
2266 int nparam;
2267 int n_in;
2268 isl_space *dim;
2269 isl_map *map;
2270 std::map<int,int> param2pos;
2272 if (!expr)
2273 return expr;
2275 for (int i = 0; i < expr->n_arg; ++i) {
2276 expr->args[i] = resolve_nested(expr->args[i]);
2277 if (!expr->args[i]) {
2278 pet_expr_free(expr);
2279 return NULL;
2283 if (expr->type != pet_expr_access)
2284 return expr;
2286 n = n_nested_parameter(expr->acc.access);
2287 if (n == 0)
2288 return expr;
2290 expr = extract_nested(expr, n, param2pos);
2291 if (!expr)
2292 return NULL;
2294 n = expr->n_arg;
2295 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
2296 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
2297 dim = isl_map_get_space(expr->acc.access);
2298 dim = isl_space_domain(dim);
2299 dim = isl_space_from_domain(dim);
2300 dim = isl_space_add_dims(dim, isl_dim_out, n);
2301 map = isl_map_universe(dim);
2302 map = isl_map_domain_map(map);
2303 map = isl_map_reverse(map);
2304 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
2306 for (int i = nparam - 1; i >= 0; --i) {
2307 isl_id *id = isl_map_get_dim_id(expr->acc.access,
2308 isl_dim_param, i);
2309 if (!is_nested_parameter(id)) {
2310 isl_id_free(id);
2311 continue;
2314 expr->acc.access = isl_map_equate(expr->acc.access,
2315 isl_dim_param, i, isl_dim_in,
2316 n_in + param2pos[i]);
2317 expr->acc.access = isl_map_project_out(expr->acc.access,
2318 isl_dim_param, i, 1);
2320 isl_id_free(id);
2323 return expr;
2324 error:
2325 pet_expr_free(expr);
2326 return NULL;
2329 /* Convert a top-level pet_expr to a pet_scop with one statement.
2330 * This mainly involves resolving nested expression parameters
2331 * and setting the name of the iteration space.
2332 * The name is given by "label" if it is non-NULL. Otherwise,
2333 * it is of the form S_<n_stmt>.
2335 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
2336 __isl_take isl_id *label)
2338 struct pet_stmt *ps;
2339 SourceLocation loc = stmt->getLocStart();
2340 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2342 expr = resolve_nested(expr);
2343 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
2344 return pet_scop_from_pet_stmt(ctx, ps);
2347 /* Check if we can extract an affine expression from "expr".
2348 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2349 * We turn on autodetection so that we won't generate any warnings
2350 * and turn off nesting, so that we won't accept any non-affine constructs.
2352 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
2354 isl_pw_aff *pwaff;
2355 int save_autodetect = autodetect;
2356 bool save_nesting = nesting_enabled;
2358 autodetect = 1;
2359 nesting_enabled = false;
2361 pwaff = extract_affine(expr);
2363 autodetect = save_autodetect;
2364 nesting_enabled = save_nesting;
2366 return pwaff;
2369 /* Check whether "expr" is an affine expression.
2371 bool PetScan::is_affine(Expr *expr)
2373 isl_pw_aff *pwaff;
2375 pwaff = try_extract_affine(expr);
2376 isl_pw_aff_free(pwaff);
2378 return pwaff != NULL;
2381 /* Check whether "expr" is an affine constraint.
2382 * We turn on autodetection so that we won't generate any warnings
2383 * and turn off nesting, so that we won't accept any non-affine constructs.
2385 bool PetScan::is_affine_condition(Expr *expr)
2387 isl_set *set;
2388 int save_autodetect = autodetect;
2389 bool save_nesting = nesting_enabled;
2391 autodetect = 1;
2392 nesting_enabled = false;
2394 set = extract_condition(expr);
2395 isl_set_free(set);
2397 autodetect = save_autodetect;
2398 nesting_enabled = save_nesting;
2400 return set != NULL;
2403 /* Check if we can extract a condition from "expr".
2404 * Return the condition as an isl_set if we can and NULL otherwise.
2405 * If allow_nested is set, then the condition may involve parameters
2406 * corresponding to nested accesses.
2407 * We turn on autodetection so that we won't generate any warnings.
2409 __isl_give isl_set *PetScan::try_extract_nested_condition(Expr *expr)
2411 isl_set *set;
2412 int save_autodetect = autodetect;
2413 bool save_nesting = nesting_enabled;
2415 autodetect = 1;
2416 nesting_enabled = allow_nested;
2417 set = extract_condition(expr);
2419 autodetect = save_autodetect;
2420 nesting_enabled = save_nesting;
2422 return set;
2425 /* If the top-level expression of "stmt" is an assignment, then
2426 * return that assignment as a BinaryOperator.
2427 * Otherwise return NULL.
2429 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
2431 BinaryOperator *ass;
2433 if (!stmt)
2434 return NULL;
2435 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
2436 return NULL;
2438 ass = cast<BinaryOperator>(stmt);
2439 if(ass->getOpcode() != BO_Assign)
2440 return NULL;
2442 return ass;
2445 /* Check if the given if statement is a conditional assignement
2446 * with a non-affine condition. If so, construct a pet_scop
2447 * corresponding to this conditional assignment. Otherwise return NULL.
2449 * In particular we check if "stmt" is of the form
2451 * if (condition)
2452 * a = f(...);
2453 * else
2454 * a = g(...);
2456 * where a is some array or scalar access.
2457 * The constructed pet_scop then corresponds to the expression
2459 * a = condition ? f(...) : g(...)
2461 * All access relations in f(...) are intersected with condition
2462 * while all access relation in g(...) are intersected with the complement.
2464 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
2466 BinaryOperator *ass_then, *ass_else;
2467 isl_map *write_then, *write_else;
2468 isl_set *cond, *comp;
2469 isl_map *map, *map_true, *map_false;
2470 int equal;
2471 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
2472 bool save_nesting = nesting_enabled;
2474 ass_then = top_assignment_or_null(stmt->getThen());
2475 ass_else = top_assignment_or_null(stmt->getElse());
2477 if (!ass_then || !ass_else)
2478 return NULL;
2480 if (is_affine_condition(stmt->getCond()))
2481 return NULL;
2483 write_then = extract_access(ass_then->getLHS());
2484 write_else = extract_access(ass_else->getLHS());
2486 equal = isl_map_is_equal(write_then, write_else);
2487 isl_map_free(write_else);
2488 if (equal < 0 || !equal) {
2489 isl_map_free(write_then);
2490 return NULL;
2493 nesting_enabled = allow_nested;
2494 cond = extract_condition(stmt->getCond());
2495 nesting_enabled = save_nesting;
2496 comp = isl_set_complement(isl_set_copy(cond));
2497 map_true = isl_map_from_domain(isl_set_from_params(isl_set_copy(cond)));
2498 map_true = isl_map_add_dims(map_true, isl_dim_out, 1);
2499 map_true = isl_map_fix_si(map_true, isl_dim_out, 0, 1);
2500 map_false = isl_map_from_domain(isl_set_from_params(isl_set_copy(comp)));
2501 map_false = isl_map_add_dims(map_false, isl_dim_out, 1);
2502 map_false = isl_map_fix_si(map_false, isl_dim_out, 0, 0);
2503 map = isl_map_union_disjoint(map_true, map_false);
2505 pe_cond = pet_expr_from_access(map);
2507 pe_then = extract_expr(ass_then->getRHS());
2508 pe_then = pet_expr_restrict(pe_then, cond);
2509 pe_else = extract_expr(ass_else->getRHS());
2510 pe_else = pet_expr_restrict(pe_else, comp);
2512 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
2513 pe_write = pet_expr_from_access(write_then);
2514 if (pe_write) {
2515 pe_write->acc.write = 1;
2516 pe_write->acc.read = 0;
2518 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
2519 return extract(stmt, pe);
2522 /* Create an access to a virtual array representing the result
2523 * of a condition.
2524 * Unlike other accessed data, the id of the array is NULL as
2525 * there is no ValueDecl in the program corresponding to the virtual
2526 * array.
2527 * The array starts out as a scalar, but grows along with the
2528 * statement writing to the array in pet_scop_embed.
2530 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2532 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2533 isl_id *id;
2534 char name[50];
2536 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2537 id = isl_id_alloc(ctx, name, NULL);
2538 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2539 return isl_map_universe(dim);
2542 /* Create a pet_scop with a single statement evaluating "cond"
2543 * and writing the result to a virtual scalar, as expressed by
2544 * "access".
2546 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
2547 __isl_take isl_map *access)
2549 struct pet_expr *expr, *write;
2550 struct pet_stmt *ps;
2551 SourceLocation loc = cond->getLocStart();
2552 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2554 write = pet_expr_from_access(access);
2555 if (write) {
2556 write->acc.write = 1;
2557 write->acc.read = 0;
2559 expr = extract_expr(cond);
2560 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
2561 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
2562 return pet_scop_from_pet_stmt(ctx, ps);
2565 /* Add an array with the given extend ("access") to the list
2566 * of arrays in "scop" and return the extended pet_scop.
2567 * The array is marked as attaining values 0 and 1 only.
2569 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2570 __isl_keep isl_map *access)
2572 isl_ctx *ctx = isl_map_get_ctx(access);
2573 isl_space *dim;
2574 struct pet_array **arrays;
2575 struct pet_array *array;
2577 if (!scop)
2578 return NULL;
2579 if (!ctx)
2580 goto error;
2582 arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2583 scop->n_array + 1);
2584 if (!arrays)
2585 goto error;
2586 scop->arrays = arrays;
2588 array = isl_calloc_type(ctx, struct pet_array);
2589 if (!array)
2590 goto error;
2592 array->extent = isl_map_range(isl_map_copy(access));
2593 dim = isl_space_params_alloc(ctx, 0);
2594 array->context = isl_set_universe(dim);
2595 dim = isl_space_set_alloc(ctx, 0, 1);
2596 array->value_bounds = isl_set_universe(dim);
2597 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2598 isl_dim_set, 0, 0);
2599 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2600 isl_dim_set, 0, 1);
2601 array->element_type = strdup("int");
2603 scop->arrays[scop->n_array] = array;
2604 scop->n_array++;
2606 if (!array->extent || !array->context)
2607 goto error;
2609 return scop;
2610 error:
2611 pet_scop_free(scop);
2612 return NULL;
2615 extern "C" {
2616 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
2617 void *user);
2620 /* Apply the map pointed to by "user" to the domain of the access
2621 * relation, thereby embedding it in the range of the map.
2622 * The domain of both relations is the zero-dimensional domain.
2624 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
2626 isl_map *map = (isl_map *) user;
2628 return isl_map_apply_domain(access, isl_map_copy(map));
2631 /* Apply "map" to all access relations in "expr".
2633 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
2635 return pet_expr_foreach_access(expr, &embed_access, map);
2638 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2640 static int n_nested_parameter(__isl_keep isl_set *set)
2642 isl_space *space;
2643 int n;
2645 space = isl_set_get_space(set);
2646 n = n_nested_parameter(space);
2647 isl_space_free(space);
2649 return n;
2652 /* Remove all parameters from "map" that refer to nested accesses.
2654 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
2656 int nparam;
2657 isl_space *space;
2659 space = isl_map_get_space(map);
2660 nparam = isl_space_dim(space, isl_dim_param);
2661 for (int i = nparam - 1; i >= 0; --i)
2662 if (is_nested_parameter(space, i))
2663 map = isl_map_project_out(map, isl_dim_param, i, 1);
2664 isl_space_free(space);
2666 return map;
2669 extern "C" {
2670 static __isl_give isl_map *access_remove_nested_parameters(
2671 __isl_take isl_map *access, void *user);
2674 static __isl_give isl_map *access_remove_nested_parameters(
2675 __isl_take isl_map *access, void *user)
2677 return remove_nested_parameters(access);
2680 /* Remove all nested access parameters from the schedule and all
2681 * accesses of "stmt".
2682 * There is no need to remove them from the domain as these parameters
2683 * have already been removed from the domain when this function is called.
2685 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
2687 if (!stmt)
2688 return NULL;
2689 stmt->schedule = remove_nested_parameters(stmt->schedule);
2690 stmt->body = pet_expr_foreach_access(stmt->body,
2691 &access_remove_nested_parameters, NULL);
2692 if (!stmt->schedule || !stmt->body)
2693 goto error;
2694 for (int i = 0; i < stmt->n_arg; ++i) {
2695 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
2696 &access_remove_nested_parameters, NULL);
2697 if (!stmt->args[i])
2698 goto error;
2701 return stmt;
2702 error:
2703 pet_stmt_free(stmt);
2704 return NULL;
2707 /* For each nested access parameter in the domain of "stmt",
2708 * construct a corresponding pet_expr, place it in stmt->args and
2709 * record its position in "param2pos".
2710 * n is the number of nested access parameters.
2712 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
2713 std::map<int,int> &param2pos)
2715 isl_space *space;
2716 unsigned n_arg;
2717 struct pet_expr **args;
2719 n_arg = stmt->n_arg;
2720 args = isl_realloc_array(ctx, stmt->args, struct pet_expr *, n_arg + n);
2721 if (!args)
2722 goto error;
2723 stmt->args = args;
2724 stmt->n_arg += n;
2726 space = isl_set_get_space(stmt->domain);
2727 n = extract_nested(space, n_arg, stmt->args, param2pos);
2728 isl_space_free(space);
2730 if (n < 0)
2731 goto error;
2733 stmt->n_arg = n;
2734 return stmt;
2735 error:
2736 pet_stmt_free(stmt);
2737 return NULL;
2740 /* Look for parameters in the iteration domain of "stmt" taht
2741 * refer to nested accesses. In particular, these are
2742 * parameters with no name.
2744 * If there are any such parameters, then as many extra variables
2745 * (after identifying identical nested accesses) are added to the
2746 * range of the map wrapped inside the domain.
2747 * If the original domain is not a wrapped map, then a new wrapped
2748 * map is created with zero output dimensions.
2749 * The parameters are then equated to the corresponding output dimensions
2750 * and subsequently projected out, from the iteration domain,
2751 * the schedule and the access relations.
2752 * For each of the output dimensions, a corresponding argument
2753 * expression is added. Initially they are created with
2754 * a zero-dimensional domain, so they have to be embedded
2755 * in the current iteration domain.
2756 * param2pos maps the position of the parameter to the position
2757 * of the corresponding output dimension in the wrapped map.
2759 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
2761 int n;
2762 int nparam;
2763 unsigned n_arg;
2764 isl_map *map;
2765 std::map<int,int> param2pos;
2767 if (!stmt)
2768 return NULL;
2770 n = n_nested_parameter(stmt->domain);
2771 if (n == 0)
2772 return stmt;
2774 n_arg = stmt->n_arg;
2775 stmt = extract_nested(stmt, n, param2pos);
2776 if (!stmt)
2777 return NULL;
2779 n = stmt->n_arg - n_arg;
2780 nparam = isl_set_dim(stmt->domain, isl_dim_param);
2781 if (isl_set_is_wrapping(stmt->domain))
2782 map = isl_set_unwrap(stmt->domain);
2783 else
2784 map = isl_map_from_domain(stmt->domain);
2785 map = isl_map_add_dims(map, isl_dim_out, n);
2787 for (int i = nparam - 1; i >= 0; --i) {
2788 isl_id *id;
2790 if (!is_nested_parameter(map, i))
2791 continue;
2793 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
2794 isl_dim_out);
2795 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
2796 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
2797 param2pos[i]);
2798 map = isl_map_project_out(map, isl_dim_param, i, 1);
2801 stmt->domain = isl_map_wrap(map);
2803 map = isl_set_unwrap(isl_set_copy(stmt->domain));
2804 map = isl_map_from_range(isl_map_domain(map));
2805 for (int pos = n_arg; pos < stmt->n_arg; ++pos)
2806 stmt->args[pos] = embed(stmt->args[pos], map);
2807 isl_map_free(map);
2809 stmt = remove_nested_parameters(stmt);
2811 return stmt;
2812 error:
2813 pet_stmt_free(stmt);
2814 return NULL;
2817 /* For each statement in "scop", move the parameters that correspond
2818 * to nested access into the ranges of the domains and create
2819 * corresponding argument expressions.
2821 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
2823 if (!scop)
2824 return NULL;
2826 for (int i = 0; i < scop->n_stmt; ++i) {
2827 scop->stmts[i] = resolve_nested(scop->stmts[i]);
2828 if (!scop->stmts[i])
2829 goto error;
2832 return scop;
2833 error:
2834 pet_scop_free(scop);
2835 return NULL;
2838 /* Does "space" involve any parameters that refer to nested
2839 * accesses, i.e., parameters with no name?
2841 static bool has_nested(__isl_keep isl_space *space)
2843 int nparam;
2845 nparam = isl_space_dim(space, isl_dim_param);
2846 for (int i = 0; i < nparam; ++i)
2847 if (is_nested_parameter(space, i))
2848 return true;
2850 return false;
2853 /* Does "set" involve any parameters that refer to nested
2854 * accesses, i.e., parameters with no name?
2856 static bool has_nested(__isl_keep isl_set *set)
2858 isl_space *space;
2859 bool nested;
2861 space = isl_set_get_space(set);
2862 nested = has_nested(space);
2863 isl_space_free(space);
2865 return nested;
2868 /* Given an access expression "expr", is the variable accessed by
2869 * "expr" assigned anywhere inside "scop"?
2871 static bool is_assigned(pet_expr *expr, pet_scop *scop)
2873 bool assigned = false;
2874 isl_id *id;
2876 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
2877 assigned = pet_scop_writes(scop, id);
2878 isl_id_free(id);
2880 return assigned;
2883 /* Are all nested access parameters in "set" allowed given "scop".
2884 * In particular, is none of them written by anywhere inside "scop".
2886 bool PetScan::is_nested_allowed(__isl_keep isl_set *set, pet_scop *scop)
2888 int nparam;
2890 nparam = isl_set_dim(set, isl_dim_param);
2891 for (int i = 0; i < nparam; ++i) {
2892 Expr *nested;
2893 isl_id *id = isl_set_get_dim_id(set, isl_dim_param, i);
2894 pet_expr *expr;
2895 bool allowed;
2897 if (!is_nested_parameter(id)) {
2898 isl_id_free(id);
2899 continue;
2902 nested = (Expr *) isl_id_get_user(id);
2903 expr = extract_expr(nested);
2904 allowed = expr && expr->type == pet_expr_access &&
2905 !is_assigned(expr, scop);
2907 pet_expr_free(expr);
2908 isl_id_free(id);
2910 if (!allowed)
2911 return false;
2914 return true;
2917 /* Construct a pet_scop for an if statement.
2919 * If the condition fits the pattern of a conditional assignment,
2920 * then it is handled by extract_conditional_assignment.
2921 * Otherwise, we do the following.
2923 * If the condition is affine, then the condition is added
2924 * to the iteration domains of the then branch, while the
2925 * opposite of the condition in added to the iteration domains
2926 * of the else branch, if any.
2927 * We allow the condition to be dynamic, i.e., to refer to
2928 * scalars or array elements that may be written to outside
2929 * of the given if statement. These nested accesses are then represented
2930 * as output dimensions in the wrapping iteration domain.
2931 * If it also written _inside_ the then or else branch, then
2932 * we treat the condition as non-affine.
2933 * As explained below, this will introduce an extra statement.
2934 * For aesthetic reasons, we want this statement to have a statement
2935 * number that is lower than those of the then and else branches.
2936 * In order to evaluate if will need such a statement, however, we
2937 * first construct scops for the then and else branches.
2938 * We therefore reserve a statement number if we might have to
2939 * introduce such an extra statement.
2941 * If the condition is not affine, then we create a separate
2942 * statement that write the result of the condition to a virtual scalar.
2943 * A constraint requiring the value of this virtual scalar to be one
2944 * is added to the iteration domains of the then branch.
2945 * Similarly, a constraint requiring the value of this virtual scalar
2946 * to be zero is added to the iteration domains of the else branch, if any.
2947 * We adjust the schedules to ensure that the virtual scalar is written
2948 * before it is read.
2950 struct pet_scop *PetScan::extract(IfStmt *stmt)
2952 struct pet_scop *scop_then, *scop_else, *scop;
2953 assigned_value_cache cache(assigned_value);
2954 isl_map *test_access = NULL;
2955 isl_set *cond;
2956 int stmt_id;
2958 scop = extract_conditional_assignment(stmt);
2959 if (scop)
2960 return scop;
2962 cond = try_extract_nested_condition(stmt->getCond());
2963 if (allow_nested && (!cond || has_nested(cond)))
2964 stmt_id = n_stmt++;
2966 scop_then = extract(stmt->getThen());
2968 if (stmt->getElse()) {
2969 scop_else = extract(stmt->getElse());
2970 if (autodetect) {
2971 if (scop_then && !scop_else) {
2972 partial = true;
2973 isl_set_free(cond);
2974 return scop_then;
2976 if (!scop_then && scop_else) {
2977 partial = true;
2978 isl_set_free(cond);
2979 return scop_else;
2984 if (cond &&
2985 (!is_nested_allowed(cond, scop_then) ||
2986 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
2987 isl_set_free(cond);
2988 cond = NULL;
2990 if (allow_nested && !cond) {
2991 int save_n_stmt = n_stmt;
2992 test_access = create_test_access(ctx, n_test++);
2993 n_stmt = stmt_id;
2994 scop = extract_non_affine_condition(stmt->getCond(),
2995 isl_map_copy(test_access));
2996 n_stmt = save_n_stmt;
2997 scop = scop_add_array(scop, test_access);
2998 if (!scop) {
2999 pet_scop_free(scop_then);
3000 pet_scop_free(scop_else);
3001 isl_map_free(test_access);
3002 return NULL;
3006 if (!scop) {
3007 if (!cond)
3008 cond = extract_condition(stmt->getCond());
3009 scop = pet_scop_restrict(scop_then, isl_set_copy(cond));
3011 if (stmt->getElse()) {
3012 cond = isl_set_complement(cond);
3013 scop_else = pet_scop_restrict(scop_else, cond);
3014 scop = pet_scop_add(ctx, scop, scop_else);
3015 } else
3016 isl_set_free(cond);
3017 scop = resolve_nested(scop);
3018 } else {
3019 scop = pet_scop_prefix(scop, 0);
3020 scop_then = pet_scop_prefix(scop_then, 1);
3021 scop_then = pet_scop_filter(scop_then,
3022 isl_map_copy(test_access), 1);
3023 scop = pet_scop_add(ctx, scop, scop_then);
3024 if (stmt->getElse()) {
3025 scop_else = pet_scop_prefix(scop_else, 1);
3026 scop_else = pet_scop_filter(scop_else, test_access, 0);
3027 scop = pet_scop_add(ctx, scop, scop_else);
3028 } else
3029 isl_map_free(test_access);
3032 return scop;
3035 /* Try and construct a pet_scop for a label statement.
3036 * We currently only allow labels on expression statements.
3038 struct pet_scop *PetScan::extract(LabelStmt *stmt)
3040 isl_id *label;
3041 Stmt *sub;
3043 sub = stmt->getSubStmt();
3044 if (!isa<Expr>(sub)) {
3045 unsupported(stmt);
3046 return NULL;
3049 label = isl_id_alloc(ctx, stmt->getName(), NULL);
3051 return extract(sub, extract_expr(cast<Expr>(sub)), label);
3054 /* Try and construct a pet_scop corresponding to "stmt".
3056 struct pet_scop *PetScan::extract(Stmt *stmt)
3058 if (isa<Expr>(stmt))
3059 return extract(stmt, extract_expr(cast<Expr>(stmt)));
3061 switch (stmt->getStmtClass()) {
3062 case Stmt::WhileStmtClass:
3063 return extract(cast<WhileStmt>(stmt));
3064 case Stmt::ForStmtClass:
3065 return extract_for(cast<ForStmt>(stmt));
3066 case Stmt::IfStmtClass:
3067 return extract(cast<IfStmt>(stmt));
3068 case Stmt::CompoundStmtClass:
3069 return extract(cast<CompoundStmt>(stmt));
3070 case Stmt::LabelStmtClass:
3071 return extract(cast<LabelStmt>(stmt));
3072 default:
3073 unsupported(stmt);
3076 return NULL;
3079 /* Try and construct a pet_scop corresponding to (part of)
3080 * a sequence of statements.
3082 struct pet_scop *PetScan::extract(StmtRange stmt_range)
3084 pet_scop *scop;
3085 StmtIterator i;
3086 int j;
3087 bool partial_range = false;
3089 scop = pet_scop_empty(ctx);
3090 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
3091 Stmt *child = *i;
3092 struct pet_scop *scop_i;
3093 scop_i = extract(child);
3094 if (scop && partial) {
3095 pet_scop_free(scop_i);
3096 break;
3098 scop_i = pet_scop_prefix(scop_i, j);
3099 if (autodetect) {
3100 if (scop_i)
3101 scop = pet_scop_add(ctx, scop, scop_i);
3102 else
3103 partial_range = true;
3104 if (scop->n_stmt != 0 && !scop_i)
3105 partial = true;
3106 } else {
3107 scop = pet_scop_add(ctx, scop, scop_i);
3109 if (partial)
3110 break;
3113 if (scop && partial_range)
3114 partial = true;
3116 return scop;
3119 /* Check if the scop marked by the user is exactly this Stmt
3120 * or part of this Stmt.
3121 * If so, return a pet_scop corresponding to the marked region.
3122 * Otherwise, return NULL.
3124 struct pet_scop *PetScan::scan(Stmt *stmt)
3126 SourceManager &SM = PP.getSourceManager();
3127 unsigned start_off, end_off;
3129 start_off = SM.getFileOffset(stmt->getLocStart());
3130 end_off = SM.getFileOffset(stmt->getLocEnd());
3132 if (start_off > loc.end)
3133 return NULL;
3134 if (end_off < loc.start)
3135 return NULL;
3136 if (start_off >= loc.start && end_off <= loc.end) {
3137 return extract(stmt);
3140 StmtIterator start;
3141 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
3142 Stmt *child = *start;
3143 if (!child)
3144 continue;
3145 start_off = SM.getFileOffset(child->getLocStart());
3146 end_off = SM.getFileOffset(child->getLocEnd());
3147 if (start_off < loc.start && end_off > loc.end)
3148 return scan(child);
3149 if (start_off >= loc.start)
3150 break;
3153 StmtIterator end;
3154 for (end = start; end != stmt->child_end(); ++end) {
3155 Stmt *child = *end;
3156 start_off = SM.getFileOffset(child->getLocStart());
3157 if (start_off >= loc.end)
3158 break;
3161 return extract(StmtRange(start, end));
3164 /* Set the size of index "pos" of "array" to "size".
3165 * In particular, add a constraint of the form
3167 * i_pos < size
3169 * to array->extent and a constraint of the form
3171 * size >= 0
3173 * to array->context.
3175 static struct pet_array *update_size(struct pet_array *array, int pos,
3176 __isl_take isl_pw_aff *size)
3178 isl_set *valid;
3179 isl_set *univ;
3180 isl_set *bound;
3181 isl_space *dim;
3182 isl_aff *aff;
3183 isl_pw_aff *index;
3184 isl_id *id;
3186 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
3187 array->context = isl_set_intersect(array->context, valid);
3189 dim = isl_set_get_space(array->extent);
3190 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
3191 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
3192 univ = isl_set_universe(isl_aff_get_domain_space(aff));
3193 index = isl_pw_aff_alloc(univ, aff);
3195 size = isl_pw_aff_add_dims(size, isl_dim_in,
3196 isl_set_dim(array->extent, isl_dim_set));
3197 id = isl_set_get_tuple_id(array->extent);
3198 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
3199 bound = isl_pw_aff_lt_set(index, size);
3201 array->extent = isl_set_intersect(array->extent, bound);
3203 if (!array->context || !array->extent)
3204 goto error;
3206 return array;
3207 error:
3208 pet_array_free(array);
3209 return NULL;
3212 /* Figure out the size of the array at position "pos" and all
3213 * subsequent positions from "type" and update "array" accordingly.
3215 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
3216 const Type *type, int pos)
3218 const ArrayType *atype;
3219 isl_pw_aff *size;
3221 if (!array)
3222 return NULL;
3224 if (type->isPointerType()) {
3225 type = type->getPointeeType().getTypePtr();
3226 return set_upper_bounds(array, type, pos + 1);
3228 if (!type->isArrayType())
3229 return array;
3231 type = type->getCanonicalTypeInternal().getTypePtr();
3232 atype = cast<ArrayType>(type);
3234 if (type->isConstantArrayType()) {
3235 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
3236 size = extract_affine(ca->getSize());
3237 array = update_size(array, pos, size);
3238 } else if (type->isVariableArrayType()) {
3239 const VariableArrayType *vla = cast<VariableArrayType>(atype);
3240 size = extract_affine(vla->getSizeExpr());
3241 array = update_size(array, pos, size);
3244 type = atype->getElementType().getTypePtr();
3246 return set_upper_bounds(array, type, pos + 1);
3249 /* Construct and return a pet_array corresponding to the variable "decl".
3250 * In particular, initialize array->extent to
3252 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3254 * and then call set_upper_bounds to set the upper bounds on the indices
3255 * based on the type of the variable.
3257 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
3259 struct pet_array *array;
3260 QualType qt = decl->getType();
3261 const Type *type = qt.getTypePtr();
3262 int depth = array_depth(type);
3263 QualType base = base_type(qt);
3264 string name;
3265 isl_id *id;
3266 isl_space *dim;
3268 array = isl_calloc_type(ctx, struct pet_array);
3269 if (!array)
3270 return NULL;
3272 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
3273 dim = isl_space_set_alloc(ctx, 0, depth);
3274 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
3276 array->extent = isl_set_nat_universe(dim);
3278 dim = isl_space_params_alloc(ctx, 0);
3279 array->context = isl_set_universe(dim);
3281 array = set_upper_bounds(array, type, 0);
3282 if (!array)
3283 return NULL;
3285 name = base.getAsString();
3286 array->element_type = strdup(name.c_str());
3288 return array;
3291 /* Construct a list of pet_arrays, one for each array (or scalar)
3292 * accessed inside "scop" add this list to "scop" and return the result.
3294 * The context of "scop" is updated with the intesection of
3295 * the contexts of all arrays, i.e., constraints on the parameters
3296 * that ensure that the arrays have a valid (non-negative) size.
3298 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
3300 int i;
3301 set<ValueDecl *> arrays;
3302 set<ValueDecl *>::iterator it;
3303 int n_array;
3304 struct pet_array **scop_arrays;
3306 if (!scop)
3307 return NULL;
3309 pet_scop_collect_arrays(scop, arrays);
3310 if (arrays.size() == 0)
3311 return scop;
3313 n_array = scop->n_array;
3315 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3316 n_array + arrays.size());
3317 if (!scop_arrays)
3318 goto error;
3319 scop->arrays = scop_arrays;
3321 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3322 struct pet_array *array;
3323 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
3324 if (!scop->arrays[n_array + i])
3325 goto error;
3326 scop->n_array++;
3327 scop->context = isl_set_intersect(scop->context,
3328 isl_set_copy(array->context));
3329 if (!scop->context)
3330 goto error;
3333 return scop;
3334 error:
3335 pet_scop_free(scop);
3336 return NULL;
3339 /* Construct a pet_scop from the given function.
3341 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3343 pet_scop *scop;
3344 Stmt *stmt;
3346 stmt = fd->getBody();
3348 if (autodetect)
3349 scop = extract(stmt);
3350 else
3351 scop = scan(stmt);
3352 scop = pet_scop_detect_parameter_accesses(scop);
3353 scop = scan_arrays(scop);
3355 return scop;