scan.cc: fix typos in comments
[pet.git] / scan.cc
blob9a6ec40894745cb34e19eae0ffdebaefca396af4
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, const char *msg)
246 if (autodetect)
247 return;
249 SourceLocation loc = stmt->getLocStart();
250 DiagnosticsEngine &diag = PP.getDiagnostics();
251 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
252 msg ? msg : "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;
1330 pet_expr *main_arg;
1332 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1333 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1334 arg = ice->getSubExpr();
1336 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1337 UnaryOperator *op = cast<UnaryOperator>(arg);
1338 if (op->getOpcode() == UO_AddrOf) {
1339 is_addr = 1;
1340 arg = op->getSubExpr();
1343 res->args[i] = PetScan::extract_expr(arg);
1344 main_arg = res->args[i];
1345 if (is_addr)
1346 res->args[i] = pet_expr_new_unary(ctx,
1347 pet_op_address_of, res->args[i]);
1348 if (!res->args[i])
1349 goto error;
1350 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1351 array_depth(arg->getType().getTypePtr()) > 0)
1352 is_addr = 1;
1353 if (is_addr && main_arg->type == pet_expr_access) {
1354 ParmVarDecl *parm;
1355 if (!fd->hasPrototype()) {
1356 unsupported(expr, "prototype required");
1357 goto error;
1359 parm = fd->getParamDecl(i);
1360 if (!const_base(parm->getType()))
1361 mark_write(main_arg);
1365 return res;
1366 error:
1367 pet_expr_free(res);
1368 return NULL;
1371 /* Try and onstruct a pet_expr representing "expr".
1373 struct pet_expr *PetScan::extract_expr(Expr *expr)
1375 switch (expr->getStmtClass()) {
1376 case Stmt::UnaryOperatorClass:
1377 return extract_expr(cast<UnaryOperator>(expr));
1378 case Stmt::CompoundAssignOperatorClass:
1379 case Stmt::BinaryOperatorClass:
1380 return extract_expr(cast<BinaryOperator>(expr));
1381 case Stmt::ImplicitCastExprClass:
1382 return extract_expr(cast<ImplicitCastExpr>(expr));
1383 case Stmt::ArraySubscriptExprClass:
1384 case Stmt::DeclRefExprClass:
1385 case Stmt::IntegerLiteralClass:
1386 return extract_access_expr(expr);
1387 case Stmt::FloatingLiteralClass:
1388 return extract_expr(cast<FloatingLiteral>(expr));
1389 case Stmt::ParenExprClass:
1390 return extract_expr(cast<ParenExpr>(expr));
1391 case Stmt::ConditionalOperatorClass:
1392 return extract_expr(cast<ConditionalOperator>(expr));
1393 case Stmt::CallExprClass:
1394 return extract_expr(cast<CallExpr>(expr));
1395 default:
1396 unsupported(expr);
1398 return NULL;
1401 /* Check if the given initialization statement is an assignment.
1402 * If so, return that assignment. Otherwise return NULL.
1404 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1406 BinaryOperator *ass;
1408 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1409 return NULL;
1411 ass = cast<BinaryOperator>(init);
1412 if (ass->getOpcode() != BO_Assign)
1413 return NULL;
1415 return ass;
1418 /* Check if the given initialization statement is a declaration
1419 * of a single variable.
1420 * If so, return that declaration. Otherwise return NULL.
1422 Decl *PetScan::initialization_declaration(Stmt *init)
1424 DeclStmt *decl;
1426 if (init->getStmtClass() != Stmt::DeclStmtClass)
1427 return NULL;
1429 decl = cast<DeclStmt>(init);
1431 if (!decl->isSingleDecl())
1432 return NULL;
1434 return decl->getSingleDecl();
1437 /* Given the assignment operator in the initialization of a for loop,
1438 * extract the induction variable, i.e., the (integer)variable being
1439 * assigned.
1441 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1443 Expr *lhs;
1444 DeclRefExpr *ref;
1445 ValueDecl *decl;
1446 const Type *type;
1448 lhs = init->getLHS();
1449 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1450 unsupported(init);
1451 return NULL;
1454 ref = cast<DeclRefExpr>(lhs);
1455 decl = ref->getDecl();
1456 type = decl->getType().getTypePtr();
1458 if (!type->isIntegerType()) {
1459 unsupported(lhs);
1460 return NULL;
1463 return decl;
1466 /* Given the initialization statement of a for loop and the single
1467 * declaration in this initialization statement,
1468 * extract the induction variable, i.e., the (integer) variable being
1469 * declared.
1471 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1473 VarDecl *vd;
1475 vd = cast<VarDecl>(decl);
1477 const QualType type = vd->getType();
1478 if (!type->isIntegerType()) {
1479 unsupported(init);
1480 return NULL;
1483 if (!vd->getInit()) {
1484 unsupported(init);
1485 return NULL;
1488 return vd;
1491 /* Check that op is of the form iv++ or iv--.
1492 * "inc" is accordingly set to 1 or -1.
1494 bool PetScan::check_unary_increment(UnaryOperator *op, clang::ValueDecl *iv,
1495 isl_int &inc)
1497 Expr *sub;
1498 DeclRefExpr *ref;
1500 if (!op->isIncrementDecrementOp()) {
1501 unsupported(op);
1502 return false;
1505 if (op->isIncrementOp())
1506 isl_int_set_si(inc, 1);
1507 else
1508 isl_int_set_si(inc, -1);
1510 sub = op->getSubExpr();
1511 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1512 unsupported(op);
1513 return false;
1516 ref = cast<DeclRefExpr>(sub);
1517 if (ref->getDecl() != iv) {
1518 unsupported(op);
1519 return false;
1522 return true;
1525 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1526 * has a single constant expression on a universe domain, then
1527 * put this constant in *user.
1529 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1530 void *user)
1532 isl_int *inc = (isl_int *)user;
1533 int res = 0;
1535 if (!isl_set_plain_is_universe(set) || !isl_aff_is_cst(aff))
1536 res = -1;
1537 else
1538 isl_aff_get_constant(aff, inc);
1540 isl_set_free(set);
1541 isl_aff_free(aff);
1543 return res;
1546 /* Check if op is of the form
1548 * iv = iv + inc
1550 * with inc a constant and set "inc" accordingly.
1552 * We extract an affine expression from the RHS and the subtract iv.
1553 * The result should be a constant.
1555 bool PetScan::check_binary_increment(BinaryOperator *op, clang::ValueDecl *iv,
1556 isl_int &inc)
1558 Expr *lhs;
1559 DeclRefExpr *ref;
1560 isl_id *id;
1561 isl_space *dim;
1562 isl_aff *aff;
1563 isl_pw_aff *val;
1565 if (op->getOpcode() != BO_Assign) {
1566 unsupported(op);
1567 return false;
1570 lhs = op->getLHS();
1571 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1572 unsupported(op);
1573 return false;
1576 ref = cast<DeclRefExpr>(lhs);
1577 if (ref->getDecl() != iv) {
1578 unsupported(op);
1579 return false;
1582 val = extract_affine(op->getRHS());
1584 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1586 dim = isl_space_params_alloc(ctx, 1);
1587 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1588 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1589 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1591 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1593 if (isl_pw_aff_foreach_piece(val, &extract_cst, &inc) < 0) {
1594 isl_pw_aff_free(val);
1595 unsupported(op);
1596 return false;
1599 isl_pw_aff_free(val);
1601 return true;
1604 /* Check that op is of the form iv += cst or iv -= cst.
1605 * "inc" is set to cst or -cst accordingly.
1607 bool PetScan::check_compound_increment(CompoundAssignOperator *op,
1608 clang::ValueDecl *iv, isl_int &inc)
1610 Expr *lhs, *rhs;
1611 DeclRefExpr *ref;
1612 bool neg = false;
1614 BinaryOperatorKind opcode;
1616 opcode = op->getOpcode();
1617 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1618 unsupported(op);
1619 return false;
1621 if (opcode == BO_SubAssign)
1622 neg = true;
1624 lhs = op->getLHS();
1625 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1626 unsupported(op);
1627 return false;
1630 ref = cast<DeclRefExpr>(lhs);
1631 if (ref->getDecl() != iv) {
1632 unsupported(op);
1633 return false;
1636 rhs = op->getRHS();
1638 if (rhs->getStmtClass() == Stmt::UnaryOperatorClass) {
1639 UnaryOperator *op = cast<UnaryOperator>(rhs);
1640 if (op->getOpcode() != UO_Minus) {
1641 unsupported(op);
1642 return false;
1645 neg = !neg;
1647 rhs = op->getSubExpr();
1650 if (rhs->getStmtClass() != Stmt::IntegerLiteralClass) {
1651 unsupported(op);
1652 return false;
1655 extract_int(cast<IntegerLiteral>(rhs), &inc);
1656 if (neg)
1657 isl_int_neg(inc, inc);
1659 return true;
1662 /* Check that the increment of the given for loop increments
1663 * (or decrements) the induction variable "iv".
1664 * "up" is set to true if the induction variable is incremented.
1666 bool PetScan::check_increment(ForStmt *stmt, ValueDecl *iv, isl_int &v)
1668 Stmt *inc = stmt->getInc();
1670 if (!inc) {
1671 unsupported(stmt);
1672 return false;
1675 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1676 return check_unary_increment(cast<UnaryOperator>(inc), iv, v);
1677 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1678 return check_compound_increment(
1679 cast<CompoundAssignOperator>(inc), iv, v);
1680 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1681 return check_binary_increment(cast<BinaryOperator>(inc), iv, v);
1683 unsupported(inc);
1684 return false;
1687 /* Embed the given iteration domain in an extra outer loop
1688 * with induction variable "var".
1689 * If this variable appeared as a parameter in the constraints,
1690 * it is replaced by the new outermost dimension.
1692 static __isl_give isl_set *embed(__isl_take isl_set *set,
1693 __isl_take isl_id *var)
1695 int pos;
1697 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1698 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1699 if (pos >= 0) {
1700 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1701 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1704 isl_id_free(var);
1705 return set;
1708 /* Construct a pet_scop for an infinite loop around the given body.
1710 * We extract a pet_scop for the body and then embed it in a loop with
1711 * iteration domain
1713 * { [t] : t >= 0 }
1715 * and schedule
1717 * { [t] -> [t] }
1719 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1721 isl_id *id;
1722 isl_space *dim;
1723 isl_set *domain;
1724 isl_map *sched;
1725 struct pet_scop *scop;
1727 scop = extract(body);
1728 if (!scop)
1729 return NULL;
1731 id = isl_id_alloc(ctx, "t", NULL);
1732 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1733 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
1734 dim = isl_space_from_domain(isl_set_get_space(domain));
1735 dim = isl_space_add_dims(dim, isl_dim_out, 1);
1736 sched = isl_map_universe(dim);
1737 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
1738 scop = pet_scop_embed(scop, domain, sched, id);
1740 return scop;
1743 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1745 * for (;;)
1746 * body
1749 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1751 return extract_infinite_loop(stmt->getBody());
1754 /* Check if the while loop is of the form
1756 * while (1)
1757 * body
1759 * If so, construct a scop for an infinite loop around body.
1760 * Otherwise, fail.
1762 struct pet_scop *PetScan::extract(WhileStmt *stmt)
1764 Expr *cond;
1765 isl_set *set;
1766 int is_universe;
1768 cond = stmt->getCond();
1769 if (!cond) {
1770 unsupported(stmt);
1771 return NULL;
1774 set = extract_condition(cond);
1775 is_universe = isl_set_plain_is_universe(set);
1776 isl_set_free(set);
1778 if (!is_universe) {
1779 unsupported(stmt);
1780 return NULL;
1783 return extract_infinite_loop(stmt->getBody());
1786 /* Check whether "cond" expresses a simple loop bound
1787 * on the only set dimension.
1788 * In particular, if "up" is set then "cond" should contain only
1789 * upper bounds on the set dimension.
1790 * Otherwise, it should contain only lower bounds.
1792 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
1794 if (isl_int_is_pos(inc))
1795 return !isl_set_dim_has_lower_bound(cond, isl_dim_set, 0);
1796 else
1797 return !isl_set_dim_has_upper_bound(cond, isl_dim_set, 0);
1800 /* Extend a condition on a given iteration of a loop to one that
1801 * imposes the same condition on all previous iterations.
1802 * "domain" expresses the lower [upper] bound on the iterations
1803 * when inc is positive [negative].
1805 * In particular, we construct the condition (when inc is positive)
1807 * forall i' : (domain(i') and i' <= i) => cond(i')
1809 * which is equivalent to
1811 * not exists i' : domain(i') and i' <= i and not cond(i')
1813 * We construct this set by negating cond, applying a map
1815 * { [i'] -> [i] : domain(i') and i' <= i }
1817 * and then negating the result again.
1819 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
1820 __isl_take isl_set *domain, isl_int inc)
1822 isl_map *previous_to_this;
1824 if (isl_int_is_pos(inc))
1825 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
1826 else
1827 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
1829 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
1831 cond = isl_set_complement(cond);
1832 cond = isl_set_apply(cond, previous_to_this);
1833 cond = isl_set_complement(cond);
1835 return cond;
1838 /* Construct a domain of the form
1840 * [id] -> { [] : exists a: id = init + a * inc and a >= 0 }
1842 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
1843 __isl_take isl_pw_aff *init, isl_int inc)
1845 isl_aff *aff;
1846 isl_space *dim;
1847 isl_set *set;
1849 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
1850 dim = isl_pw_aff_get_domain_space(init);
1851 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1852 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
1853 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
1855 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
1856 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1857 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1858 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1860 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
1862 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
1864 return isl_set_project_out(set, isl_dim_set, 0, 1);
1867 static unsigned get_type_size(ValueDecl *decl)
1869 return decl->getASTContext().getIntWidth(decl->getType());
1872 /* Assuming "cond" represents a simple bound on a loop where the loop
1873 * iterator "iv" is incremented (or decremented) by one, check if wrapping
1874 * is possible.
1876 * Under the given assumptions, wrapping is only possible if "cond" allows
1877 * for the last value before wrapping, i.e., 2^width - 1 in case of an
1878 * increasing iterator and 0 in case of a decreasing iterator.
1880 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
1882 bool cw;
1883 isl_int limit;
1884 isl_set *test;
1886 test = isl_set_copy(cond);
1888 isl_int_init(limit);
1889 if (isl_int_is_neg(inc))
1890 isl_int_set_si(limit, 0);
1891 else {
1892 isl_int_set_si(limit, 1);
1893 isl_int_mul_2exp(limit, limit, get_type_size(iv));
1894 isl_int_sub_ui(limit, limit, 1);
1897 test = isl_set_fix(cond, isl_dim_set, 0, limit);
1898 cw = !isl_set_is_empty(test);
1899 isl_set_free(test);
1901 isl_int_clear(limit);
1903 return cw;
1906 /* Given a one-dimensional space, construct the following mapping on this
1907 * space
1909 * { [v] -> [v mod 2^width] }
1911 * where width is the number of bits used to represent the values
1912 * of the unsigned variable "iv".
1914 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
1915 ValueDecl *iv)
1917 isl_int mod;
1918 isl_aff *aff;
1919 isl_map *map;
1921 isl_int_init(mod);
1922 isl_int_set_si(mod, 1);
1923 isl_int_mul_2exp(mod, mod, get_type_size(iv));
1925 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1926 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1927 aff = isl_aff_mod(aff, mod);
1929 isl_int_clear(mod);
1931 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
1932 map = isl_map_reverse(map);
1935 /* Construct a pet_scop for a for statement.
1936 * The for loop is required to be of the form
1938 * for (i = init; condition; ++i)
1940 * or
1942 * for (i = init; condition; --i)
1944 * The initialization of the for loop should either be an assignment
1945 * to an integer variable, or a declaration of such a variable with
1946 * initialization.
1948 * The condition is allowed to contain nested accesses, provided
1949 * they are not being written to inside the body of the loop.
1951 * We extract a pet_scop for the body and then embed it in a loop with
1952 * iteration domain and schedule
1954 * { [i] : i >= init and condition' }
1955 * { [i] -> [i] }
1957 * or
1959 * { [i] : i <= init and condition' }
1960 * { [i] -> [-i] }
1962 * Where condition' is equal to condition if the latter is
1963 * a simple upper [lower] bound and a condition that is extended
1964 * to apply to all previous iterations otherwise.
1966 * If the stride of the loop is not 1, then "i >= init" is replaced by
1968 * (exists a: i = init + stride * a and a >= 0)
1970 * If the loop iterator i is unsigned, then wrapping may occur.
1971 * During the computation, we work with a virtual iterator that
1972 * does not wrap. However, the condition in the code applies
1973 * to the wrapped value, so we need to change condition(i)
1974 * into condition([i % 2^width]).
1975 * After computing the virtual domain and schedule, we apply
1976 * the function { [v] -> [v % 2^width] } to the domain and the domain
1977 * of the schedule. In order not to lose any information, we also
1978 * need to intersect the domain of the schedule with the virtual domain
1979 * first, since some iterations in the wrapped domain may be scheduled
1980 * several times, typically an infinite number of times.
1981 * Note that there is no need to perform this final wrapping
1982 * if the loop condition (after wrapping) is simple.
1984 * Wrapping on unsigned iterators can be avoided entirely if
1985 * loop condition is simple, the loop iterator is incremented
1986 * [decremented] by one and the last value before wrapping cannot
1987 * possibly satisfy the loop condition.
1989 * Before extracting a pet_scop from the body we remove all
1990 * assignments in assigned_value to variables that are assigned
1991 * somewhere in the body of the loop.
1993 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
1995 BinaryOperator *ass;
1996 Decl *decl;
1997 Stmt *init;
1998 Expr *lhs, *rhs;
1999 ValueDecl *iv;
2000 isl_space *dim;
2001 isl_set *domain;
2002 isl_map *sched;
2003 isl_set *cond = NULL;
2004 isl_id *id;
2005 struct pet_scop *scop;
2006 assigned_value_cache cache(assigned_value);
2007 isl_int inc;
2008 bool is_one;
2009 bool is_unsigned;
2010 bool is_simple;
2011 isl_map *wrap = NULL;
2013 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2014 return extract_infinite_for(stmt);
2016 init = stmt->getInit();
2017 if (!init) {
2018 unsupported(stmt);
2019 return NULL;
2021 if ((ass = initialization_assignment(init)) != NULL) {
2022 iv = extract_induction_variable(ass);
2023 if (!iv)
2024 return NULL;
2025 lhs = ass->getLHS();
2026 rhs = ass->getRHS();
2027 } else if ((decl = initialization_declaration(init)) != NULL) {
2028 VarDecl *var = extract_induction_variable(init, decl);
2029 if (!var)
2030 return NULL;
2031 iv = var;
2032 rhs = var->getInit();
2033 lhs = DeclRefExpr::Create(iv->getASTContext(),
2034 var->getQualifierLoc(), iv, var->getInnerLocStart(),
2035 var->getType(), VK_LValue);
2036 } else {
2037 unsupported(stmt->getInit());
2038 return NULL;
2041 isl_int_init(inc);
2042 if (!check_increment(stmt, iv, inc)) {
2043 isl_int_clear(inc);
2044 return NULL;
2047 is_unsigned = iv->getType()->isUnsignedIntegerType();
2049 assigned_value.erase(iv);
2050 clear_assignments clear(assigned_value);
2051 clear.TraverseStmt(stmt->getBody());
2053 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2055 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
2056 if (is_one)
2057 domain = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
2058 lhs, rhs, init);
2059 else {
2060 isl_pw_aff *lb = extract_affine(rhs);
2061 domain = strided_domain(isl_id_copy(id), lb, inc);
2064 scop = extract(stmt->getBody());
2066 cond = try_extract_nested_condition(stmt->getCond());
2067 if (cond && !is_nested_allowed(cond, scop)) {
2068 isl_set_free(cond);
2069 cond = NULL;
2072 if (!cond)
2073 cond = extract_condition(stmt->getCond());
2074 cond = embed(cond, isl_id_copy(id));
2075 domain = embed(domain, isl_id_copy(id));
2076 is_simple = is_simple_bound(cond, inc);
2077 if (is_unsigned &&
2078 (!is_simple || !is_one || can_wrap(cond, iv, inc))) {
2079 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2080 cond = isl_set_apply(cond, isl_map_reverse(isl_map_copy(wrap)));
2081 is_simple = is_simple && is_simple_bound(cond, inc);
2083 if (!is_simple)
2084 cond = valid_for_each_iteration(cond,
2085 isl_set_copy(domain), inc);
2086 domain = isl_set_intersect(domain, cond);
2087 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2088 dim = isl_space_from_domain(isl_set_get_space(domain));
2089 dim = isl_space_add_dims(dim, isl_dim_out, 1);
2090 sched = isl_map_universe(dim);
2091 if (isl_int_is_pos(inc))
2092 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2093 else
2094 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2096 if (is_unsigned && !is_simple) {
2097 wrap = isl_map_set_dim_id(wrap,
2098 isl_dim_out, 0, isl_id_copy(id));
2099 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2100 domain = isl_set_apply(domain, isl_map_copy(wrap));
2101 sched = isl_map_apply_domain(sched, wrap);
2102 } else
2103 isl_map_free(wrap);
2105 scop = pet_scop_embed(scop, domain, sched, id);
2106 scop = resolve_nested(scop);
2107 clear_assignment(assigned_value, iv);
2109 isl_int_clear(inc);
2110 return scop;
2113 struct pet_scop *PetScan::extract(CompoundStmt *stmt)
2115 return extract(stmt->children());
2118 /* Does "id" refer to a nested access?
2120 static bool is_nested_parameter(__isl_keep isl_id *id)
2122 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2125 /* Does parameter "pos" of "space" refer to a nested access?
2127 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2129 bool nested;
2130 isl_id *id;
2132 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2133 nested = is_nested_parameter(id);
2134 isl_id_free(id);
2136 return nested;
2139 /* Does parameter "pos" of "map" refer to a nested access?
2141 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2143 bool nested;
2144 isl_id *id;
2146 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2147 nested = is_nested_parameter(id);
2148 isl_id_free(id);
2150 return nested;
2153 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2155 static int n_nested_parameter(__isl_keep isl_space *space)
2157 int n = 0;
2158 int nparam;
2160 nparam = isl_space_dim(space, isl_dim_param);
2161 for (int i = 0; i < nparam; ++i)
2162 if (is_nested_parameter(space, i))
2163 ++n;
2165 return n;
2168 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2170 static int n_nested_parameter(__isl_keep isl_map *map)
2172 isl_space *space;
2173 int n;
2175 space = isl_map_get_space(map);
2176 n = n_nested_parameter(space);
2177 isl_space_free(space);
2179 return n;
2182 /* For each nested access parameter in "space",
2183 * construct a corresponding pet_expr, place it in args and
2184 * record its position in "param2pos".
2185 * "n_arg" is the number of elements that are already in args.
2186 * The position recorded in "param2pos" takes this number into account.
2187 * If the pet_expr corresponding to a parameter is identical to
2188 * the pet_expr corresponding to an earlier parameter, then these two
2189 * parameters are made to refer to the same element in args.
2191 * Return the final number of elements in args or -1 if an error has occurred.
2193 int PetScan::extract_nested(__isl_keep isl_space *space,
2194 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
2196 int nparam;
2198 nparam = isl_space_dim(space, isl_dim_param);
2199 for (int i = 0; i < nparam; ++i) {
2200 int j;
2201 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2202 Expr *nested;
2204 if (!is_nested_parameter(id)) {
2205 isl_id_free(id);
2206 continue;
2209 nested = (Expr *) isl_id_get_user(id);
2210 args[n_arg] = extract_expr(nested);
2211 if (!args[n_arg])
2212 return -1;
2214 for (j = 0; j < n_arg; ++j)
2215 if (pet_expr_is_equal(args[j], args[n_arg]))
2216 break;
2218 if (j < n_arg) {
2219 pet_expr_free(args[n_arg]);
2220 args[n_arg] = NULL;
2221 param2pos[i] = j;
2222 } else
2223 param2pos[i] = n_arg++;
2225 isl_id_free(id);
2228 return n_arg;
2231 /* For each nested access parameter in the access relations in "expr",
2232 * construct a corresponding pet_expr, place it in expr->args and
2233 * record its position in "param2pos".
2234 * n is the number of nested access parameters.
2236 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
2237 std::map<int,int> &param2pos)
2239 isl_space *space;
2241 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
2242 expr->n_arg = n;
2243 if (!expr->args)
2244 goto error;
2246 space = isl_map_get_space(expr->acc.access);
2247 n = extract_nested(space, 0, expr->args, param2pos);
2248 isl_space_free(space);
2250 if (n < 0)
2251 goto error;
2253 expr->n_arg = n;
2254 return expr;
2255 error:
2256 pet_expr_free(expr);
2257 return NULL;
2260 /* Look for parameters in any access relation in "expr" that
2261 * refer to nested accesses. In particular, these are
2262 * parameters with no name.
2264 * If there are any such parameters, then the domain of the access
2265 * relation, which is still [] at this point, is replaced by
2266 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2267 * (after identifying identical nested accesses).
2268 * The parameters are then equated to the corresponding t dimensions
2269 * and subsequently projected out.
2270 * param2pos maps the position of the parameter to the position
2271 * of the corresponding t dimension.
2273 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
2275 int n;
2276 int nparam;
2277 int n_in;
2278 isl_space *dim;
2279 isl_map *map;
2280 std::map<int,int> param2pos;
2282 if (!expr)
2283 return expr;
2285 for (int i = 0; i < expr->n_arg; ++i) {
2286 expr->args[i] = resolve_nested(expr->args[i]);
2287 if (!expr->args[i]) {
2288 pet_expr_free(expr);
2289 return NULL;
2293 if (expr->type != pet_expr_access)
2294 return expr;
2296 n = n_nested_parameter(expr->acc.access);
2297 if (n == 0)
2298 return expr;
2300 expr = extract_nested(expr, n, param2pos);
2301 if (!expr)
2302 return NULL;
2304 n = expr->n_arg;
2305 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
2306 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
2307 dim = isl_map_get_space(expr->acc.access);
2308 dim = isl_space_domain(dim);
2309 dim = isl_space_from_domain(dim);
2310 dim = isl_space_add_dims(dim, isl_dim_out, n);
2311 map = isl_map_universe(dim);
2312 map = isl_map_domain_map(map);
2313 map = isl_map_reverse(map);
2314 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
2316 for (int i = nparam - 1; i >= 0; --i) {
2317 isl_id *id = isl_map_get_dim_id(expr->acc.access,
2318 isl_dim_param, i);
2319 if (!is_nested_parameter(id)) {
2320 isl_id_free(id);
2321 continue;
2324 expr->acc.access = isl_map_equate(expr->acc.access,
2325 isl_dim_param, i, isl_dim_in,
2326 n_in + param2pos[i]);
2327 expr->acc.access = isl_map_project_out(expr->acc.access,
2328 isl_dim_param, i, 1);
2330 isl_id_free(id);
2333 return expr;
2334 error:
2335 pet_expr_free(expr);
2336 return NULL;
2339 /* Convert a top-level pet_expr to a pet_scop with one statement.
2340 * This mainly involves resolving nested expression parameters
2341 * and setting the name of the iteration space.
2342 * The name is given by "label" if it is non-NULL. Otherwise,
2343 * it is of the form S_<n_stmt>.
2345 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
2346 __isl_take isl_id *label)
2348 struct pet_stmt *ps;
2349 SourceLocation loc = stmt->getLocStart();
2350 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2352 expr = resolve_nested(expr);
2353 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
2354 return pet_scop_from_pet_stmt(ctx, ps);
2357 /* Check if we can extract an affine expression from "expr".
2358 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
2359 * We turn on autodetection so that we won't generate any warnings
2360 * and turn off nesting, so that we won't accept any non-affine constructs.
2362 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
2364 isl_pw_aff *pwaff;
2365 int save_autodetect = autodetect;
2366 bool save_nesting = nesting_enabled;
2368 autodetect = 1;
2369 nesting_enabled = false;
2371 pwaff = extract_affine(expr);
2373 autodetect = save_autodetect;
2374 nesting_enabled = save_nesting;
2376 return pwaff;
2379 /* Check whether "expr" is an affine expression.
2381 bool PetScan::is_affine(Expr *expr)
2383 isl_pw_aff *pwaff;
2385 pwaff = try_extract_affine(expr);
2386 isl_pw_aff_free(pwaff);
2388 return pwaff != NULL;
2391 /* Check whether "expr" is an affine constraint.
2392 * We turn on autodetection so that we won't generate any warnings
2393 * and turn off nesting, so that we won't accept any non-affine constructs.
2395 bool PetScan::is_affine_condition(Expr *expr)
2397 isl_set *set;
2398 int save_autodetect = autodetect;
2399 bool save_nesting = nesting_enabled;
2401 autodetect = 1;
2402 nesting_enabled = false;
2404 set = extract_condition(expr);
2405 isl_set_free(set);
2407 autodetect = save_autodetect;
2408 nesting_enabled = save_nesting;
2410 return set != NULL;
2413 /* Check if we can extract a condition from "expr".
2414 * Return the condition as an isl_set if we can and NULL otherwise.
2415 * If allow_nested is set, then the condition may involve parameters
2416 * corresponding to nested accesses.
2417 * We turn on autodetection so that we won't generate any warnings.
2419 __isl_give isl_set *PetScan::try_extract_nested_condition(Expr *expr)
2421 isl_set *set;
2422 int save_autodetect = autodetect;
2423 bool save_nesting = nesting_enabled;
2425 autodetect = 1;
2426 nesting_enabled = allow_nested;
2427 set = extract_condition(expr);
2429 autodetect = save_autodetect;
2430 nesting_enabled = save_nesting;
2432 return set;
2435 /* If the top-level expression of "stmt" is an assignment, then
2436 * return that assignment as a BinaryOperator.
2437 * Otherwise return NULL.
2439 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
2441 BinaryOperator *ass;
2443 if (!stmt)
2444 return NULL;
2445 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
2446 return NULL;
2448 ass = cast<BinaryOperator>(stmt);
2449 if(ass->getOpcode() != BO_Assign)
2450 return NULL;
2452 return ass;
2455 /* Check if the given if statement is a conditional assignement
2456 * with a non-affine condition. If so, construct a pet_scop
2457 * corresponding to this conditional assignment. Otherwise return NULL.
2459 * In particular we check if "stmt" is of the form
2461 * if (condition)
2462 * a = f(...);
2463 * else
2464 * a = g(...);
2466 * where a is some array or scalar access.
2467 * The constructed pet_scop then corresponds to the expression
2469 * a = condition ? f(...) : g(...)
2471 * All access relations in f(...) are intersected with condition
2472 * while all access relation in g(...) are intersected with the complement.
2474 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
2476 BinaryOperator *ass_then, *ass_else;
2477 isl_map *write_then, *write_else;
2478 isl_set *cond, *comp;
2479 isl_map *map, *map_true, *map_false;
2480 int equal;
2481 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
2482 bool save_nesting = nesting_enabled;
2484 ass_then = top_assignment_or_null(stmt->getThen());
2485 ass_else = top_assignment_or_null(stmt->getElse());
2487 if (!ass_then || !ass_else)
2488 return NULL;
2490 if (is_affine_condition(stmt->getCond()))
2491 return NULL;
2493 write_then = extract_access(ass_then->getLHS());
2494 write_else = extract_access(ass_else->getLHS());
2496 equal = isl_map_is_equal(write_then, write_else);
2497 isl_map_free(write_else);
2498 if (equal < 0 || !equal) {
2499 isl_map_free(write_then);
2500 return NULL;
2503 nesting_enabled = allow_nested;
2504 cond = extract_condition(stmt->getCond());
2505 nesting_enabled = save_nesting;
2506 comp = isl_set_complement(isl_set_copy(cond));
2507 map_true = isl_map_from_domain(isl_set_from_params(isl_set_copy(cond)));
2508 map_true = isl_map_add_dims(map_true, isl_dim_out, 1);
2509 map_true = isl_map_fix_si(map_true, isl_dim_out, 0, 1);
2510 map_false = isl_map_from_domain(isl_set_from_params(isl_set_copy(comp)));
2511 map_false = isl_map_add_dims(map_false, isl_dim_out, 1);
2512 map_false = isl_map_fix_si(map_false, isl_dim_out, 0, 0);
2513 map = isl_map_union_disjoint(map_true, map_false);
2515 pe_cond = pet_expr_from_access(map);
2517 pe_then = extract_expr(ass_then->getRHS());
2518 pe_then = pet_expr_restrict(pe_then, cond);
2519 pe_else = extract_expr(ass_else->getRHS());
2520 pe_else = pet_expr_restrict(pe_else, comp);
2522 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
2523 pe_write = pet_expr_from_access(write_then);
2524 if (pe_write) {
2525 pe_write->acc.write = 1;
2526 pe_write->acc.read = 0;
2528 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
2529 return extract(stmt, pe);
2532 /* Create an access to a virtual array representing the result
2533 * of a condition.
2534 * Unlike other accessed data, the id of the array is NULL as
2535 * there is no ValueDecl in the program corresponding to the virtual
2536 * array.
2537 * The array starts out as a scalar, but grows along with the
2538 * statement writing to the array in pet_scop_embed.
2540 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2542 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2543 isl_id *id;
2544 char name[50];
2546 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2547 id = isl_id_alloc(ctx, name, NULL);
2548 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2549 return isl_map_universe(dim);
2552 /* Create a pet_scop with a single statement evaluating "cond"
2553 * and writing the result to a virtual scalar, as expressed by
2554 * "access".
2556 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
2557 __isl_take isl_map *access)
2559 struct pet_expr *expr, *write;
2560 struct pet_stmt *ps;
2561 SourceLocation loc = cond->getLocStart();
2562 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2564 write = pet_expr_from_access(access);
2565 if (write) {
2566 write->acc.write = 1;
2567 write->acc.read = 0;
2569 expr = extract_expr(cond);
2570 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
2571 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
2572 return pet_scop_from_pet_stmt(ctx, ps);
2575 /* Add an array with the given extent ("access") to the list
2576 * of arrays in "scop" and return the extended pet_scop.
2577 * The array is marked as attaining values 0 and 1 only.
2579 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2580 __isl_keep isl_map *access)
2582 isl_ctx *ctx = isl_map_get_ctx(access);
2583 isl_space *dim;
2584 struct pet_array **arrays;
2585 struct pet_array *array;
2587 if (!scop)
2588 return NULL;
2589 if (!ctx)
2590 goto error;
2592 arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2593 scop->n_array + 1);
2594 if (!arrays)
2595 goto error;
2596 scop->arrays = arrays;
2598 array = isl_calloc_type(ctx, struct pet_array);
2599 if (!array)
2600 goto error;
2602 array->extent = isl_map_range(isl_map_copy(access));
2603 dim = isl_space_params_alloc(ctx, 0);
2604 array->context = isl_set_universe(dim);
2605 dim = isl_space_set_alloc(ctx, 0, 1);
2606 array->value_bounds = isl_set_universe(dim);
2607 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2608 isl_dim_set, 0, 0);
2609 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2610 isl_dim_set, 0, 1);
2611 array->element_type = strdup("int");
2613 scop->arrays[scop->n_array] = array;
2614 scop->n_array++;
2616 if (!array->extent || !array->context)
2617 goto error;
2619 return scop;
2620 error:
2621 pet_scop_free(scop);
2622 return NULL;
2625 extern "C" {
2626 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
2627 void *user);
2630 /* Apply the map pointed to by "user" to the domain of the access
2631 * relation, thereby embedding it in the range of the map.
2632 * The domain of both relations is the zero-dimensional domain.
2634 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
2636 isl_map *map = (isl_map *) user;
2638 return isl_map_apply_domain(access, isl_map_copy(map));
2641 /* Apply "map" to all access relations in "expr".
2643 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
2645 return pet_expr_foreach_access(expr, &embed_access, map);
2648 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2650 static int n_nested_parameter(__isl_keep isl_set *set)
2652 isl_space *space;
2653 int n;
2655 space = isl_set_get_space(set);
2656 n = n_nested_parameter(space);
2657 isl_space_free(space);
2659 return n;
2662 /* Remove all parameters from "map" that refer to nested accesses.
2664 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
2666 int nparam;
2667 isl_space *space;
2669 space = isl_map_get_space(map);
2670 nparam = isl_space_dim(space, isl_dim_param);
2671 for (int i = nparam - 1; i >= 0; --i)
2672 if (is_nested_parameter(space, i))
2673 map = isl_map_project_out(map, isl_dim_param, i, 1);
2674 isl_space_free(space);
2676 return map;
2679 extern "C" {
2680 static __isl_give isl_map *access_remove_nested_parameters(
2681 __isl_take isl_map *access, void *user);
2684 static __isl_give isl_map *access_remove_nested_parameters(
2685 __isl_take isl_map *access, void *user)
2687 return remove_nested_parameters(access);
2690 /* Remove all nested access parameters from the schedule and all
2691 * accesses of "stmt".
2692 * There is no need to remove them from the domain as these parameters
2693 * have already been removed from the domain when this function is called.
2695 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
2697 if (!stmt)
2698 return NULL;
2699 stmt->schedule = remove_nested_parameters(stmt->schedule);
2700 stmt->body = pet_expr_foreach_access(stmt->body,
2701 &access_remove_nested_parameters, NULL);
2702 if (!stmt->schedule || !stmt->body)
2703 goto error;
2704 for (int i = 0; i < stmt->n_arg; ++i) {
2705 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
2706 &access_remove_nested_parameters, NULL);
2707 if (!stmt->args[i])
2708 goto error;
2711 return stmt;
2712 error:
2713 pet_stmt_free(stmt);
2714 return NULL;
2717 /* For each nested access parameter in the domain of "stmt",
2718 * construct a corresponding pet_expr, place it in stmt->args and
2719 * record its position in "param2pos".
2720 * n is the number of nested access parameters.
2722 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
2723 std::map<int,int> &param2pos)
2725 isl_space *space;
2726 unsigned n_arg;
2727 struct pet_expr **args;
2729 n_arg = stmt->n_arg;
2730 args = isl_realloc_array(ctx, stmt->args, struct pet_expr *, n_arg + n);
2731 if (!args)
2732 goto error;
2733 stmt->args = args;
2734 stmt->n_arg += n;
2736 space = isl_set_get_space(stmt->domain);
2737 n = extract_nested(space, n_arg, stmt->args, param2pos);
2738 isl_space_free(space);
2740 if (n < 0)
2741 goto error;
2743 stmt->n_arg = n;
2744 return stmt;
2745 error:
2746 pet_stmt_free(stmt);
2747 return NULL;
2750 /* Look for parameters in the iteration domain of "stmt" that
2751 * refer to nested accesses. In particular, these are
2752 * parameters with no name.
2754 * If there are any such parameters, then as many extra variables
2755 * (after identifying identical nested accesses) are added to the
2756 * range of the map wrapped inside the domain.
2757 * If the original domain is not a wrapped map, then a new wrapped
2758 * map is created with zero output dimensions.
2759 * The parameters are then equated to the corresponding output dimensions
2760 * and subsequently projected out, from the iteration domain,
2761 * the schedule and the access relations.
2762 * For each of the output dimensions, a corresponding argument
2763 * expression is added. Initially they are created with
2764 * a zero-dimensional domain, so they have to be embedded
2765 * in the current iteration domain.
2766 * param2pos maps the position of the parameter to the position
2767 * of the corresponding output dimension in the wrapped map.
2769 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
2771 int n;
2772 int nparam;
2773 unsigned n_arg;
2774 isl_map *map;
2775 std::map<int,int> param2pos;
2777 if (!stmt)
2778 return NULL;
2780 n = n_nested_parameter(stmt->domain);
2781 if (n == 0)
2782 return stmt;
2784 n_arg = stmt->n_arg;
2785 stmt = extract_nested(stmt, n, param2pos);
2786 if (!stmt)
2787 return NULL;
2789 n = stmt->n_arg - n_arg;
2790 nparam = isl_set_dim(stmt->domain, isl_dim_param);
2791 if (isl_set_is_wrapping(stmt->domain))
2792 map = isl_set_unwrap(stmt->domain);
2793 else
2794 map = isl_map_from_domain(stmt->domain);
2795 map = isl_map_add_dims(map, isl_dim_out, n);
2797 for (int i = nparam - 1; i >= 0; --i) {
2798 isl_id *id;
2800 if (!is_nested_parameter(map, i))
2801 continue;
2803 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
2804 isl_dim_out);
2805 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
2806 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
2807 param2pos[i]);
2808 map = isl_map_project_out(map, isl_dim_param, i, 1);
2811 stmt->domain = isl_map_wrap(map);
2813 map = isl_set_unwrap(isl_set_copy(stmt->domain));
2814 map = isl_map_from_range(isl_map_domain(map));
2815 for (int pos = n_arg; pos < stmt->n_arg; ++pos)
2816 stmt->args[pos] = embed(stmt->args[pos], map);
2817 isl_map_free(map);
2819 stmt = remove_nested_parameters(stmt);
2821 return stmt;
2822 error:
2823 pet_stmt_free(stmt);
2824 return NULL;
2827 /* For each statement in "scop", move the parameters that correspond
2828 * to nested access into the ranges of the domains and create
2829 * corresponding argument expressions.
2831 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
2833 if (!scop)
2834 return NULL;
2836 for (int i = 0; i < scop->n_stmt; ++i) {
2837 scop->stmts[i] = resolve_nested(scop->stmts[i]);
2838 if (!scop->stmts[i])
2839 goto error;
2842 return scop;
2843 error:
2844 pet_scop_free(scop);
2845 return NULL;
2848 /* Does "space" involve any parameters that refer to nested
2849 * accesses, i.e., parameters with no name?
2851 static bool has_nested(__isl_keep isl_space *space)
2853 int nparam;
2855 nparam = isl_space_dim(space, isl_dim_param);
2856 for (int i = 0; i < nparam; ++i)
2857 if (is_nested_parameter(space, i))
2858 return true;
2860 return false;
2863 /* Does "set" involve any parameters that refer to nested
2864 * accesses, i.e., parameters with no name?
2866 static bool has_nested(__isl_keep isl_set *set)
2868 isl_space *space;
2869 bool nested;
2871 space = isl_set_get_space(set);
2872 nested = has_nested(space);
2873 isl_space_free(space);
2875 return nested;
2878 /* Given an access expression "expr", is the variable accessed by
2879 * "expr" assigned anywhere inside "scop"?
2881 static bool is_assigned(pet_expr *expr, pet_scop *scop)
2883 bool assigned = false;
2884 isl_id *id;
2886 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
2887 assigned = pet_scop_writes(scop, id);
2888 isl_id_free(id);
2890 return assigned;
2893 /* Are all nested access parameters in "set" allowed given "scop".
2894 * In particular, is none of them written by anywhere inside "scop".
2896 bool PetScan::is_nested_allowed(__isl_keep isl_set *set, pet_scop *scop)
2898 int nparam;
2900 nparam = isl_set_dim(set, isl_dim_param);
2901 for (int i = 0; i < nparam; ++i) {
2902 Expr *nested;
2903 isl_id *id = isl_set_get_dim_id(set, isl_dim_param, i);
2904 pet_expr *expr;
2905 bool allowed;
2907 if (!is_nested_parameter(id)) {
2908 isl_id_free(id);
2909 continue;
2912 nested = (Expr *) isl_id_get_user(id);
2913 expr = extract_expr(nested);
2914 allowed = expr && expr->type == pet_expr_access &&
2915 !is_assigned(expr, scop);
2917 pet_expr_free(expr);
2918 isl_id_free(id);
2920 if (!allowed)
2921 return false;
2924 return true;
2927 /* Construct a pet_scop for an if statement.
2929 * If the condition fits the pattern of a conditional assignment,
2930 * then it is handled by extract_conditional_assignment.
2931 * Otherwise, we do the following.
2933 * If the condition is affine, then the condition is added
2934 * to the iteration domains of the then branch, while the
2935 * opposite of the condition in added to the iteration domains
2936 * of the else branch, if any.
2937 * We allow the condition to be dynamic, i.e., to refer to
2938 * scalars or array elements that may be written to outside
2939 * of the given if statement. These nested accesses are then represented
2940 * as output dimensions in the wrapping iteration domain.
2941 * If it also written _inside_ the then or else branch, then
2942 * we treat the condition as non-affine.
2943 * As explained below, this will introduce an extra statement.
2944 * For aesthetic reasons, we want this statement to have a statement
2945 * number that is lower than those of the then and else branches.
2946 * In order to evaluate if will need such a statement, however, we
2947 * first construct scops for the then and else branches.
2948 * We therefore reserve a statement number if we might have to
2949 * introduce such an extra statement.
2951 * If the condition is not affine, then we create a separate
2952 * statement that writes the result of the condition to a virtual scalar.
2953 * A constraint requiring the value of this virtual scalar to be one
2954 * is added to the iteration domains of the then branch.
2955 * Similarly, a constraint requiring the value of this virtual scalar
2956 * to be zero is added to the iteration domains of the else branch, if any.
2957 * We adjust the schedules to ensure that the virtual scalar is written
2958 * before it is read.
2960 struct pet_scop *PetScan::extract(IfStmt *stmt)
2962 struct pet_scop *scop_then, *scop_else, *scop;
2963 assigned_value_cache cache(assigned_value);
2964 isl_map *test_access = NULL;
2965 isl_set *cond;
2966 int stmt_id;
2968 scop = extract_conditional_assignment(stmt);
2969 if (scop)
2970 return scop;
2972 cond = try_extract_nested_condition(stmt->getCond());
2973 if (allow_nested && (!cond || has_nested(cond)))
2974 stmt_id = n_stmt++;
2976 scop_then = extract(stmt->getThen());
2978 if (stmt->getElse()) {
2979 scop_else = extract(stmt->getElse());
2980 if (autodetect) {
2981 if (scop_then && !scop_else) {
2982 partial = true;
2983 isl_set_free(cond);
2984 return scop_then;
2986 if (!scop_then && scop_else) {
2987 partial = true;
2988 isl_set_free(cond);
2989 return scop_else;
2994 if (cond &&
2995 (!is_nested_allowed(cond, scop_then) ||
2996 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
2997 isl_set_free(cond);
2998 cond = NULL;
3000 if (allow_nested && !cond) {
3001 int save_n_stmt = n_stmt;
3002 test_access = create_test_access(ctx, n_test++);
3003 n_stmt = stmt_id;
3004 scop = extract_non_affine_condition(stmt->getCond(),
3005 isl_map_copy(test_access));
3006 n_stmt = save_n_stmt;
3007 scop = scop_add_array(scop, test_access);
3008 if (!scop) {
3009 pet_scop_free(scop_then);
3010 pet_scop_free(scop_else);
3011 isl_map_free(test_access);
3012 return NULL;
3016 if (!scop) {
3017 if (!cond)
3018 cond = extract_condition(stmt->getCond());
3019 scop = pet_scop_restrict(scop_then, isl_set_copy(cond));
3021 if (stmt->getElse()) {
3022 cond = isl_set_complement(cond);
3023 scop_else = pet_scop_restrict(scop_else, cond);
3024 scop = pet_scop_add(ctx, scop, scop_else);
3025 } else
3026 isl_set_free(cond);
3027 scop = resolve_nested(scop);
3028 } else {
3029 scop = pet_scop_prefix(scop, 0);
3030 scop_then = pet_scop_prefix(scop_then, 1);
3031 scop_then = pet_scop_filter(scop_then,
3032 isl_map_copy(test_access), 1);
3033 scop = pet_scop_add(ctx, scop, scop_then);
3034 if (stmt->getElse()) {
3035 scop_else = pet_scop_prefix(scop_else, 1);
3036 scop_else = pet_scop_filter(scop_else, test_access, 0);
3037 scop = pet_scop_add(ctx, scop, scop_else);
3038 } else
3039 isl_map_free(test_access);
3042 return scop;
3045 /* Try and construct a pet_scop for a label statement.
3046 * We currently only allow labels on expression statements.
3048 struct pet_scop *PetScan::extract(LabelStmt *stmt)
3050 isl_id *label;
3051 Stmt *sub;
3053 sub = stmt->getSubStmt();
3054 if (!isa<Expr>(sub)) {
3055 unsupported(stmt);
3056 return NULL;
3059 label = isl_id_alloc(ctx, stmt->getName(), NULL);
3061 return extract(sub, extract_expr(cast<Expr>(sub)), label);
3064 /* Try and construct a pet_scop corresponding to "stmt".
3066 struct pet_scop *PetScan::extract(Stmt *stmt)
3068 if (isa<Expr>(stmt))
3069 return extract(stmt, extract_expr(cast<Expr>(stmt)));
3071 switch (stmt->getStmtClass()) {
3072 case Stmt::WhileStmtClass:
3073 return extract(cast<WhileStmt>(stmt));
3074 case Stmt::ForStmtClass:
3075 return extract_for(cast<ForStmt>(stmt));
3076 case Stmt::IfStmtClass:
3077 return extract(cast<IfStmt>(stmt));
3078 case Stmt::CompoundStmtClass:
3079 return extract(cast<CompoundStmt>(stmt));
3080 case Stmt::LabelStmtClass:
3081 return extract(cast<LabelStmt>(stmt));
3082 default:
3083 unsupported(stmt);
3086 return NULL;
3089 /* Try and construct a pet_scop corresponding to (part of)
3090 * a sequence of statements.
3092 struct pet_scop *PetScan::extract(StmtRange stmt_range)
3094 pet_scop *scop;
3095 StmtIterator i;
3096 int j;
3097 bool partial_range = false;
3099 scop = pet_scop_empty(ctx);
3100 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
3101 Stmt *child = *i;
3102 struct pet_scop *scop_i;
3103 scop_i = extract(child);
3104 if (scop && partial) {
3105 pet_scop_free(scop_i);
3106 break;
3108 scop_i = pet_scop_prefix(scop_i, j);
3109 if (autodetect) {
3110 if (scop_i)
3111 scop = pet_scop_add(ctx, scop, scop_i);
3112 else
3113 partial_range = true;
3114 if (scop->n_stmt != 0 && !scop_i)
3115 partial = true;
3116 } else {
3117 scop = pet_scop_add(ctx, scop, scop_i);
3119 if (partial)
3120 break;
3123 if (scop && partial_range)
3124 partial = true;
3126 return scop;
3129 /* Check if the scop marked by the user is exactly this Stmt
3130 * or part of this Stmt.
3131 * If so, return a pet_scop corresponding to the marked region.
3132 * Otherwise, return NULL.
3134 struct pet_scop *PetScan::scan(Stmt *stmt)
3136 SourceManager &SM = PP.getSourceManager();
3137 unsigned start_off, end_off;
3139 start_off = SM.getFileOffset(stmt->getLocStart());
3140 end_off = SM.getFileOffset(stmt->getLocEnd());
3142 if (start_off > loc.end)
3143 return NULL;
3144 if (end_off < loc.start)
3145 return NULL;
3146 if (start_off >= loc.start && end_off <= loc.end) {
3147 return extract(stmt);
3150 StmtIterator start;
3151 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
3152 Stmt *child = *start;
3153 if (!child)
3154 continue;
3155 start_off = SM.getFileOffset(child->getLocStart());
3156 end_off = SM.getFileOffset(child->getLocEnd());
3157 if (start_off < loc.start && end_off > loc.end)
3158 return scan(child);
3159 if (start_off >= loc.start)
3160 break;
3163 StmtIterator end;
3164 for (end = start; end != stmt->child_end(); ++end) {
3165 Stmt *child = *end;
3166 start_off = SM.getFileOffset(child->getLocStart());
3167 if (start_off >= loc.end)
3168 break;
3171 return extract(StmtRange(start, end));
3174 /* Set the size of index "pos" of "array" to "size".
3175 * In particular, add a constraint of the form
3177 * i_pos < size
3179 * to array->extent and a constraint of the form
3181 * size >= 0
3183 * to array->context.
3185 static struct pet_array *update_size(struct pet_array *array, int pos,
3186 __isl_take isl_pw_aff *size)
3188 isl_set *valid;
3189 isl_set *univ;
3190 isl_set *bound;
3191 isl_space *dim;
3192 isl_aff *aff;
3193 isl_pw_aff *index;
3194 isl_id *id;
3196 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
3197 array->context = isl_set_intersect(array->context, valid);
3199 dim = isl_set_get_space(array->extent);
3200 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
3201 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
3202 univ = isl_set_universe(isl_aff_get_domain_space(aff));
3203 index = isl_pw_aff_alloc(univ, aff);
3205 size = isl_pw_aff_add_dims(size, isl_dim_in,
3206 isl_set_dim(array->extent, isl_dim_set));
3207 id = isl_set_get_tuple_id(array->extent);
3208 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
3209 bound = isl_pw_aff_lt_set(index, size);
3211 array->extent = isl_set_intersect(array->extent, bound);
3213 if (!array->context || !array->extent)
3214 goto error;
3216 return array;
3217 error:
3218 pet_array_free(array);
3219 return NULL;
3222 /* Figure out the size of the array at position "pos" and all
3223 * subsequent positions from "type" and update "array" accordingly.
3225 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
3226 const Type *type, int pos)
3228 const ArrayType *atype;
3229 isl_pw_aff *size;
3231 if (!array)
3232 return NULL;
3234 if (type->isPointerType()) {
3235 type = type->getPointeeType().getTypePtr();
3236 return set_upper_bounds(array, type, pos + 1);
3238 if (!type->isArrayType())
3239 return array;
3241 type = type->getCanonicalTypeInternal().getTypePtr();
3242 atype = cast<ArrayType>(type);
3244 if (type->isConstantArrayType()) {
3245 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
3246 size = extract_affine(ca->getSize());
3247 array = update_size(array, pos, size);
3248 } else if (type->isVariableArrayType()) {
3249 const VariableArrayType *vla = cast<VariableArrayType>(atype);
3250 size = extract_affine(vla->getSizeExpr());
3251 array = update_size(array, pos, size);
3254 type = atype->getElementType().getTypePtr();
3256 return set_upper_bounds(array, type, pos + 1);
3259 /* Construct and return a pet_array corresponding to the variable "decl".
3260 * In particular, initialize array->extent to
3262 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3264 * and then call set_upper_bounds to set the upper bounds on the indices
3265 * based on the type of the variable.
3267 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
3269 struct pet_array *array;
3270 QualType qt = decl->getType();
3271 const Type *type = qt.getTypePtr();
3272 int depth = array_depth(type);
3273 QualType base = base_type(qt);
3274 string name;
3275 isl_id *id;
3276 isl_space *dim;
3278 array = isl_calloc_type(ctx, struct pet_array);
3279 if (!array)
3280 return NULL;
3282 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
3283 dim = isl_space_set_alloc(ctx, 0, depth);
3284 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
3286 array->extent = isl_set_nat_universe(dim);
3288 dim = isl_space_params_alloc(ctx, 0);
3289 array->context = isl_set_universe(dim);
3291 array = set_upper_bounds(array, type, 0);
3292 if (!array)
3293 return NULL;
3295 name = base.getAsString();
3296 array->element_type = strdup(name.c_str());
3298 return array;
3301 /* Construct a list of pet_arrays, one for each array (or scalar)
3302 * accessed inside "scop" add this list to "scop" and return the result.
3304 * The context of "scop" is updated with the intesection of
3305 * the contexts of all arrays, i.e., constraints on the parameters
3306 * that ensure that the arrays have a valid (non-negative) size.
3308 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
3310 int i;
3311 set<ValueDecl *> arrays;
3312 set<ValueDecl *>::iterator it;
3313 int n_array;
3314 struct pet_array **scop_arrays;
3316 if (!scop)
3317 return NULL;
3319 pet_scop_collect_arrays(scop, arrays);
3320 if (arrays.size() == 0)
3321 return scop;
3323 n_array = scop->n_array;
3325 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3326 n_array + arrays.size());
3327 if (!scop_arrays)
3328 goto error;
3329 scop->arrays = scop_arrays;
3331 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3332 struct pet_array *array;
3333 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
3334 if (!scop->arrays[n_array + i])
3335 goto error;
3336 scop->n_array++;
3337 scop->context = isl_set_intersect(scop->context,
3338 isl_set_copy(array->context));
3339 if (!scop->context)
3340 goto error;
3343 return scop;
3344 error:
3345 pet_scop_free(scop);
3346 return NULL;
3349 /* Construct a pet_scop from the given function.
3351 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3353 pet_scop *scop;
3354 Stmt *stmt;
3356 stmt = fd->getBody();
3358 if (autodetect)
3359 scop = extract(stmt);
3360 else
3361 scop = scan(stmt);
3362 scop = pet_scop_detect_parameter_accesses(scop);
3363 scop = scan_arrays(scop);
3365 return scop;