allow parens around integer literal in second argument of integer division
[pet.git] / scan.cc
blob98388683191ab5070421f1a1b7a192db47f936f3
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 /* Look for any assignments to scalar variables in part of the parse
76 * tree and set assigned_value to NULL for each of them.
77 * Also reset assigned_value if the address of a scalar variable
78 * is being taken. As an exception, if the address is passed to a function
79 * that is declared to receive a const pointer, then assigned_value is
80 * not reset.
82 * This ensures that we won't use any previously stored value
83 * in the current subtree and its parents.
85 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
86 map<ValueDecl *, Expr *> &assigned_value;
87 set<UnaryOperator *> skip;
89 clear_assignments(map<ValueDecl *, Expr *> &assigned_value) :
90 assigned_value(assigned_value) {}
92 /* Check for "address of" operators whose value is passed
93 * to a const pointer argument and add them to "skip", so that
94 * we can skip them in VisitUnaryOperator.
96 bool VisitCallExpr(CallExpr *expr) {
97 FunctionDecl *fd;
98 fd = expr->getDirectCallee();
99 if (!fd)
100 return true;
101 for (int i = 0; i < expr->getNumArgs(); ++i) {
102 Expr *arg = expr->getArg(i);
103 UnaryOperator *op;
104 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
105 ImplicitCastExpr *ice;
106 ice = cast<ImplicitCastExpr>(arg);
107 arg = ice->getSubExpr();
109 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
110 continue;
111 op = cast<UnaryOperator>(arg);
112 if (op->getOpcode() != UO_AddrOf)
113 continue;
114 if (const_base(fd->getParamDecl(i)->getType()))
115 skip.insert(op);
117 return true;
120 bool VisitUnaryOperator(UnaryOperator *expr) {
121 Expr *arg;
122 DeclRefExpr *ref;
123 ValueDecl *decl;
125 if (expr->getOpcode() != UO_AddrOf)
126 return true;
127 if (skip.find(expr) != skip.end())
128 return true;
130 arg = expr->getSubExpr();
131 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
132 return true;
133 ref = cast<DeclRefExpr>(arg);
134 decl = ref->getDecl();
135 assigned_value[decl] = NULL;
136 return true;
139 bool VisitBinaryOperator(BinaryOperator *expr) {
140 Expr *lhs;
141 DeclRefExpr *ref;
142 ValueDecl *decl;
144 if (!expr->isAssignmentOp())
145 return true;
146 lhs = expr->getLHS();
147 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
148 return true;
149 ref = cast<DeclRefExpr>(lhs);
150 decl = ref->getDecl();
151 assigned_value[decl] = NULL;
152 return true;
156 /* Keep a copy of the currently assigned values.
158 * Any variable that is assigned a value inside the current scope
159 * is removed again when we leave the scope (either because it wasn't
160 * stored in the cache or because it has a different value in the cache).
162 struct assigned_value_cache {
163 map<ValueDecl *, Expr *> &assigned_value;
164 map<ValueDecl *, Expr *> cache;
166 assigned_value_cache(map<ValueDecl *, Expr *> &assigned_value) :
167 assigned_value(assigned_value), cache(assigned_value) {}
168 ~assigned_value_cache() {
169 map<ValueDecl *, Expr *>::iterator it = cache.begin();
170 for (it = assigned_value.begin(); it != assigned_value.end();
171 ++it) {
172 if (!it->second ||
173 (cache.find(it->first) != cache.end() &&
174 cache[it->first] != it->second))
175 cache[it->first] = NULL;
177 assigned_value = cache;
181 /* Called if we found something we (currently) cannot handle.
182 * We'll provide more informative warnings later.
184 * We only actually complain if autodetect is false.
186 void PetScan::unsupported(Stmt *stmt)
188 if (autodetect)
189 return;
191 SourceLocation loc = stmt->getLocStart();
192 DiagnosticsEngine &diag = PP.getDiagnostics();
193 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
194 "unsupported");
195 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
198 /* Extract an integer from "expr" and store it in "v".
200 int PetScan::extract_int(IntegerLiteral *expr, isl_int *v)
202 const Type *type = expr->getType().getTypePtr();
203 int is_signed = type->hasSignedIntegerRepresentation();
205 if (is_signed) {
206 int64_t i = expr->getValue().getSExtValue();
207 isl_int_set_si(*v, i);
208 } else {
209 uint64_t i = expr->getValue().getZExtValue();
210 isl_int_set_ui(*v, i);
213 return 0;
216 /* Extract an integer from "expr" and store it in "v".
217 * Return -1 if "expr" does not (obviously) represent an integer.
219 int PetScan::extract_int(clang::ParenExpr *expr, isl_int *v)
221 return extract_int(expr->getSubExpr(), v);
224 /* Extract an integer from "expr" and store it in "v".
225 * Return -1 if "expr" does not (obviously) represent an integer.
227 int PetScan::extract_int(clang::Expr *expr, isl_int *v)
229 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
230 return extract_int(cast<IntegerLiteral>(expr), v);
231 if (expr->getStmtClass() == Stmt::ParenExprClass)
232 return extract_int(cast<ParenExpr>(expr), v);
234 unsupported(expr);
235 return -1;
238 /* Extract an affine expression from the IntegerLiteral "expr".
240 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
242 isl_space *dim = isl_space_params_alloc(ctx, 0);
243 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
244 isl_aff *aff = isl_aff_zero_on_domain(ls);
245 isl_set *dom = isl_set_universe(dim);
246 isl_int v;
248 isl_int_init(v);
249 extract_int(expr, &v);
250 aff = isl_aff_add_constant(aff, v);
251 isl_int_clear(v);
253 return isl_pw_aff_alloc(dom, aff);
256 /* Extract an affine expression from the APInt "val".
258 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
260 isl_space *dim = isl_space_params_alloc(ctx, 0);
261 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
262 isl_aff *aff = isl_aff_zero_on_domain(ls);
263 isl_set *dom = isl_set_universe(dim);
264 isl_int v;
266 isl_int_init(v);
267 isl_int_set_ui(v, val.getZExtValue());
268 aff = isl_aff_add_constant(aff, v);
269 isl_int_clear(v);
271 return isl_pw_aff_alloc(dom, aff);
274 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
276 return extract_affine(expr->getSubExpr());
279 /* Extract an affine expression from the DeclRefExpr "expr".
281 * If the variable has been assigned a value, then we check whether
282 * we know what expression was assigned and whether this expression
283 * is affine. If so, we convert the expression to an isl_pw_aff
284 * and to an extra parameter otherwise (provided nesting_enabled is set).
286 * Otherwise, we simply return an expression that is equal
287 * to a parameter corresponding to the referenced variable.
289 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
291 ValueDecl *decl = expr->getDecl();
292 const Type *type = decl->getType().getTypePtr();
293 isl_id *id;
294 isl_space *dim;
295 isl_aff *aff;
296 isl_set *dom;
298 if (!type->isIntegerType()) {
299 unsupported(expr);
300 return NULL;
303 if (assigned_value.find(decl) != assigned_value.end()) {
304 if (assigned_value[decl] && is_affine(assigned_value[decl]))
305 return extract_affine(assigned_value[decl]);
306 else
307 return nested_access(expr);
310 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
311 dim = isl_space_params_alloc(ctx, 1);
313 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
315 dom = isl_set_universe(isl_space_copy(dim));
316 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
317 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
319 return isl_pw_aff_alloc(dom, aff);
322 /* Extract an affine expression from an integer division operation.
323 * In particular, if "expr" is lhs/rhs, then return
325 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
327 * The second argument (rhs) is required to be a (positive) integer constant.
329 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
331 Expr *rhs_expr;
332 isl_pw_aff *lhs, *lhs_f, *lhs_c;
333 isl_pw_aff *res;
334 isl_int v;
335 isl_set *cond;
337 rhs_expr = expr->getRHS();
338 isl_int_init(v);
339 if (extract_int(rhs_expr, &v) < 0) {
340 isl_int_clear(v);
341 return NULL;
344 lhs = extract_affine(expr->getLHS());
345 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
347 lhs = isl_pw_aff_scale_down(lhs, v);
348 isl_int_clear(v);
350 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(lhs));
351 lhs_c = isl_pw_aff_ceil(lhs);
352 res = isl_pw_aff_cond(cond, lhs_f, lhs_c);
354 return res;
357 /* Extract an affine expression from a modulo operation.
358 * In particular, if "expr" is lhs/rhs, then return
360 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
362 * The second argument (rhs) is required to be a (positive) integer constant.
364 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
366 Expr *rhs_expr;
367 isl_pw_aff *lhs, *lhs_f, *lhs_c;
368 isl_pw_aff *res;
369 isl_int v;
370 isl_set *cond;
372 rhs_expr = expr->getRHS();
373 if (rhs_expr->getStmtClass() != Stmt::IntegerLiteralClass) {
374 unsupported(expr);
375 return NULL;
378 lhs = extract_affine(expr->getLHS());
379 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
381 isl_int_init(v);
382 extract_int(cast<IntegerLiteral>(rhs_expr), &v);
383 res = isl_pw_aff_scale_down(isl_pw_aff_copy(lhs), v);
385 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(res));
386 lhs_c = isl_pw_aff_ceil(res);
387 res = isl_pw_aff_cond(cond, lhs_f, lhs_c);
389 res = isl_pw_aff_scale(res, v);
390 isl_int_clear(v);
392 res = isl_pw_aff_sub(lhs, res);
394 return res;
397 /* Extract an affine expression from a multiplication operation.
398 * This is only allowed if at least one of the two arguments
399 * is a (piecewise) constant.
401 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
403 isl_pw_aff *lhs;
404 isl_pw_aff *rhs;
406 lhs = extract_affine(expr->getLHS());
407 rhs = extract_affine(expr->getRHS());
409 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
410 isl_pw_aff_free(lhs);
411 isl_pw_aff_free(rhs);
412 unsupported(expr);
413 return NULL;
416 return isl_pw_aff_mul(lhs, rhs);
419 /* Extract an affine expression from an addition or subtraction operation.
421 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
423 isl_pw_aff *lhs;
424 isl_pw_aff *rhs;
426 lhs = extract_affine(expr->getLHS());
427 rhs = extract_affine(expr->getRHS());
429 switch (expr->getOpcode()) {
430 case BO_Add:
431 return isl_pw_aff_add(lhs, rhs);
432 case BO_Sub:
433 return isl_pw_aff_sub(lhs, rhs);
434 default:
435 isl_pw_aff_free(lhs);
436 isl_pw_aff_free(rhs);
437 return NULL;
442 /* Compute
444 * pwaff mod 2^width
446 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
447 unsigned width)
449 isl_int mod;
451 isl_int_init(mod);
452 isl_int_set_si(mod, 1);
453 isl_int_mul_2exp(mod, mod, width);
455 pwaff = isl_pw_aff_mod(pwaff, mod);
457 isl_int_clear(mod);
459 return pwaff;
462 /* Extract an affine expression from some binary operations.
463 * If the result of the expression is unsigned, then we wrap it
464 * based on the size of the type.
466 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
468 isl_pw_aff *res;
470 switch (expr->getOpcode()) {
471 case BO_Add:
472 case BO_Sub:
473 res = extract_affine_add(expr);
474 break;
475 case BO_Div:
476 res = extract_affine_div(expr);
477 break;
478 case BO_Rem:
479 res = extract_affine_mod(expr);
480 break;
481 case BO_Mul:
482 res = extract_affine_mul(expr);
483 break;
484 default:
485 unsupported(expr);
486 return NULL;
489 if (expr->getType()->isUnsignedIntegerType())
490 res = wrap(res, ast_context.getIntWidth(expr->getType()));
492 return res;
495 /* Extract an affine expression from a negation operation.
497 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
499 if (expr->getOpcode() == UO_Minus)
500 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
502 unsupported(expr);
503 return NULL;
506 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
508 return extract_affine(expr->getSubExpr());
511 /* Extract an affine expression from some special function calls.
512 * In particular, we handle "min", "max", "ceild" and "floord".
513 * In case of the latter two, the second argument needs to be
514 * a (positive) integer constant.
516 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
518 FunctionDecl *fd;
519 string name;
520 isl_pw_aff *aff1, *aff2;
522 fd = expr->getDirectCallee();
523 if (!fd) {
524 unsupported(expr);
525 return NULL;
528 name = fd->getDeclName().getAsString();
529 if (!(expr->getNumArgs() == 2 && name == "min") &&
530 !(expr->getNumArgs() == 2 && name == "max") &&
531 !(expr->getNumArgs() == 2 && name == "floord") &&
532 !(expr->getNumArgs() == 2 && name == "ceild")) {
533 unsupported(expr);
534 return NULL;
537 if (name == "min" || name == "max") {
538 aff1 = extract_affine(expr->getArg(0));
539 aff2 = extract_affine(expr->getArg(1));
541 if (name == "min")
542 aff1 = isl_pw_aff_min(aff1, aff2);
543 else
544 aff1 = isl_pw_aff_max(aff1, aff2);
545 } else if (name == "floord" || name == "ceild") {
546 isl_int v;
547 Expr *arg2 = expr->getArg(1);
549 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
550 unsupported(expr);
551 return NULL;
553 aff1 = extract_affine(expr->getArg(0));
554 isl_int_init(v);
555 extract_int(cast<IntegerLiteral>(arg2), &v);
556 aff1 = isl_pw_aff_scale_down(aff1, v);
557 isl_int_clear(v);
558 if (name == "floord")
559 aff1 = isl_pw_aff_floor(aff1);
560 else
561 aff1 = isl_pw_aff_ceil(aff1);
562 } else {
563 unsupported(expr);
564 return NULL;
567 return aff1;
571 /* This method is called when we come across an access that is
572 * nested in what is supposed to be an affine expression.
573 * If nesting is allowed, we return a new parameter that corresponds
574 * to this nested access. Otherwise, we simply complain.
576 * The new parameter is resolved in resolve_nested.
578 isl_pw_aff *PetScan::nested_access(Expr *expr)
580 isl_id *id;
581 isl_space *dim;
582 isl_aff *aff;
583 isl_set *dom;
585 if (!nesting_enabled) {
586 unsupported(expr);
587 return NULL;
590 id = isl_id_alloc(ctx, NULL, expr);
591 dim = isl_space_params_alloc(ctx, 1);
593 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
595 dom = isl_set_universe(isl_space_copy(dim));
596 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
597 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
599 return isl_pw_aff_alloc(dom, aff);
602 /* Affine expressions are not supposed to contain array accesses,
603 * but if nesting is allowed, we return a parameter corresponding
604 * to the array access.
606 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
608 return nested_access(expr);
611 /* Extract an affine expression from a conditional operation.
613 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
615 isl_set *cond;
616 isl_pw_aff *lhs, *rhs;
618 cond = extract_condition(expr->getCond());
619 lhs = extract_affine(expr->getTrueExpr());
620 rhs = extract_affine(expr->getFalseExpr());
622 return isl_pw_aff_cond(cond, lhs, rhs);
625 /* Extract an affine expression, if possible, from "expr".
626 * Otherwise return NULL.
628 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
630 switch (expr->getStmtClass()) {
631 case Stmt::ImplicitCastExprClass:
632 return extract_affine(cast<ImplicitCastExpr>(expr));
633 case Stmt::IntegerLiteralClass:
634 return extract_affine(cast<IntegerLiteral>(expr));
635 case Stmt::DeclRefExprClass:
636 return extract_affine(cast<DeclRefExpr>(expr));
637 case Stmt::BinaryOperatorClass:
638 return extract_affine(cast<BinaryOperator>(expr));
639 case Stmt::UnaryOperatorClass:
640 return extract_affine(cast<UnaryOperator>(expr));
641 case Stmt::ParenExprClass:
642 return extract_affine(cast<ParenExpr>(expr));
643 case Stmt::CallExprClass:
644 return extract_affine(cast<CallExpr>(expr));
645 case Stmt::ArraySubscriptExprClass:
646 return extract_affine(cast<ArraySubscriptExpr>(expr));
647 case Stmt::ConditionalOperatorClass:
648 return extract_affine(cast<ConditionalOperator>(expr));
649 default:
650 unsupported(expr);
652 return NULL;
655 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
657 return extract_access(expr->getSubExpr());
660 /* Return the depth of an array of the given type.
662 static int array_depth(const Type *type)
664 if (type->isPointerType())
665 return 1 + array_depth(type->getPointeeType().getTypePtr());
666 if (type->isArrayType()) {
667 const ArrayType *atype;
668 type = type->getCanonicalTypeInternal().getTypePtr();
669 atype = cast<ArrayType>(type);
670 return 1 + array_depth(atype->getElementType().getTypePtr());
672 return 0;
675 /* Return the element type of the given array type.
677 static QualType base_type(QualType qt)
679 const Type *type = qt.getTypePtr();
681 if (type->isPointerType())
682 return base_type(type->getPointeeType());
683 if (type->isArrayType()) {
684 const ArrayType *atype;
685 type = type->getCanonicalTypeInternal().getTypePtr();
686 atype = cast<ArrayType>(type);
687 return base_type(atype->getElementType());
689 return qt;
692 /* Extract an access relation from a reference to a variable.
693 * If the variable has name "A" and its type corresponds to an
694 * array of depth d, then the returned access relation is of the
695 * form
697 * { [] -> A[i_1,...,i_d] }
699 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
701 ValueDecl *decl = expr->getDecl();
702 int depth = array_depth(decl->getType().getTypePtr());
703 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
704 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
705 isl_map *access_rel;
707 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
709 access_rel = isl_map_universe(dim);
711 return access_rel;
714 /* Extract an access relation from an integer contant.
715 * If the value of the constant is "v", then the returned access relation
716 * is
718 * { [] -> [v] }
720 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
722 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
725 /* Try and extract an access relation from the given Expr.
726 * Return NULL if it doesn't work out.
728 __isl_give isl_map *PetScan::extract_access(Expr *expr)
730 switch (expr->getStmtClass()) {
731 case Stmt::ImplicitCastExprClass:
732 return extract_access(cast<ImplicitCastExpr>(expr));
733 case Stmt::DeclRefExprClass:
734 return extract_access(cast<DeclRefExpr>(expr));
735 case Stmt::ArraySubscriptExprClass:
736 return extract_access(cast<ArraySubscriptExpr>(expr));
737 default:
738 unsupported(expr);
740 return NULL;
743 /* Assign the affine expression "index" to the output dimension "pos" of "map"
744 * and return the result.
746 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
747 __isl_take isl_pw_aff *index)
749 isl_map *index_map;
750 int len = isl_map_dim(map, isl_dim_out);
751 isl_id *id;
753 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
754 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
755 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
756 id = isl_map_get_tuple_id(map, isl_dim_out);
757 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
759 map = isl_map_intersect(map, index_map);
761 return map;
764 /* Extract an access relation from the given array subscript expression.
765 * If nesting is allowed in general, then we turn it on while
766 * examining the index expression.
768 * We first extract an access relation from the base.
769 * This will result in an access relation with a range that corresponds
770 * to the array being accessed and with earlier indices filled in already.
771 * We then extract the current index and fill that in as well.
772 * The position of the current index is based on the type of base.
773 * If base is the actual array variable, then the depth of this type
774 * will be the same as the depth of the array and we will fill in
775 * the first array index.
776 * Otherwise, the depth of the base type will be smaller and we will fill
777 * in a later index.
779 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
781 Expr *base = expr->getBase();
782 Expr *idx = expr->getIdx();
783 isl_pw_aff *index;
784 isl_map *base_access;
785 isl_map *access;
786 int depth = array_depth(base->getType().getTypePtr());
787 int pos;
788 bool save_nesting = nesting_enabled;
790 nesting_enabled = allow_nested;
792 base_access = extract_access(base);
793 index = extract_affine(idx);
795 nesting_enabled = save_nesting;
797 pos = isl_map_dim(base_access, isl_dim_out) - depth;
798 access = set_index(base_access, pos, index);
800 return access;
803 /* Check if "expr" calls function "minmax" with two arguments and if so
804 * make lhs and rhs refer to these two arguments.
806 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
808 CallExpr *call;
809 FunctionDecl *fd;
810 string name;
812 if (expr->getStmtClass() != Stmt::CallExprClass)
813 return false;
815 call = cast<CallExpr>(expr);
816 fd = call->getDirectCallee();
817 if (!fd)
818 return false;
820 if (call->getNumArgs() != 2)
821 return false;
823 name = fd->getDeclName().getAsString();
824 if (name != minmax)
825 return false;
827 lhs = call->getArg(0);
828 rhs = call->getArg(1);
830 return true;
833 /* Check if "expr" is of the form min(lhs, rhs) and if so make
834 * lhs and rhs refer to the two arguments.
836 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
838 return is_minmax(expr, "min", lhs, rhs);
841 /* Check if "expr" is of the form max(lhs, rhs) and if so make
842 * lhs and rhs refer to the two arguments.
844 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
846 return is_minmax(expr, "max", lhs, rhs);
849 /* Extract a set of values satisfying the comparison "LHS op RHS"
850 * "comp" is the original statement that "LHS op RHS" is derived from
851 * and is used for diagnostics.
853 * If the comparison is of the form
855 * a <= min(b,c)
857 * then the set is constructed as the intersection of the set corresponding
858 * to the comparisons
860 * a <= b and a <= c
862 * A similar optimization is performed for max(a,b) <= c.
863 * We do this because that will lead to simpler representations of the set.
864 * If isl is ever enhanced to explicitly deal with min and max expressions,
865 * this optimization can be removed.
867 __isl_give isl_set *PetScan::extract_comparison(BinaryOperatorKind op,
868 Expr *LHS, Expr *RHS, Stmt *comp)
870 isl_pw_aff *lhs;
871 isl_pw_aff *rhs;
872 isl_set *cond;
874 if (op == BO_GT)
875 return extract_comparison(BO_LT, RHS, LHS, comp);
876 if (op == BO_GE)
877 return extract_comparison(BO_LE, RHS, LHS, comp);
879 if (op == BO_LT || op == BO_LE) {
880 Expr *expr1, *expr2;
881 isl_set *set1, *set2;
882 if (is_min(RHS, expr1, expr2)) {
883 set1 = extract_comparison(op, LHS, expr1, comp);
884 set2 = extract_comparison(op, LHS, expr2, comp);
885 return isl_set_intersect(set1, set2);
887 if (is_max(LHS, expr1, expr2)) {
888 set1 = extract_comparison(op, expr1, RHS, comp);
889 set2 = extract_comparison(op, expr2, RHS, comp);
890 return isl_set_intersect(set1, set2);
894 lhs = extract_affine(LHS);
895 rhs = extract_affine(RHS);
897 switch (op) {
898 case BO_LT:
899 cond = isl_pw_aff_lt_set(lhs, rhs);
900 break;
901 case BO_LE:
902 cond = isl_pw_aff_le_set(lhs, rhs);
903 break;
904 case BO_EQ:
905 cond = isl_pw_aff_eq_set(lhs, rhs);
906 break;
907 case BO_NE:
908 cond = isl_pw_aff_ne_set(lhs, rhs);
909 break;
910 default:
911 isl_pw_aff_free(lhs);
912 isl_pw_aff_free(rhs);
913 unsupported(comp);
914 return NULL;
917 cond = isl_set_coalesce(cond);
919 return cond;
922 __isl_give isl_set *PetScan::extract_comparison(BinaryOperator *comp)
924 return extract_comparison(comp->getOpcode(), comp->getLHS(),
925 comp->getRHS(), comp);
928 /* Extract a set of values satisfying the negation (logical not)
929 * of a subexpression.
931 __isl_give isl_set *PetScan::extract_boolean(UnaryOperator *op)
933 isl_set *cond;
935 cond = extract_condition(op->getSubExpr());
937 return isl_set_complement(cond);
940 /* Extract a set of values satisfying the union (logical or)
941 * or intersection (logical and) of two subexpressions.
943 __isl_give isl_set *PetScan::extract_boolean(BinaryOperator *comp)
945 isl_set *lhs;
946 isl_set *rhs;
947 isl_set *cond;
949 lhs = extract_condition(comp->getLHS());
950 rhs = extract_condition(comp->getRHS());
952 switch (comp->getOpcode()) {
953 case BO_LAnd:
954 cond = isl_set_intersect(lhs, rhs);
955 break;
956 case BO_LOr:
957 cond = isl_set_union(lhs, rhs);
958 break;
959 default:
960 isl_set_free(lhs);
961 isl_set_free(rhs);
962 unsupported(comp);
963 return NULL;
966 return cond;
969 __isl_give isl_set *PetScan::extract_condition(UnaryOperator *expr)
971 switch (expr->getOpcode()) {
972 case UO_LNot:
973 return extract_boolean(expr);
974 default:
975 unsupported(expr);
976 return NULL;
980 /* Extract a set of values satisfying the condition "expr != 0".
982 __isl_give isl_set *PetScan::extract_implicit_condition(Expr *expr)
984 return isl_pw_aff_non_zero_set(extract_affine(expr));
987 /* Extract a set of values satisfying the condition expressed by "expr".
989 * If the expression doesn't look like a condition, we assume it
990 * is an affine expression and return the condition "expr != 0".
992 __isl_give isl_set *PetScan::extract_condition(Expr *expr)
994 BinaryOperator *comp;
996 if (!expr)
997 return isl_set_universe(isl_space_params_alloc(ctx, 0));
999 if (expr->getStmtClass() == Stmt::ParenExprClass)
1000 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1002 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1003 return extract_condition(cast<UnaryOperator>(expr));
1005 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1006 return extract_implicit_condition(expr);
1008 comp = cast<BinaryOperator>(expr);
1009 switch (comp->getOpcode()) {
1010 case BO_LT:
1011 case BO_LE:
1012 case BO_GT:
1013 case BO_GE:
1014 case BO_EQ:
1015 case BO_NE:
1016 return extract_comparison(comp);
1017 case BO_LAnd:
1018 case BO_LOr:
1019 return extract_boolean(comp);
1020 default:
1021 return extract_implicit_condition(expr);
1025 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1027 switch (kind) {
1028 case UO_Minus:
1029 return pet_op_minus;
1030 default:
1031 return pet_op_last;
1035 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1037 switch (kind) {
1038 case BO_AddAssign:
1039 return pet_op_add_assign;
1040 case BO_SubAssign:
1041 return pet_op_sub_assign;
1042 case BO_MulAssign:
1043 return pet_op_mul_assign;
1044 case BO_DivAssign:
1045 return pet_op_div_assign;
1046 case BO_Assign:
1047 return pet_op_assign;
1048 case BO_Add:
1049 return pet_op_add;
1050 case BO_Sub:
1051 return pet_op_sub;
1052 case BO_Mul:
1053 return pet_op_mul;
1054 case BO_Div:
1055 return pet_op_div;
1056 case BO_EQ:
1057 return pet_op_eq;
1058 case BO_LE:
1059 return pet_op_le;
1060 case BO_LT:
1061 return pet_op_lt;
1062 case BO_GT:
1063 return pet_op_gt;
1064 default:
1065 return pet_op_last;
1069 /* Construct a pet_expr representing a unary operator expression.
1071 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1073 struct pet_expr *arg;
1074 enum pet_op_type op;
1076 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1077 if (op == pet_op_last) {
1078 unsupported(expr);
1079 return NULL;
1082 arg = extract_expr(expr->getSubExpr());
1084 return pet_expr_new_unary(ctx, op, arg);
1087 /* Mark the given access pet_expr as a write.
1088 * If a scalar is being accessed, then mark its value
1089 * as unknown in assigned_value.
1091 void PetScan::mark_write(struct pet_expr *access)
1093 isl_id *id;
1094 ValueDecl *decl;
1096 access->acc.write = 1;
1097 access->acc.read = 0;
1099 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1100 return;
1102 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1103 decl = (ValueDecl *) isl_id_get_user(id);
1104 assigned_value[decl] = NULL;
1105 isl_id_free(id);
1108 /* Construct a pet_expr representing a binary operator expression.
1110 * If the top level operator is an assignment and the LHS is an access,
1111 * then we mark that access as a write. If the operator is a compound
1112 * assignment, the access is marked as both a read and a write.
1114 * If "expr" assigns something to a scalar variable, then we keep track
1115 * of the assigned expression in assigned_value so that we can plug
1116 * it in when we later come across the same variable.
1118 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1120 struct pet_expr *lhs, *rhs;
1121 enum pet_op_type op;
1123 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1124 if (op == pet_op_last) {
1125 unsupported(expr);
1126 return NULL;
1129 lhs = extract_expr(expr->getLHS());
1130 rhs = extract_expr(expr->getRHS());
1132 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1133 mark_write(lhs);
1134 if (expr->isCompoundAssignmentOp())
1135 lhs->acc.read = 1;
1138 if (expr->getOpcode() == BO_Assign &&
1139 lhs && lhs->type == pet_expr_access &&
1140 isl_map_dim(lhs->acc.access, isl_dim_out) == 0) {
1141 isl_id *id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1142 ValueDecl *decl = (ValueDecl *) isl_id_get_user(id);
1143 assigned_value[decl] = expr->getRHS();
1144 isl_id_free(id);
1147 return pet_expr_new_binary(ctx, op, lhs, rhs);
1150 /* Construct a pet_expr representing a conditional operation.
1152 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1154 struct pet_expr *cond, *lhs, *rhs;
1156 cond = extract_expr(expr->getCond());
1157 lhs = extract_expr(expr->getTrueExpr());
1158 rhs = extract_expr(expr->getFalseExpr());
1160 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1163 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1165 return extract_expr(expr->getSubExpr());
1168 /* Construct a pet_expr representing a floating point value.
1170 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1172 return pet_expr_new_double(ctx, expr->getValueAsApproximateDouble());
1175 /* Extract an access relation from "expr" and then convert it into
1176 * a pet_expr.
1178 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1180 isl_map *access;
1181 struct pet_expr *pe;
1183 switch (expr->getStmtClass()) {
1184 case Stmt::ArraySubscriptExprClass:
1185 access = extract_access(cast<ArraySubscriptExpr>(expr));
1186 break;
1187 case Stmt::DeclRefExprClass:
1188 access = extract_access(cast<DeclRefExpr>(expr));
1189 break;
1190 case Stmt::IntegerLiteralClass:
1191 access = extract_access(cast<IntegerLiteral>(expr));
1192 break;
1193 default:
1194 unsupported(expr);
1195 return NULL;
1198 pe = pet_expr_from_access(access);
1200 return pe;
1203 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1205 return extract_expr(expr->getSubExpr());
1208 /* Construct a pet_expr representing a function call.
1210 * If we are passing along a pointer to an array element
1211 * or an entire row or even higher dimensional slice of an array,
1212 * then the function being called may write into the array.
1214 * We assume here that if the function is declared to take a pointer
1215 * to a const type, then the function will perform a read
1216 * and that otherwise, it will perform a write.
1218 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1220 struct pet_expr *res = NULL;
1221 FunctionDecl *fd;
1222 string name;
1224 fd = expr->getDirectCallee();
1225 if (!fd) {
1226 unsupported(expr);
1227 return NULL;
1230 name = fd->getDeclName().getAsString();
1231 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1232 if (!res)
1233 return NULL;
1235 for (int i = 0; i < expr->getNumArgs(); ++i) {
1236 Expr *arg = expr->getArg(i);
1237 int is_addr = 0;
1239 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1240 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1241 arg = ice->getSubExpr();
1243 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1244 UnaryOperator *op = cast<UnaryOperator>(arg);
1245 if (op->getOpcode() == UO_AddrOf) {
1246 is_addr = 1;
1247 arg = op->getSubExpr();
1250 res->args[i] = PetScan::extract_expr(arg);
1251 if (!res->args[i])
1252 goto error;
1253 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1254 array_depth(arg->getType().getTypePtr()) > 0)
1255 is_addr = 1;
1256 if (is_addr && res->args[i]->type == pet_expr_access) {
1257 ParmVarDecl *parm = fd->getParamDecl(i);
1258 if (!const_base(parm->getType()))
1259 mark_write(res->args[i]);
1263 return res;
1264 error:
1265 pet_expr_free(res);
1266 return NULL;
1269 /* Try and onstruct a pet_expr representing "expr".
1271 struct pet_expr *PetScan::extract_expr(Expr *expr)
1273 switch (expr->getStmtClass()) {
1274 case Stmt::UnaryOperatorClass:
1275 return extract_expr(cast<UnaryOperator>(expr));
1276 case Stmt::CompoundAssignOperatorClass:
1277 case Stmt::BinaryOperatorClass:
1278 return extract_expr(cast<BinaryOperator>(expr));
1279 case Stmt::ImplicitCastExprClass:
1280 return extract_expr(cast<ImplicitCastExpr>(expr));
1281 case Stmt::ArraySubscriptExprClass:
1282 case Stmt::DeclRefExprClass:
1283 case Stmt::IntegerLiteralClass:
1284 return extract_access_expr(expr);
1285 case Stmt::FloatingLiteralClass:
1286 return extract_expr(cast<FloatingLiteral>(expr));
1287 case Stmt::ParenExprClass:
1288 return extract_expr(cast<ParenExpr>(expr));
1289 case Stmt::ConditionalOperatorClass:
1290 return extract_expr(cast<ConditionalOperator>(expr));
1291 case Stmt::CallExprClass:
1292 return extract_expr(cast<CallExpr>(expr));
1293 default:
1294 unsupported(expr);
1296 return NULL;
1299 /* Check if the given initialization statement is an assignment.
1300 * If so, return that assignment. Otherwise return NULL.
1302 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1304 BinaryOperator *ass;
1306 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1307 return NULL;
1309 ass = cast<BinaryOperator>(init);
1310 if (ass->getOpcode() != BO_Assign)
1311 return NULL;
1313 return ass;
1316 /* Check if the given initialization statement is a declaration
1317 * of a single variable.
1318 * If so, return that declaration. Otherwise return NULL.
1320 Decl *PetScan::initialization_declaration(Stmt *init)
1322 DeclStmt *decl;
1324 if (init->getStmtClass() != Stmt::DeclStmtClass)
1325 return NULL;
1327 decl = cast<DeclStmt>(init);
1329 if (!decl->isSingleDecl())
1330 return NULL;
1332 return decl->getSingleDecl();
1335 /* Given the assignment operator in the initialization of a for loop,
1336 * extract the induction variable, i.e., the (integer)variable being
1337 * assigned.
1339 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1341 Expr *lhs;
1342 DeclRefExpr *ref;
1343 ValueDecl *decl;
1344 const Type *type;
1346 lhs = init->getLHS();
1347 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1348 unsupported(init);
1349 return NULL;
1352 ref = cast<DeclRefExpr>(lhs);
1353 decl = ref->getDecl();
1354 type = decl->getType().getTypePtr();
1356 if (!type->isIntegerType()) {
1357 unsupported(lhs);
1358 return NULL;
1361 return decl;
1364 /* Given the initialization statement of a for loop and the single
1365 * declaration in this initialization statement,
1366 * extract the induction variable, i.e., the (integer) variable being
1367 * declared.
1369 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1371 VarDecl *vd;
1373 vd = cast<VarDecl>(decl);
1375 const QualType type = vd->getType();
1376 if (!type->isIntegerType()) {
1377 unsupported(init);
1378 return NULL;
1381 if (!vd->getInit()) {
1382 unsupported(init);
1383 return NULL;
1386 return vd;
1389 /* Check that op is of the form iv++ or iv--.
1390 * "inc" is accordingly set to 1 or -1.
1392 bool PetScan::check_unary_increment(UnaryOperator *op, clang::ValueDecl *iv,
1393 isl_int &inc)
1395 Expr *sub;
1396 DeclRefExpr *ref;
1398 if (!op->isIncrementDecrementOp()) {
1399 unsupported(op);
1400 return false;
1403 if (op->isIncrementOp())
1404 isl_int_set_si(inc, 1);
1405 else
1406 isl_int_set_si(inc, -1);
1408 sub = op->getSubExpr();
1409 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1410 unsupported(op);
1411 return false;
1414 ref = cast<DeclRefExpr>(sub);
1415 if (ref->getDecl() != iv) {
1416 unsupported(op);
1417 return false;
1420 return true;
1423 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1424 * has a single constant expression on a universe domain, then
1425 * put this constant in *user.
1427 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1428 void *user)
1430 isl_int *inc = (isl_int *)user;
1431 int res = 0;
1433 if (!isl_set_plain_is_universe(set) || !isl_aff_is_cst(aff))
1434 res = -1;
1435 else
1436 isl_aff_get_constant(aff, inc);
1438 isl_set_free(set);
1439 isl_aff_free(aff);
1441 return res;
1444 /* Check if op is of the form
1446 * iv = iv + inc
1448 * with inc a constant and set "inc" accordingly.
1450 * We extract an affine expression from the RHS and the subtract iv.
1451 * The result should be a constant.
1453 bool PetScan::check_binary_increment(BinaryOperator *op, clang::ValueDecl *iv,
1454 isl_int &inc)
1456 Expr *lhs;
1457 DeclRefExpr *ref;
1458 isl_id *id;
1459 isl_space *dim;
1460 isl_aff *aff;
1461 isl_pw_aff *val;
1463 if (op->getOpcode() != BO_Assign) {
1464 unsupported(op);
1465 return false;
1468 lhs = op->getLHS();
1469 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1470 unsupported(op);
1471 return false;
1474 ref = cast<DeclRefExpr>(lhs);
1475 if (ref->getDecl() != iv) {
1476 unsupported(op);
1477 return false;
1480 val = extract_affine(op->getRHS());
1482 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1484 dim = isl_space_params_alloc(ctx, 1);
1485 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1486 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1487 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1489 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1491 if (isl_pw_aff_foreach_piece(val, &extract_cst, &inc) < 0) {
1492 isl_pw_aff_free(val);
1493 unsupported(op);
1494 return false;
1497 isl_pw_aff_free(val);
1499 return true;
1502 /* Check that op is of the form iv += cst or iv -= cst.
1503 * "inc" is set to cst or -cst accordingly.
1505 bool PetScan::check_compound_increment(CompoundAssignOperator *op,
1506 clang::ValueDecl *iv, isl_int &inc)
1508 Expr *lhs, *rhs;
1509 DeclRefExpr *ref;
1510 bool neg = false;
1512 BinaryOperatorKind opcode;
1514 opcode = op->getOpcode();
1515 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1516 unsupported(op);
1517 return false;
1519 if (opcode == BO_SubAssign)
1520 neg = true;
1522 lhs = op->getLHS();
1523 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1524 unsupported(op);
1525 return false;
1528 ref = cast<DeclRefExpr>(lhs);
1529 if (ref->getDecl() != iv) {
1530 unsupported(op);
1531 return false;
1534 rhs = op->getRHS();
1536 if (rhs->getStmtClass() == Stmt::UnaryOperatorClass) {
1537 UnaryOperator *op = cast<UnaryOperator>(rhs);
1538 if (op->getOpcode() != UO_Minus) {
1539 unsupported(op);
1540 return false;
1543 neg = !neg;
1545 rhs = op->getSubExpr();
1548 if (rhs->getStmtClass() != Stmt::IntegerLiteralClass) {
1549 unsupported(op);
1550 return false;
1553 extract_int(cast<IntegerLiteral>(rhs), &inc);
1554 if (neg)
1555 isl_int_neg(inc, inc);
1557 return true;
1560 /* Check that the increment of the given for loop increments
1561 * (or decrements) the induction variable "iv".
1562 * "up" is set to true if the induction variable is incremented.
1564 bool PetScan::check_increment(ForStmt *stmt, ValueDecl *iv, isl_int &v)
1566 Stmt *inc = stmt->getInc();
1568 if (!inc) {
1569 unsupported(stmt);
1570 return false;
1573 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1574 return check_unary_increment(cast<UnaryOperator>(inc), iv, v);
1575 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1576 return check_compound_increment(
1577 cast<CompoundAssignOperator>(inc), iv, v);
1578 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1579 return check_binary_increment(cast<BinaryOperator>(inc), iv, v);
1581 unsupported(inc);
1582 return false;
1585 /* Embed the given iteration domain in an extra outer loop
1586 * with induction variable "var".
1587 * If this variable appeared as a parameter in the constraints,
1588 * it is replaced by the new outermost dimension.
1590 static __isl_give isl_set *embed(__isl_take isl_set *set,
1591 __isl_take isl_id *var)
1593 int pos;
1595 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1596 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1597 if (pos >= 0) {
1598 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1599 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1602 isl_id_free(var);
1603 return set;
1606 /* Construct a pet_scop for an infinite loop around the given body.
1608 * We extract a pet_scop for the body and then embed it in a loop with
1609 * iteration domain
1611 * { [t] : t >= 0 }
1613 * and schedule
1615 * { [t] -> [t] }
1617 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1619 isl_id *id;
1620 isl_space *dim;
1621 isl_set *domain;
1622 isl_map *sched;
1623 struct pet_scop *scop;
1625 scop = extract(body);
1626 if (!scop)
1627 return NULL;
1629 id = isl_id_alloc(ctx, "t", NULL);
1630 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1631 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
1632 dim = isl_space_from_domain(isl_set_get_space(domain));
1633 dim = isl_space_add_dims(dim, isl_dim_out, 1);
1634 sched = isl_map_universe(dim);
1635 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
1636 scop = pet_scop_embed(scop, domain, sched, id);
1638 return scop;
1641 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1643 * for (;;)
1644 * body
1647 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1649 return extract_infinite_loop(stmt->getBody());
1652 /* Check if the while loop is of the form
1654 * while (1)
1655 * body
1657 * If so, construct a scop for an infinite loop around body.
1658 * Otherwise, fail.
1660 struct pet_scop *PetScan::extract(WhileStmt *stmt)
1662 Expr *cond;
1663 isl_set *set;
1664 int is_universe;
1666 cond = stmt->getCond();
1667 if (!cond) {
1668 unsupported(stmt);
1669 return NULL;
1672 set = extract_condition(cond);
1673 is_universe = isl_set_plain_is_universe(set);
1674 isl_set_free(set);
1676 if (!is_universe) {
1677 unsupported(stmt);
1678 return NULL;
1681 return extract_infinite_loop(stmt->getBody());
1684 /* Check whether "cond" expresses a simple loop bound
1685 * on the only set dimension.
1686 * In particular, if "up" is set then "cond" should contain only
1687 * upper bounds on the set dimension.
1688 * Otherwise, it should contain only lower bounds.
1690 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
1692 if (isl_int_is_pos(inc))
1693 return !isl_set_dim_has_lower_bound(cond, isl_dim_set, 0);
1694 else
1695 return !isl_set_dim_has_upper_bound(cond, isl_dim_set, 0);
1698 /* Extend a condition on a given iteration of a loop to one that
1699 * imposes the same condition on all previous iterations.
1700 * "domain" expresses the lower [upper] bound on the iterations
1701 * when inc is positive [negative].
1703 * In particular, we construct the condition (when inc is positive)
1705 * forall i' : (domain(i') and i' <= i) => cond(i')
1707 * which is equivalent to
1709 * not exists i' : domain(i') and i' <= i and not cond(i')
1711 * We construct this set by negating cond, applying a map
1713 * { [i'] -> [i] : domain(i') and i' <= i }
1715 * and then negating the result again.
1717 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
1718 __isl_take isl_set *domain, isl_int inc)
1720 isl_map *previous_to_this;
1722 if (isl_int_is_pos(inc))
1723 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
1724 else
1725 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
1727 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
1729 cond = isl_set_complement(cond);
1730 cond = isl_set_apply(cond, previous_to_this);
1731 cond = isl_set_complement(cond);
1733 return cond;
1736 /* Construct a domain of the form
1738 * [id] -> { [] : exists a: id = init + a * inc and a >= 0 }
1740 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
1741 __isl_take isl_pw_aff *init, isl_int inc)
1743 isl_aff *aff;
1744 isl_space *dim;
1745 isl_set *set;
1747 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
1748 dim = isl_pw_aff_get_domain_space(init);
1749 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1750 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
1751 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
1753 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
1754 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1755 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1756 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1758 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
1760 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
1762 return isl_set_project_out(set, isl_dim_set, 0, 1);
1765 static unsigned get_type_size(ValueDecl *decl)
1767 return decl->getASTContext().getIntWidth(decl->getType());
1770 /* Assuming "cond" represents a simple bound on a loop where the loop
1771 * iterator "iv" is incremented (or decremented) by one, check if wrapping
1772 * is possible.
1774 * Under the given assumptions, wrapping is only possible if "cond" allows
1775 * for the last value before wrapping, i.e., 2^width - 1 in case of an
1776 * increasing iterator and 0 in case of a decreasing iterator.
1778 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
1780 bool cw;
1781 isl_int limit;
1782 isl_set *test;
1784 test = isl_set_copy(cond);
1786 isl_int_init(limit);
1787 if (isl_int_is_neg(inc))
1788 isl_int_set_si(limit, 0);
1789 else {
1790 isl_int_set_si(limit, 1);
1791 isl_int_mul_2exp(limit, limit, get_type_size(iv));
1792 isl_int_sub_ui(limit, limit, 1);
1795 test = isl_set_fix(cond, isl_dim_set, 0, limit);
1796 cw = !isl_set_is_empty(test);
1797 isl_set_free(test);
1799 isl_int_clear(limit);
1801 return cw;
1804 /* Given a one-dimensional space, construct the following mapping on this
1805 * space
1807 * { [v] -> [v mod 2^width] }
1809 * where width is the number of bits used to represent the values
1810 * of the unsigned variable "iv".
1812 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
1813 ValueDecl *iv)
1815 isl_int mod;
1816 isl_aff *aff;
1817 isl_map *map;
1819 isl_int_init(mod);
1820 isl_int_set_si(mod, 1);
1821 isl_int_mul_2exp(mod, mod, get_type_size(iv));
1823 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1824 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1825 aff = isl_aff_mod(aff, mod);
1827 isl_int_clear(mod);
1829 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
1830 map = isl_map_reverse(map);
1833 /* Construct a pet_scop for a for statement.
1834 * The for loop is required to be of the form
1836 * for (i = init; condition; ++i)
1838 * or
1840 * for (i = init; condition; --i)
1842 * The initialization of the for loop should either be an assignment
1843 * to an integer variable, or a declaration of such a variable with
1844 * initialization.
1846 * The condition is allowed to contain nested accesses, provided
1847 * they are not being written to inside the body of the loop.
1849 * We extract a pet_scop for the body and then embed it in a loop with
1850 * iteration domain and schedule
1852 * { [i] : i >= init and condition' }
1853 * { [i] -> [i] }
1855 * or
1857 * { [i] : i <= init and condition' }
1858 * { [i] -> [-i] }
1860 * Where condition' is equal to condition if the latter is
1861 * a simple upper [lower] bound and a condition that is extended
1862 * to apply to all previous iterations otherwise.
1864 * If the stride of the loop is not 1, then "i >= init" is replaced by
1866 * (exists a: i = init + stride * a and a >= 0)
1868 * If the loop iterator i is unsigned, then wrapping may occur.
1869 * During the computation, we work with a virtual iterator that
1870 * does not wrap. However, the condition in the code applies
1871 * to the wrapped value, so we need to change condition(i)
1872 * into condition([i % 2^width]).
1873 * After computing the virtual domain and schedule, we apply
1874 * the function { [v] -> [v % 2^width] } to the domain and the domain
1875 * of the schedule. In order not to lose any information, we also
1876 * need to intersect the domain of the schedule with the virtual domain
1877 * first, since some iterations in the wrapped domain may be scheduled
1878 * several times, typically an infinite number of times.
1879 * Note that there is no need to perform this final wrapping
1880 * if the loop condition (after wrapping) is simple.
1882 * Wrapping on unsigned iterators can be avoided entirely if
1883 * loop condition is simple, the loop iterator is incremented
1884 * [decremented] by one and the last value before wrapping cannot
1885 * possibly satisfy the loop condition.
1887 * Before extracting a pet_scop from the body we remove all
1888 * assignments in assigned_value to variables that are assigned
1889 * somewhere in the body of the loop.
1891 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
1893 BinaryOperator *ass;
1894 Decl *decl;
1895 Stmt *init;
1896 Expr *lhs, *rhs;
1897 ValueDecl *iv;
1898 isl_space *dim;
1899 isl_set *domain;
1900 isl_map *sched;
1901 isl_set *cond = NULL;
1902 isl_id *id;
1903 struct pet_scop *scop;
1904 assigned_value_cache cache(assigned_value);
1905 isl_int inc;
1906 bool is_one;
1907 bool is_unsigned;
1908 bool is_simple;
1909 isl_map *wrap = NULL;
1911 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
1912 return extract_infinite_for(stmt);
1914 init = stmt->getInit();
1915 if (!init) {
1916 unsupported(stmt);
1917 return NULL;
1919 if ((ass = initialization_assignment(init)) != NULL) {
1920 iv = extract_induction_variable(ass);
1921 if (!iv)
1922 return NULL;
1923 lhs = ass->getLHS();
1924 rhs = ass->getRHS();
1925 } else if ((decl = initialization_declaration(init)) != NULL) {
1926 VarDecl *var = extract_induction_variable(init, decl);
1927 if (!var)
1928 return NULL;
1929 iv = var;
1930 rhs = var->getInit();
1931 lhs = DeclRefExpr::Create(iv->getASTContext(),
1932 var->getQualifierLoc(), iv, var->getInnerLocStart(),
1933 var->getType(), VK_LValue);
1934 } else {
1935 unsupported(stmt->getInit());
1936 return NULL;
1939 isl_int_init(inc);
1940 if (!check_increment(stmt, iv, inc)) {
1941 isl_int_clear(inc);
1942 return NULL;
1945 is_unsigned = iv->getType()->isUnsignedIntegerType();
1947 assigned_value.erase(iv);
1948 clear_assignments clear(assigned_value);
1949 clear.TraverseStmt(stmt->getBody());
1951 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1953 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
1954 if (is_one)
1955 domain = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
1956 lhs, rhs, init);
1957 else {
1958 isl_pw_aff *lb = extract_affine(rhs);
1959 domain = strided_domain(isl_id_copy(id), lb, inc);
1962 scop = extract(stmt->getBody());
1964 cond = try_extract_nested_condition(stmt->getCond());
1965 if (cond && !is_nested_allowed(cond, scop)) {
1966 isl_set_free(cond);
1967 cond = NULL;
1970 if (!cond)
1971 cond = extract_condition(stmt->getCond());
1972 cond = embed(cond, isl_id_copy(id));
1973 domain = embed(domain, isl_id_copy(id));
1974 is_simple = is_simple_bound(cond, inc);
1975 if (is_unsigned &&
1976 (!is_simple || !is_one || can_wrap(cond, iv, inc))) {
1977 wrap = compute_wrapping(isl_set_get_space(cond), iv);
1978 cond = isl_set_apply(cond, isl_map_reverse(isl_map_copy(wrap)));
1979 is_simple = is_simple && is_simple_bound(cond, inc);
1981 if (!is_simple)
1982 cond = valid_for_each_iteration(cond,
1983 isl_set_copy(domain), inc);
1984 domain = isl_set_intersect(domain, cond);
1985 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
1986 dim = isl_space_from_domain(isl_set_get_space(domain));
1987 dim = isl_space_add_dims(dim, isl_dim_out, 1);
1988 sched = isl_map_universe(dim);
1989 if (isl_int_is_pos(inc))
1990 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
1991 else
1992 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
1994 if (is_unsigned && !is_simple) {
1995 wrap = isl_map_set_dim_id(wrap,
1996 isl_dim_out, 0, isl_id_copy(id));
1997 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
1998 domain = isl_set_apply(domain, isl_map_copy(wrap));
1999 sched = isl_map_apply_domain(sched, wrap);
2000 } else
2001 isl_map_free(wrap);
2003 scop = pet_scop_embed(scop, domain, sched, id);
2004 scop = resolve_nested(scop);
2005 assigned_value[iv] = NULL;
2007 isl_int_clear(inc);
2008 return scop;
2011 struct pet_scop *PetScan::extract(CompoundStmt *stmt)
2013 return extract(stmt->children());
2016 /* Does "id" refer to a nested access?
2018 static bool is_nested_parameter(__isl_keep isl_id *id)
2020 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2023 /* Does parameter "pos" of "space" refer to a nested access?
2025 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2027 bool nested;
2028 isl_id *id;
2030 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2031 nested = is_nested_parameter(id);
2032 isl_id_free(id);
2034 return nested;
2037 /* Does parameter "pos" of "map" refer to a nested access?
2039 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2041 bool nested;
2042 isl_id *id;
2044 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2045 nested = is_nested_parameter(id);
2046 isl_id_free(id);
2048 return nested;
2051 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2053 static int n_nested_parameter(__isl_keep isl_space *space)
2055 int n = 0;
2056 int nparam;
2058 nparam = isl_space_dim(space, isl_dim_param);
2059 for (int i = 0; i < nparam; ++i)
2060 if (is_nested_parameter(space, i))
2061 ++n;
2063 return n;
2066 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2068 static int n_nested_parameter(__isl_keep isl_map *map)
2070 isl_space *space;
2071 int n;
2073 space = isl_map_get_space(map);
2074 n = n_nested_parameter(space);
2075 isl_space_free(space);
2077 return n;
2080 /* For each nested access parameter in "space",
2081 * construct a corresponding pet_expr, place it in args and
2082 * record its position in "param2pos".
2083 * "n_arg" is the number of elements that are already in args.
2084 * The position recorded in "param2pos" takes this number into account.
2085 * If the pet_expr corresponding to a parameter is identical to
2086 * the pet_expr corresponding to an earlier parameter, then these two
2087 * parameters are made to refer to the same element in args.
2089 * Return the final number of elements in args or -1 if an error has occurred.
2091 int PetScan::extract_nested(__isl_keep isl_space *space,
2092 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
2094 int nparam;
2096 nparam = isl_space_dim(space, isl_dim_param);
2097 for (int i = 0; i < nparam; ++i) {
2098 int j;
2099 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
2100 Expr *nested;
2102 if (!is_nested_parameter(id)) {
2103 isl_id_free(id);
2104 continue;
2107 nested = (Expr *) isl_id_get_user(id);
2108 args[n_arg] = extract_expr(nested);
2109 if (!args[n_arg])
2110 return -1;
2112 for (j = 0; j < n_arg; ++j)
2113 if (pet_expr_is_equal(args[j], args[n_arg]))
2114 break;
2116 if (j < n_arg) {
2117 pet_expr_free(args[n_arg]);
2118 args[n_arg] = NULL;
2119 param2pos[i] = j;
2120 } else
2121 param2pos[i] = n_arg++;
2123 isl_id_free(id);
2126 return n_arg;
2129 /* For each nested access parameter in the access relations in "expr",
2130 * construct a corresponding pet_expr, place it in expr->args and
2131 * record its position in "param2pos".
2132 * n is the number of nested access parameters.
2134 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
2135 std::map<int,int> &param2pos)
2137 isl_space *space;
2139 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
2140 expr->n_arg = n;
2141 if (!expr->args)
2142 goto error;
2144 space = isl_map_get_space(expr->acc.access);
2145 n = extract_nested(space, 0, expr->args, param2pos);
2146 isl_space_free(space);
2148 if (n < 0)
2149 goto error;
2151 expr->n_arg = n;
2152 return expr;
2153 error:
2154 pet_expr_free(expr);
2155 return NULL;
2158 /* Look for parameters in any access relation in "expr" that
2159 * refer to nested accesses. In particular, these are
2160 * parameters with no name.
2162 * If there are any such parameters, then the domain of the access
2163 * relation, which is still [] at this point, is replaced by
2164 * [[] -> [t_1,...,t_n]], with n the number of these parameters
2165 * (after identifying identical nested accesses).
2166 * The parameters are then equated to the corresponding t dimensions
2167 * and subsequently projected out.
2168 * param2pos maps the position of the parameter to the position
2169 * of the corresponding t dimension.
2171 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
2173 int n;
2174 int nparam;
2175 int n_in;
2176 isl_space *dim;
2177 isl_map *map;
2178 std::map<int,int> param2pos;
2180 if (!expr)
2181 return expr;
2183 for (int i = 0; i < expr->n_arg; ++i) {
2184 expr->args[i] = resolve_nested(expr->args[i]);
2185 if (!expr->args[i]) {
2186 pet_expr_free(expr);
2187 return NULL;
2191 if (expr->type != pet_expr_access)
2192 return expr;
2194 n = n_nested_parameter(expr->acc.access);
2195 if (n == 0)
2196 return expr;
2198 expr = extract_nested(expr, n, param2pos);
2199 if (!expr)
2200 return NULL;
2202 n = expr->n_arg;
2203 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
2204 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
2205 dim = isl_map_get_space(expr->acc.access);
2206 dim = isl_space_domain(dim);
2207 dim = isl_space_from_domain(dim);
2208 dim = isl_space_add_dims(dim, isl_dim_out, n);
2209 map = isl_map_universe(dim);
2210 map = isl_map_domain_map(map);
2211 map = isl_map_reverse(map);
2212 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
2214 for (int i = nparam - 1; i >= 0; --i) {
2215 isl_id *id = isl_map_get_dim_id(expr->acc.access,
2216 isl_dim_param, i);
2217 if (!is_nested_parameter(id)) {
2218 isl_id_free(id);
2219 continue;
2222 expr->acc.access = isl_map_equate(expr->acc.access,
2223 isl_dim_param, i, isl_dim_in,
2224 n_in + param2pos[i]);
2225 expr->acc.access = isl_map_project_out(expr->acc.access,
2226 isl_dim_param, i, 1);
2228 isl_id_free(id);
2231 return expr;
2232 error:
2233 pet_expr_free(expr);
2234 return NULL;
2237 /* Convert a top-level pet_expr to a pet_scop with one statement.
2238 * This mainly involves resolving nested expression parameters
2239 * and setting the name of the iteration space.
2240 * The name is given by "label" if it is non-NULL. Otherwise,
2241 * it is of the form S_<n_stmt>.
2243 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
2244 __isl_take isl_id *label)
2246 struct pet_stmt *ps;
2247 SourceLocation loc = stmt->getLocStart();
2248 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2250 expr = resolve_nested(expr);
2251 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
2252 return pet_scop_from_pet_stmt(ctx, ps);
2255 /* Check whether "expr" is an affine expression.
2256 * We turn on autodetection so that we won't generate any warnings
2257 * and turn off nesting, so that we won't accept any non-affine constructs.
2259 bool PetScan::is_affine(Expr *expr)
2261 isl_pw_aff *pwaff;
2262 int save_autodetect = autodetect;
2263 bool save_nesting = nesting_enabled;
2265 autodetect = 1;
2266 nesting_enabled = false;
2268 pwaff = extract_affine(expr);
2269 isl_pw_aff_free(pwaff);
2271 autodetect = save_autodetect;
2272 nesting_enabled = save_nesting;
2274 return pwaff != NULL;
2277 /* Check whether "expr" is an affine constraint.
2278 * We turn on autodetection so that we won't generate any warnings
2279 * and turn off nesting, so that we won't accept any non-affine constructs.
2281 bool PetScan::is_affine_condition(Expr *expr)
2283 isl_set *set;
2284 int save_autodetect = autodetect;
2285 bool save_nesting = nesting_enabled;
2287 autodetect = 1;
2288 nesting_enabled = false;
2290 set = extract_condition(expr);
2291 isl_set_free(set);
2293 autodetect = save_autodetect;
2294 nesting_enabled = save_nesting;
2296 return set != NULL;
2299 /* Check if we can extract a condition from "expr".
2300 * Return the condition as an isl_set if we can and NULL otherwise.
2301 * If allow_nested is set, then the condition may involve parameters
2302 * corresponding to nested accesses.
2303 * We turn on autodetection so that we won't generate any warnings.
2305 __isl_give isl_set *PetScan::try_extract_nested_condition(Expr *expr)
2307 isl_set *set;
2308 int save_autodetect = autodetect;
2309 bool save_nesting = nesting_enabled;
2311 autodetect = 1;
2312 nesting_enabled = allow_nested;
2313 set = extract_condition(expr);
2315 autodetect = save_autodetect;
2316 nesting_enabled = save_nesting;
2318 return set;
2321 /* If the top-level expression of "stmt" is an assignment, then
2322 * return that assignment as a BinaryOperator.
2323 * Otherwise return NULL.
2325 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
2327 BinaryOperator *ass;
2329 if (!stmt)
2330 return NULL;
2331 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
2332 return NULL;
2334 ass = cast<BinaryOperator>(stmt);
2335 if(ass->getOpcode() != BO_Assign)
2336 return NULL;
2338 return ass;
2341 /* Check if the given if statement is a conditional assignement
2342 * with a non-affine condition. If so, construct a pet_scop
2343 * corresponding to this conditional assignment. Otherwise return NULL.
2345 * In particular we check if "stmt" is of the form
2347 * if (condition)
2348 * a = f(...);
2349 * else
2350 * a = g(...);
2352 * where a is some array or scalar access.
2353 * The constructed pet_scop then corresponds to the expression
2355 * a = condition ? f(...) : g(...)
2357 * All access relations in f(...) are intersected with condition
2358 * while all access relation in g(...) are intersected with the complement.
2360 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
2362 BinaryOperator *ass_then, *ass_else;
2363 isl_map *write_then, *write_else;
2364 isl_set *cond, *comp;
2365 isl_map *map, *map_true, *map_false;
2366 int equal;
2367 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
2368 bool save_nesting = nesting_enabled;
2370 ass_then = top_assignment_or_null(stmt->getThen());
2371 ass_else = top_assignment_or_null(stmt->getElse());
2373 if (!ass_then || !ass_else)
2374 return NULL;
2376 if (is_affine_condition(stmt->getCond()))
2377 return NULL;
2379 write_then = extract_access(ass_then->getLHS());
2380 write_else = extract_access(ass_else->getLHS());
2382 equal = isl_map_is_equal(write_then, write_else);
2383 isl_map_free(write_else);
2384 if (equal < 0 || !equal) {
2385 isl_map_free(write_then);
2386 return NULL;
2389 nesting_enabled = allow_nested;
2390 cond = extract_condition(stmt->getCond());
2391 nesting_enabled = save_nesting;
2392 comp = isl_set_complement(isl_set_copy(cond));
2393 map_true = isl_map_from_domain(isl_set_from_params(isl_set_copy(cond)));
2394 map_true = isl_map_add_dims(map_true, isl_dim_out, 1);
2395 map_true = isl_map_fix_si(map_true, isl_dim_out, 0, 1);
2396 map_false = isl_map_from_domain(isl_set_from_params(isl_set_copy(comp)));
2397 map_false = isl_map_add_dims(map_false, isl_dim_out, 1);
2398 map_false = isl_map_fix_si(map_false, isl_dim_out, 0, 0);
2399 map = isl_map_union_disjoint(map_true, map_false);
2401 pe_cond = pet_expr_from_access(map);
2403 pe_then = extract_expr(ass_then->getRHS());
2404 pe_then = pet_expr_restrict(pe_then, cond);
2405 pe_else = extract_expr(ass_else->getRHS());
2406 pe_else = pet_expr_restrict(pe_else, comp);
2408 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
2409 pe_write = pet_expr_from_access(write_then);
2410 if (pe_write) {
2411 pe_write->acc.write = 1;
2412 pe_write->acc.read = 0;
2414 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
2415 return extract(stmt, pe);
2418 /* Create an access to a virtual array representing the result
2419 * of a condition.
2420 * Unlike other accessed data, the id of the array is NULL as
2421 * there is no ValueDecl in the program corresponding to the virtual
2422 * array.
2423 * The array starts out as a scalar, but grows along with the
2424 * statement writing to the array in pet_scop_embed.
2426 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2428 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2429 isl_id *id;
2430 char name[50];
2432 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2433 id = isl_id_alloc(ctx, name, NULL);
2434 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2435 return isl_map_universe(dim);
2438 /* Create a pet_scop with a single statement evaluating "cond"
2439 * and writing the result to a virtual scalar, as expressed by
2440 * "access".
2442 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
2443 __isl_take isl_map *access)
2445 struct pet_expr *expr, *write;
2446 struct pet_stmt *ps;
2447 SourceLocation loc = cond->getLocStart();
2448 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2450 write = pet_expr_from_access(access);
2451 if (write) {
2452 write->acc.write = 1;
2453 write->acc.read = 0;
2455 expr = extract_expr(cond);
2456 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
2457 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
2458 return pet_scop_from_pet_stmt(ctx, ps);
2461 /* Add an array with the given extend ("access") to the list
2462 * of arrays in "scop" and return the extended pet_scop.
2463 * The array is marked as attaining values 0 and 1 only.
2465 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2466 __isl_keep isl_map *access)
2468 isl_ctx *ctx = isl_map_get_ctx(access);
2469 isl_space *dim;
2470 struct pet_array **arrays;
2471 struct pet_array *array;
2473 if (!scop)
2474 return NULL;
2475 if (!ctx)
2476 goto error;
2478 arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2479 scop->n_array + 1);
2480 if (!arrays)
2481 goto error;
2482 scop->arrays = arrays;
2484 array = isl_calloc_type(ctx, struct pet_array);
2485 if (!array)
2486 goto error;
2488 array->extent = isl_map_range(isl_map_copy(access));
2489 dim = isl_space_params_alloc(ctx, 0);
2490 array->context = isl_set_universe(dim);
2491 dim = isl_space_set_alloc(ctx, 0, 1);
2492 array->value_bounds = isl_set_universe(dim);
2493 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2494 isl_dim_set, 0, 0);
2495 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2496 isl_dim_set, 0, 1);
2497 array->element_type = strdup("int");
2499 scop->arrays[scop->n_array] = array;
2500 scop->n_array++;
2502 if (!array->extent || !array->context)
2503 goto error;
2505 return scop;
2506 error:
2507 pet_scop_free(scop);
2508 return NULL;
2511 extern "C" {
2512 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
2513 void *user);
2516 /* Apply the map pointed to by "user" to the domain of the access
2517 * relation, thereby embedding it in the range of the map.
2518 * The domain of both relations is the zero-dimensional domain.
2520 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
2522 isl_map *map = (isl_map *) user;
2524 return isl_map_apply_domain(access, isl_map_copy(map));
2527 /* Apply "map" to all access relations in "expr".
2529 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
2531 return pet_expr_foreach_access(expr, &embed_access, map);
2534 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
2536 static int n_nested_parameter(__isl_keep isl_set *set)
2538 isl_space *space;
2539 int n;
2541 space = isl_set_get_space(set);
2542 n = n_nested_parameter(space);
2543 isl_space_free(space);
2545 return n;
2548 /* Remove all parameters from "map" that refer to nested accesses.
2550 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
2552 int nparam;
2553 isl_space *space;
2555 space = isl_map_get_space(map);
2556 nparam = isl_space_dim(space, isl_dim_param);
2557 for (int i = nparam - 1; i >= 0; --i)
2558 if (is_nested_parameter(space, i))
2559 map = isl_map_project_out(map, isl_dim_param, i, 1);
2560 isl_space_free(space);
2562 return map;
2565 extern "C" {
2566 static __isl_give isl_map *access_remove_nested_parameters(
2567 __isl_take isl_map *access, void *user);
2570 static __isl_give isl_map *access_remove_nested_parameters(
2571 __isl_take isl_map *access, void *user)
2573 return remove_nested_parameters(access);
2576 /* Remove all nested access parameters from the schedule and all
2577 * accesses of "stmt".
2578 * There is no need to remove them from the domain as these parameters
2579 * have already been removed from the domain when this function is called.
2581 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
2583 if (!stmt)
2584 return NULL;
2585 stmt->schedule = remove_nested_parameters(stmt->schedule);
2586 stmt->body = pet_expr_foreach_access(stmt->body,
2587 &access_remove_nested_parameters, NULL);
2588 if (!stmt->schedule || !stmt->body)
2589 goto error;
2590 for (int i = 0; i < stmt->n_arg; ++i) {
2591 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
2592 &access_remove_nested_parameters, NULL);
2593 if (!stmt->args[i])
2594 goto error;
2597 return stmt;
2598 error:
2599 pet_stmt_free(stmt);
2600 return NULL;
2603 /* For each nested access parameter in the domain of "stmt",
2604 * construct a corresponding pet_expr, place it in stmt->args and
2605 * record its position in "param2pos".
2606 * n is the number of nested access parameters.
2608 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
2609 std::map<int,int> &param2pos)
2611 isl_space *space;
2612 unsigned n_arg;
2613 struct pet_expr **args;
2615 n_arg = stmt->n_arg;
2616 args = isl_realloc_array(ctx, stmt->args, struct pet_expr *, n_arg + n);
2617 if (!args)
2618 goto error;
2619 stmt->args = args;
2620 stmt->n_arg += n;
2622 space = isl_set_get_space(stmt->domain);
2623 n = extract_nested(space, n_arg, stmt->args, param2pos);
2624 isl_space_free(space);
2626 if (n < 0)
2627 goto error;
2629 stmt->n_arg = n;
2630 return stmt;
2631 error:
2632 pet_stmt_free(stmt);
2633 return NULL;
2636 /* Look for parameters in the iteration domain of "stmt" taht
2637 * refer to nested accesses. In particular, these are
2638 * parameters with no name.
2640 * If there are any such parameters, then as many extra variables
2641 * (after identifying identical nested accesses) are added to the
2642 * range of the map wrapped inside the domain.
2643 * If the original domain is not a wrapped map, then a new wrapped
2644 * map is created with zero output dimensions.
2645 * The parameters are then equated to the corresponding output dimensions
2646 * and subsequently projected out, from the iteration domain,
2647 * the schedule and the access relations.
2648 * For each of the output dimensions, a corresponding argument
2649 * expression is added. Initially they are created with
2650 * a zero-dimensional domain, so they have to be embedded
2651 * in the current iteration domain.
2652 * param2pos maps the position of the parameter to the position
2653 * of the corresponding output dimension in the wrapped map.
2655 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
2657 int n;
2658 int nparam;
2659 unsigned n_arg;
2660 isl_map *map;
2661 std::map<int,int> param2pos;
2663 if (!stmt)
2664 return NULL;
2666 n = n_nested_parameter(stmt->domain);
2667 if (n == 0)
2668 return stmt;
2670 n_arg = stmt->n_arg;
2671 stmt = extract_nested(stmt, n, param2pos);
2672 if (!stmt)
2673 return NULL;
2675 n = stmt->n_arg - n_arg;
2676 nparam = isl_set_dim(stmt->domain, isl_dim_param);
2677 if (isl_set_is_wrapping(stmt->domain))
2678 map = isl_set_unwrap(stmt->domain);
2679 else
2680 map = isl_map_from_domain(stmt->domain);
2681 map = isl_map_add_dims(map, isl_dim_out, n);
2683 for (int i = nparam - 1; i >= 0; --i) {
2684 isl_id *id;
2686 if (!is_nested_parameter(map, i))
2687 continue;
2689 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
2690 isl_dim_out);
2691 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
2692 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
2693 param2pos[i]);
2694 map = isl_map_project_out(map, isl_dim_param, i, 1);
2697 stmt->domain = isl_map_wrap(map);
2699 map = isl_set_unwrap(isl_set_copy(stmt->domain));
2700 map = isl_map_from_range(isl_map_domain(map));
2701 for (int pos = n_arg; pos < stmt->n_arg; ++pos)
2702 stmt->args[pos] = embed(stmt->args[pos], map);
2703 isl_map_free(map);
2705 stmt = remove_nested_parameters(stmt);
2707 return stmt;
2708 error:
2709 pet_stmt_free(stmt);
2710 return NULL;
2713 /* For each statement in "scop", move the parameters that correspond
2714 * to nested access into the ranges of the domains and create
2715 * corresponding argument expressions.
2717 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
2719 if (!scop)
2720 return NULL;
2722 for (int i = 0; i < scop->n_stmt; ++i) {
2723 scop->stmts[i] = resolve_nested(scop->stmts[i]);
2724 if (!scop->stmts[i])
2725 goto error;
2728 return scop;
2729 error:
2730 pet_scop_free(scop);
2731 return NULL;
2734 /* Does "space" involve any parameters that refer to nested
2735 * accesses, i.e., parameters with no name?
2737 static bool has_nested(__isl_keep isl_space *space)
2739 int nparam;
2741 nparam = isl_space_dim(space, isl_dim_param);
2742 for (int i = 0; i < nparam; ++i)
2743 if (is_nested_parameter(space, i))
2744 return true;
2746 return false;
2749 /* Does "set" involve any parameters that refer to nested
2750 * accesses, i.e., parameters with no name?
2752 static bool has_nested(__isl_keep isl_set *set)
2754 isl_space *space;
2755 bool nested;
2757 space = isl_set_get_space(set);
2758 nested = has_nested(space);
2759 isl_space_free(space);
2761 return nested;
2764 /* Given an access expression "expr", is the variable accessed by
2765 * "expr" assigned anywhere inside "scop"?
2767 static bool is_assigned(pet_expr *expr, pet_scop *scop)
2769 bool assigned = false;
2770 isl_id *id;
2772 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
2773 assigned = pet_scop_writes(scop, id);
2774 isl_id_free(id);
2776 return assigned;
2779 /* Are all nested access parameters in "set" allowed given "scop".
2780 * In particular, is none of them written by anywhere inside "scop".
2782 bool PetScan::is_nested_allowed(__isl_keep isl_set *set, pet_scop *scop)
2784 int nparam;
2786 nparam = isl_set_dim(set, isl_dim_param);
2787 for (int i = 0; i < nparam; ++i) {
2788 Expr *nested;
2789 isl_id *id = isl_set_get_dim_id(set, isl_dim_param, i);
2790 pet_expr *expr;
2791 bool allowed;
2793 if (!is_nested_parameter(id)) {
2794 isl_id_free(id);
2795 continue;
2798 nested = (Expr *) isl_id_get_user(id);
2799 expr = extract_expr(nested);
2800 allowed = expr && expr->type == pet_expr_access &&
2801 !is_assigned(expr, scop);
2803 pet_expr_free(expr);
2804 isl_id_free(id);
2806 if (!allowed)
2807 return false;
2810 return true;
2813 /* Construct a pet_scop for an if statement.
2815 * If the condition fits the pattern of a conditional assignment,
2816 * then it is handled by extract_conditional_assignment.
2817 * Otherwise, we do the following.
2819 * If the condition is affine, then the condition is added
2820 * to the iteration domains of the then branch, while the
2821 * opposite of the condition in added to the iteration domains
2822 * of the else branch, if any.
2823 * We allow the condition to be dynamic, i.e., to refer to
2824 * scalars or array elements that may be written to outside
2825 * of the given if statement. These nested accesses are then represented
2826 * as output dimensions in the wrapping iteration domain.
2827 * If it also written _inside_ the then or else branch, then
2828 * we treat the condition as non-affine.
2829 * As explained below, this will introduce an extra statement.
2830 * For aesthetic reasons, we want this statement to have a statement
2831 * number that is lower than those of the then and else branches.
2832 * In order to evaluate if will need such a statement, however, we
2833 * first construct scops for the then and else branches.
2834 * We therefore reserve a statement number if we might have to
2835 * introduce such an extra statement.
2837 * If the condition is not affine, then we create a separate
2838 * statement that write the result of the condition to a virtual scalar.
2839 * A constraint requiring the value of this virtual scalar to be one
2840 * is added to the iteration domains of the then branch.
2841 * Similarly, a constraint requiring the value of this virtual scalar
2842 * to be zero is added to the iteration domains of the else branch, if any.
2843 * We adjust the schedules to ensure that the virtual scalar is written
2844 * before it is read.
2846 struct pet_scop *PetScan::extract(IfStmt *stmt)
2848 struct pet_scop *scop_then, *scop_else, *scop;
2849 assigned_value_cache cache(assigned_value);
2850 isl_map *test_access = NULL;
2851 isl_set *cond;
2852 int stmt_id;
2854 scop = extract_conditional_assignment(stmt);
2855 if (scop)
2856 return scop;
2858 cond = try_extract_nested_condition(stmt->getCond());
2859 if (allow_nested && (!cond || has_nested(cond)))
2860 stmt_id = n_stmt++;
2862 scop_then = extract(stmt->getThen());
2864 if (stmt->getElse()) {
2865 scop_else = extract(stmt->getElse());
2866 if (autodetect) {
2867 if (scop_then && !scop_else) {
2868 partial = true;
2869 isl_set_free(cond);
2870 return scop_then;
2872 if (!scop_then && scop_else) {
2873 partial = true;
2874 isl_set_free(cond);
2875 return scop_else;
2880 if (cond &&
2881 (!is_nested_allowed(cond, scop_then) ||
2882 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
2883 isl_set_free(cond);
2884 cond = NULL;
2886 if (allow_nested && !cond) {
2887 int save_n_stmt = n_stmt;
2888 test_access = create_test_access(ctx, n_test++);
2889 n_stmt = stmt_id;
2890 scop = extract_non_affine_condition(stmt->getCond(),
2891 isl_map_copy(test_access));
2892 n_stmt = save_n_stmt;
2893 scop = scop_add_array(scop, test_access);
2894 if (!scop) {
2895 pet_scop_free(scop_then);
2896 pet_scop_free(scop_else);
2897 isl_map_free(test_access);
2898 return NULL;
2902 if (!scop) {
2903 if (!cond)
2904 cond = extract_condition(stmt->getCond());
2905 scop = pet_scop_restrict(scop_then, isl_set_copy(cond));
2907 if (stmt->getElse()) {
2908 cond = isl_set_complement(cond);
2909 scop_else = pet_scop_restrict(scop_else, cond);
2910 scop = pet_scop_add(ctx, scop, scop_else);
2911 } else
2912 isl_set_free(cond);
2913 scop = resolve_nested(scop);
2914 } else {
2915 scop = pet_scop_prefix(scop, 0);
2916 scop_then = pet_scop_prefix(scop_then, 1);
2917 scop_then = pet_scop_filter(scop_then,
2918 isl_map_copy(test_access), 1);
2919 scop = pet_scop_add(ctx, scop, scop_then);
2920 if (stmt->getElse()) {
2921 scop_else = pet_scop_prefix(scop_else, 1);
2922 scop_else = pet_scop_filter(scop_else, test_access, 0);
2923 scop = pet_scop_add(ctx, scop, scop_else);
2924 } else
2925 isl_map_free(test_access);
2928 return scop;
2931 /* Try and construct a pet_scop for a label statement.
2932 * We currently only allow labels on expression statements.
2934 struct pet_scop *PetScan::extract(LabelStmt *stmt)
2936 isl_id *label;
2937 Stmt *sub;
2939 sub = stmt->getSubStmt();
2940 if (!isa<Expr>(sub)) {
2941 unsupported(stmt);
2942 return NULL;
2945 label = isl_id_alloc(ctx, stmt->getName(), NULL);
2947 return extract(sub, extract_expr(cast<Expr>(sub)), label);
2950 /* Try and construct a pet_scop corresponding to "stmt".
2952 struct pet_scop *PetScan::extract(Stmt *stmt)
2954 if (isa<Expr>(stmt))
2955 return extract(stmt, extract_expr(cast<Expr>(stmt)));
2957 switch (stmt->getStmtClass()) {
2958 case Stmt::WhileStmtClass:
2959 return extract(cast<WhileStmt>(stmt));
2960 case Stmt::ForStmtClass:
2961 return extract_for(cast<ForStmt>(stmt));
2962 case Stmt::IfStmtClass:
2963 return extract(cast<IfStmt>(stmt));
2964 case Stmt::CompoundStmtClass:
2965 return extract(cast<CompoundStmt>(stmt));
2966 case Stmt::LabelStmtClass:
2967 return extract(cast<LabelStmt>(stmt));
2968 default:
2969 unsupported(stmt);
2972 return NULL;
2975 /* Try and construct a pet_scop corresponding to (part of)
2976 * a sequence of statements.
2978 struct pet_scop *PetScan::extract(StmtRange stmt_range)
2980 pet_scop *scop;
2981 StmtIterator i;
2982 int j;
2983 bool partial_range = false;
2985 scop = pet_scop_empty(ctx);
2986 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
2987 Stmt *child = *i;
2988 struct pet_scop *scop_i;
2989 scop_i = extract(child);
2990 if (scop && partial) {
2991 pet_scop_free(scop_i);
2992 break;
2994 scop_i = pet_scop_prefix(scop_i, j);
2995 if (autodetect) {
2996 if (scop_i)
2997 scop = pet_scop_add(ctx, scop, scop_i);
2998 else
2999 partial_range = true;
3000 if (scop->n_stmt != 0 && !scop_i)
3001 partial = true;
3002 } else {
3003 scop = pet_scop_add(ctx, scop, scop_i);
3005 if (partial)
3006 break;
3009 if (scop && partial_range)
3010 partial = true;
3012 return scop;
3015 /* Check if the scop marked by the user is exactly this Stmt
3016 * or part of this Stmt.
3017 * If so, return a pet_scop corresponding to the marked region.
3018 * Otherwise, return NULL.
3020 struct pet_scop *PetScan::scan(Stmt *stmt)
3022 SourceManager &SM = PP.getSourceManager();
3023 unsigned start_off, end_off;
3025 start_off = SM.getFileOffset(stmt->getLocStart());
3026 end_off = SM.getFileOffset(stmt->getLocEnd());
3028 if (start_off > loc.end)
3029 return NULL;
3030 if (end_off < loc.start)
3031 return NULL;
3032 if (start_off >= loc.start && end_off <= loc.end) {
3033 return extract(stmt);
3036 StmtIterator start;
3037 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
3038 Stmt *child = *start;
3039 if (!child)
3040 continue;
3041 start_off = SM.getFileOffset(child->getLocStart());
3042 end_off = SM.getFileOffset(child->getLocEnd());
3043 if (start_off < loc.start && end_off > loc.end)
3044 return scan(child);
3045 if (start_off >= loc.start)
3046 break;
3049 StmtIterator end;
3050 for (end = start; end != stmt->child_end(); ++end) {
3051 Stmt *child = *end;
3052 start_off = SM.getFileOffset(child->getLocStart());
3053 if (start_off >= loc.end)
3054 break;
3057 return extract(StmtRange(start, end));
3060 /* Set the size of index "pos" of "array" to "size".
3061 * In particular, add a constraint of the form
3063 * i_pos < size
3065 * to array->extent and a constraint of the form
3067 * size >= 0
3069 * to array->context.
3071 static struct pet_array *update_size(struct pet_array *array, int pos,
3072 __isl_take isl_pw_aff *size)
3074 isl_set *valid;
3075 isl_set *univ;
3076 isl_set *bound;
3077 isl_space *dim;
3078 isl_aff *aff;
3079 isl_pw_aff *index;
3080 isl_id *id;
3082 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
3083 array->context = isl_set_intersect(array->context, valid);
3085 dim = isl_set_get_space(array->extent);
3086 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
3087 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
3088 univ = isl_set_universe(isl_aff_get_domain_space(aff));
3089 index = isl_pw_aff_alloc(univ, aff);
3091 size = isl_pw_aff_add_dims(size, isl_dim_in,
3092 isl_set_dim(array->extent, isl_dim_set));
3093 id = isl_set_get_tuple_id(array->extent);
3094 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
3095 bound = isl_pw_aff_lt_set(index, size);
3097 array->extent = isl_set_intersect(array->extent, bound);
3099 if (!array->context || !array->extent)
3100 goto error;
3102 return array;
3103 error:
3104 pet_array_free(array);
3105 return NULL;
3108 /* Figure out the size of the array at position "pos" and all
3109 * subsequent positions from "type" and update "array" accordingly.
3111 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
3112 const Type *type, int pos)
3114 const ArrayType *atype;
3115 isl_pw_aff *size;
3117 if (!array)
3118 return NULL;
3120 if (type->isPointerType()) {
3121 type = type->getPointeeType().getTypePtr();
3122 return set_upper_bounds(array, type, pos + 1);
3124 if (!type->isArrayType())
3125 return array;
3127 type = type->getCanonicalTypeInternal().getTypePtr();
3128 atype = cast<ArrayType>(type);
3130 if (type->isConstantArrayType()) {
3131 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
3132 size = extract_affine(ca->getSize());
3133 array = update_size(array, pos, size);
3134 } else if (type->isVariableArrayType()) {
3135 const VariableArrayType *vla = cast<VariableArrayType>(atype);
3136 size = extract_affine(vla->getSizeExpr());
3137 array = update_size(array, pos, size);
3140 type = atype->getElementType().getTypePtr();
3142 return set_upper_bounds(array, type, pos + 1);
3145 /* Construct and return a pet_array corresponding to the variable "decl".
3146 * In particular, initialize array->extent to
3148 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
3150 * and then call set_upper_bounds to set the upper bounds on the indices
3151 * based on the type of the variable.
3153 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
3155 struct pet_array *array;
3156 QualType qt = decl->getType();
3157 const Type *type = qt.getTypePtr();
3158 int depth = array_depth(type);
3159 QualType base = base_type(qt);
3160 string name;
3161 isl_id *id;
3162 isl_space *dim;
3164 array = isl_calloc_type(ctx, struct pet_array);
3165 if (!array)
3166 return NULL;
3168 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
3169 dim = isl_space_set_alloc(ctx, 0, depth);
3170 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
3172 array->extent = isl_set_nat_universe(dim);
3174 dim = isl_space_params_alloc(ctx, 0);
3175 array->context = isl_set_universe(dim);
3177 array = set_upper_bounds(array, type, 0);
3178 if (!array)
3179 return NULL;
3181 name = base.getAsString();
3182 array->element_type = strdup(name.c_str());
3184 return array;
3187 /* Construct a list of pet_arrays, one for each array (or scalar)
3188 * accessed inside "scop" add this list to "scop" and return the result.
3190 * The context of "scop" is updated with the intesection of
3191 * the contexts of all arrays, i.e., constraints on the parameters
3192 * that ensure that the arrays have a valid (non-negative) size.
3194 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
3196 int i;
3197 set<ValueDecl *> arrays;
3198 set<ValueDecl *>::iterator it;
3199 int n_array;
3200 struct pet_array **scop_arrays;
3202 if (!scop)
3203 return NULL;
3205 pet_scop_collect_arrays(scop, arrays);
3206 if (arrays.size() == 0)
3207 return scop;
3209 n_array = scop->n_array;
3211 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
3212 n_array + arrays.size());
3213 if (!scop_arrays)
3214 goto error;
3215 scop->arrays = scop_arrays;
3217 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
3218 struct pet_array *array;
3219 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
3220 if (!scop->arrays[n_array + i])
3221 goto error;
3222 scop->n_array++;
3223 scop->context = isl_set_intersect(scop->context,
3224 isl_set_copy(array->context));
3225 if (!scop->context)
3226 goto error;
3229 return scop;
3230 error:
3231 pet_scop_free(scop);
3232 return NULL;
3235 /* Construct a pet_scop from the given function.
3237 struct pet_scop *PetScan::scan(FunctionDecl *fd)
3239 pet_scop *scop;
3240 Stmt *stmt;
3242 stmt = fd->getBody();
3244 if (autodetect)
3245 scop = extract(stmt);
3246 else
3247 scop = scan(stmt);
3248 scop = pet_scop_detect_parameter_accesses(scop);
3249 scop = scan_arrays(scop);
3251 return scop;