update isl to version 0.12.1
[pet.git] / scan.cc
blob88ff1824a115aeb2ec7434f7ebf70c1f08fce15d
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012 Ecole Normale Superieure. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
32 * Leiden University.
33 */
35 #include <string.h>
36 #include <set>
37 #include <map>
38 #include <iostream>
39 #include <llvm/Support/raw_ostream.h>
40 #include <clang/AST/ASTContext.h>
41 #include <clang/AST/ASTDiagnostic.h>
42 #include <clang/AST/Expr.h>
43 #include <clang/AST/RecursiveASTVisitor.h>
45 #include <isl/id.h>
46 #include <isl/space.h>
47 #include <isl/aff.h>
48 #include <isl/set.h>
50 #include "options.h"
51 #include "scan.h"
52 #include "scop.h"
53 #include "scop_plus.h"
55 #include "config.h"
57 using namespace std;
58 using namespace clang;
60 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
61 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
63 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
64 SourceLocation(), var, false, var->getInnerLocStart(),
65 var->getType(), VK_LValue);
67 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
68 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
70 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
71 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
72 VK_LValue);
74 #else
75 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
77 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
78 var, var->getInnerLocStart(), var->getType(), VK_LValue);
80 #endif
82 /* Check if the element type corresponding to the given array type
83 * has a const qualifier.
85 static bool const_base(QualType qt)
87 const Type *type = qt.getTypePtr();
89 if (type->isPointerType())
90 return const_base(type->getPointeeType());
91 if (type->isArrayType()) {
92 const ArrayType *atype;
93 type = type->getCanonicalTypeInternal().getTypePtr();
94 atype = cast<ArrayType>(type);
95 return const_base(atype->getElementType());
98 return qt.isConstQualified();
101 /* Mark "decl" as having an unknown value in "assigned_value".
103 * If no (known or unknown) value was assigned to "decl" before,
104 * then it may have been treated as a parameter before and may
105 * therefore appear in a value assigned to another variable.
106 * If so, this assignment needs to be turned into an unknown value too.
108 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
109 ValueDecl *decl)
111 map<ValueDecl *, isl_pw_aff *>::iterator it;
113 it = assigned_value.find(decl);
115 assigned_value[decl] = NULL;
117 if (it == assigned_value.end())
118 return;
120 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
121 isl_pw_aff *pa = it->second;
122 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
124 for (int i = 0; i < nparam; ++i) {
125 isl_id *id;
127 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
128 continue;
129 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
130 if (isl_id_get_user(id) == decl)
131 it->second = NULL;
132 isl_id_free(id);
137 /* Look for any assignments to scalar variables in part of the parse
138 * tree and set assigned_value to NULL for each of them.
139 * Also reset assigned_value if the address of a scalar variable
140 * is being taken. As an exception, if the address is passed to a function
141 * that is declared to receive a const pointer, then assigned_value is
142 * not reset.
144 * This ensures that we won't use any previously stored value
145 * in the current subtree and its parents.
147 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
148 map<ValueDecl *, isl_pw_aff *> &assigned_value;
149 set<UnaryOperator *> skip;
151 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
152 assigned_value(assigned_value) {}
154 /* Check for "address of" operators whose value is passed
155 * to a const pointer argument and add them to "skip", so that
156 * we can skip them in VisitUnaryOperator.
158 bool VisitCallExpr(CallExpr *expr) {
159 FunctionDecl *fd;
160 fd = expr->getDirectCallee();
161 if (!fd)
162 return true;
163 for (int i = 0; i < expr->getNumArgs(); ++i) {
164 Expr *arg = expr->getArg(i);
165 UnaryOperator *op;
166 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
167 ImplicitCastExpr *ice;
168 ice = cast<ImplicitCastExpr>(arg);
169 arg = ice->getSubExpr();
171 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
172 continue;
173 op = cast<UnaryOperator>(arg);
174 if (op->getOpcode() != UO_AddrOf)
175 continue;
176 if (const_base(fd->getParamDecl(i)->getType()))
177 skip.insert(op);
179 return true;
182 bool VisitUnaryOperator(UnaryOperator *expr) {
183 Expr *arg;
184 DeclRefExpr *ref;
185 ValueDecl *decl;
187 switch (expr->getOpcode()) {
188 case UO_AddrOf:
189 case UO_PostInc:
190 case UO_PostDec:
191 case UO_PreInc:
192 case UO_PreDec:
193 break;
194 default:
195 return true;
197 if (skip.find(expr) != skip.end())
198 return true;
200 arg = expr->getSubExpr();
201 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
202 return true;
203 ref = cast<DeclRefExpr>(arg);
204 decl = ref->getDecl();
205 clear_assignment(assigned_value, decl);
206 return true;
209 bool VisitBinaryOperator(BinaryOperator *expr) {
210 Expr *lhs;
211 DeclRefExpr *ref;
212 ValueDecl *decl;
214 if (!expr->isAssignmentOp())
215 return true;
216 lhs = expr->getLHS();
217 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
218 return true;
219 ref = cast<DeclRefExpr>(lhs);
220 decl = ref->getDecl();
221 clear_assignment(assigned_value, decl);
222 return true;
226 /* Keep a copy of the currently assigned values.
228 * Any variable that is assigned a value inside the current scope
229 * is removed again when we leave the scope (either because it wasn't
230 * stored in the cache or because it has a different value in the cache).
232 struct assigned_value_cache {
233 map<ValueDecl *, isl_pw_aff *> &assigned_value;
234 map<ValueDecl *, isl_pw_aff *> cache;
236 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
237 assigned_value(assigned_value), cache(assigned_value) {}
238 ~assigned_value_cache() {
239 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
240 for (it = assigned_value.begin(); it != assigned_value.end();
241 ++it) {
242 if (!it->second ||
243 (cache.find(it->first) != cache.end() &&
244 cache[it->first] != it->second))
245 cache[it->first] = NULL;
247 assigned_value = cache;
251 /* Insert an expression into the collection of expressions,
252 * provided it is not already in there.
253 * The isl_pw_affs are freed in the destructor.
255 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
257 std::set<isl_pw_aff *>::iterator it;
259 if (expressions.find(expr) == expressions.end())
260 expressions.insert(expr);
261 else
262 isl_pw_aff_free(expr);
265 PetScan::~PetScan()
267 std::set<isl_pw_aff *>::iterator it;
269 for (it = expressions.begin(); it != expressions.end(); ++it)
270 isl_pw_aff_free(*it);
272 isl_union_map_free(value_bounds);
275 /* Called if we found something we (currently) cannot handle.
276 * We'll provide more informative warnings later.
278 * We only actually complain if autodetect is false.
280 void PetScan::unsupported(Stmt *stmt, const char *msg)
282 if (options->autodetect)
283 return;
285 SourceLocation loc = stmt->getLocStart();
286 DiagnosticsEngine &diag = PP.getDiagnostics();
287 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
288 msg ? msg : "unsupported");
289 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
292 /* Extract an integer from "expr".
294 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
296 const Type *type = expr->getType().getTypePtr();
297 int is_signed = type->hasSignedIntegerRepresentation();
298 llvm::APInt val = expr->getValue();
299 int is_negative = is_signed && val.isNegative();
300 isl_val *v;
302 if (is_negative)
303 val = -val;
305 v = extract_unsigned(ctx, val);
307 if (is_negative)
308 v = isl_val_neg(v);
309 return v;
312 /* Extract an integer from "val", which assumed to be non-negative.
314 __isl_give isl_val *PetScan::extract_unsigned(isl_ctx *ctx,
315 const llvm::APInt &val)
317 unsigned n;
318 const uint64_t *data;
320 data = val.getRawData();
321 n = val.getNumWords();
322 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
325 /* Extract an integer from "expr".
326 * Return NULL if "expr" does not (obviously) represent an integer.
328 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
330 return extract_int(expr->getSubExpr());
333 /* Extract an integer from "expr".
334 * Return NULL if "expr" does not (obviously) represent an integer.
336 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
338 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
339 return extract_int(ctx, cast<IntegerLiteral>(expr));
340 if (expr->getStmtClass() == Stmt::ParenExprClass)
341 return extract_int(cast<ParenExpr>(expr));
343 unsupported(expr);
344 return NULL;
347 /* Extract an affine expression from the IntegerLiteral "expr".
349 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
351 isl_space *dim = isl_space_params_alloc(ctx, 0);
352 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
353 isl_aff *aff = isl_aff_zero_on_domain(ls);
354 isl_set *dom = isl_set_universe(dim);
355 isl_val *v;
357 v = extract_int(expr);
358 aff = isl_aff_add_constant_val(aff, v);
360 return isl_pw_aff_alloc(dom, aff);
363 /* Extract an affine expression from the APInt "val", which is assumed
364 * to be non-negative.
366 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
368 isl_space *dim = isl_space_params_alloc(ctx, 0);
369 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
370 isl_aff *aff = isl_aff_zero_on_domain(ls);
371 isl_set *dom = isl_set_universe(dim);
372 isl_val *v;
374 v = extract_unsigned(ctx, val);
375 aff = isl_aff_add_constant_val(aff, v);
377 return isl_pw_aff_alloc(dom, aff);
380 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
382 return extract_affine(expr->getSubExpr());
385 static unsigned get_type_size(ValueDecl *decl)
387 return decl->getASTContext().getIntWidth(decl->getType());
390 /* Bound parameter "pos" of "set" to the possible values of "decl".
392 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
393 unsigned pos, ValueDecl *decl)
395 unsigned width;
396 isl_ctx *ctx;
397 isl_val *bound;
399 ctx = isl_set_get_ctx(set);
400 width = get_type_size(decl);
401 if (decl->getType()->isUnsignedIntegerType()) {
402 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
403 bound = isl_val_int_from_ui(ctx, width);
404 bound = isl_val_2exp(bound);
405 bound = isl_val_sub_ui(bound, 1);
406 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
407 } else {
408 bound = isl_val_int_from_ui(ctx, width - 1);
409 bound = isl_val_2exp(bound);
410 bound = isl_val_sub_ui(bound, 1);
411 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
412 isl_val_copy(bound));
413 bound = isl_val_neg(bound);
414 bound = isl_val_sub_ui(bound, 1);
415 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
418 return set;
421 /* Extract an affine expression from the DeclRefExpr "expr".
423 * If the variable has been assigned a value, then we check whether
424 * we know what (affine) value was assigned.
425 * If so, we return this value. Otherwise we convert "expr"
426 * to an extra parameter (provided nesting_enabled is set).
428 * Otherwise, we simply return an expression that is equal
429 * to a parameter corresponding to the referenced variable.
431 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
433 ValueDecl *decl = expr->getDecl();
434 const Type *type = decl->getType().getTypePtr();
435 isl_id *id;
436 isl_space *dim;
437 isl_aff *aff;
438 isl_set *dom;
440 if (!type->isIntegerType()) {
441 unsupported(expr);
442 return NULL;
445 if (assigned_value.find(decl) != assigned_value.end()) {
446 if (assigned_value[decl])
447 return isl_pw_aff_copy(assigned_value[decl]);
448 else
449 return nested_access(expr);
452 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
453 dim = isl_space_params_alloc(ctx, 1);
455 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
457 dom = isl_set_universe(isl_space_copy(dim));
458 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
459 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
461 return isl_pw_aff_alloc(dom, aff);
464 /* Extract an affine expression from an integer division operation.
465 * In particular, if "expr" is lhs/rhs, then return
467 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
469 * The second argument (rhs) is required to be a (positive) integer constant.
471 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
473 int is_cst;
474 isl_pw_aff *rhs, *lhs;
476 rhs = extract_affine(expr->getRHS());
477 is_cst = isl_pw_aff_is_cst(rhs);
478 if (is_cst < 0 || !is_cst) {
479 isl_pw_aff_free(rhs);
480 if (!is_cst)
481 unsupported(expr);
482 return NULL;
485 lhs = extract_affine(expr->getLHS());
487 return isl_pw_aff_tdiv_q(lhs, rhs);
490 /* Extract an affine expression from a modulo operation.
491 * In particular, if "expr" is lhs/rhs, then return
493 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
495 * The second argument (rhs) is required to be a (positive) integer constant.
497 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
499 int is_cst;
500 isl_pw_aff *rhs, *lhs;
502 rhs = extract_affine(expr->getRHS());
503 is_cst = isl_pw_aff_is_cst(rhs);
504 if (is_cst < 0 || !is_cst) {
505 isl_pw_aff_free(rhs);
506 if (!is_cst)
507 unsupported(expr);
508 return NULL;
511 lhs = extract_affine(expr->getLHS());
513 return isl_pw_aff_tdiv_r(lhs, rhs);
516 /* Extract an affine expression from a multiplication operation.
517 * This is only allowed if at least one of the two arguments
518 * is a (piecewise) constant.
520 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
522 isl_pw_aff *lhs;
523 isl_pw_aff *rhs;
525 lhs = extract_affine(expr->getLHS());
526 rhs = extract_affine(expr->getRHS());
528 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
529 isl_pw_aff_free(lhs);
530 isl_pw_aff_free(rhs);
531 unsupported(expr);
532 return NULL;
535 return isl_pw_aff_mul(lhs, rhs);
538 /* Extract an affine expression from an addition or subtraction operation.
540 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
542 isl_pw_aff *lhs;
543 isl_pw_aff *rhs;
545 lhs = extract_affine(expr->getLHS());
546 rhs = extract_affine(expr->getRHS());
548 switch (expr->getOpcode()) {
549 case BO_Add:
550 return isl_pw_aff_add(lhs, rhs);
551 case BO_Sub:
552 return isl_pw_aff_sub(lhs, rhs);
553 default:
554 isl_pw_aff_free(lhs);
555 isl_pw_aff_free(rhs);
556 return NULL;
561 /* Compute
563 * pwaff mod 2^width
565 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
566 unsigned width)
568 isl_ctx *ctx;
569 isl_val *mod;
571 ctx = isl_pw_aff_get_ctx(pwaff);
572 mod = isl_val_int_from_ui(ctx, width);
573 mod = isl_val_2exp(mod);
575 pwaff = isl_pw_aff_mod_val(pwaff, mod);
577 return pwaff;
580 /* Limit the domain of "pwaff" to those elements where the function
581 * value satisfies
583 * 2^{width-1} <= pwaff < 2^{width-1}
585 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
586 unsigned width)
588 isl_ctx *ctx;
589 isl_val *v;
590 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
591 isl_local_space *ls = isl_local_space_from_space(space);
592 isl_aff *bound;
593 isl_set *dom;
594 isl_pw_aff *b;
596 ctx = isl_pw_aff_get_ctx(pwaff);
597 v = isl_val_int_from_ui(ctx, width - 1);
598 v = isl_val_2exp(v);
600 bound = isl_aff_zero_on_domain(ls);
601 bound = isl_aff_add_constant_val(bound, v);
602 b = isl_pw_aff_from_aff(bound);
604 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
605 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
607 b = isl_pw_aff_neg(b);
608 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
609 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
611 return pwaff;
614 /* Handle potential overflows on signed computations.
616 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
617 * the we adjust the domain of "pa" to avoid overflows.
619 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
620 unsigned width)
622 if (options->signed_overflow == PET_OVERFLOW_AVOID)
623 pa = avoid_overflow(pa, width);
625 return pa;
628 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
630 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
631 __isl_take isl_set *dom)
633 isl_pw_aff *pa;
634 pa = isl_set_indicator_function(set);
635 pa = isl_pw_aff_intersect_domain(pa, dom);
636 return pa;
639 /* Extract an affine expression from some binary operations.
640 * If the result of the expression is unsigned, then we wrap it
641 * based on the size of the type. Otherwise, we ensure that
642 * no overflow occurs.
644 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
646 isl_pw_aff *res;
647 unsigned width;
649 switch (expr->getOpcode()) {
650 case BO_Add:
651 case BO_Sub:
652 res = extract_affine_add(expr);
653 break;
654 case BO_Div:
655 res = extract_affine_div(expr);
656 break;
657 case BO_Rem:
658 res = extract_affine_mod(expr);
659 break;
660 case BO_Mul:
661 res = extract_affine_mul(expr);
662 break;
663 case BO_LT:
664 case BO_LE:
665 case BO_GT:
666 case BO_GE:
667 case BO_EQ:
668 case BO_NE:
669 case BO_LAnd:
670 case BO_LOr:
671 return extract_condition(expr);
672 default:
673 unsupported(expr);
674 return NULL;
677 width = ast_context.getIntWidth(expr->getType());
678 if (expr->getType()->isUnsignedIntegerType())
679 res = wrap(res, width);
680 else
681 res = signed_overflow(res, width);
683 return res;
686 /* Extract an affine expression from a negation operation.
688 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
690 if (expr->getOpcode() == UO_Minus)
691 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
692 if (expr->getOpcode() == UO_LNot)
693 return extract_condition(expr);
695 unsupported(expr);
696 return NULL;
699 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
701 return extract_affine(expr->getSubExpr());
704 /* Extract an affine expression from some special function calls.
705 * In particular, we handle "min", "max", "ceild" and "floord".
706 * In case of the latter two, the second argument needs to be
707 * a (positive) integer constant.
709 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
711 FunctionDecl *fd;
712 string name;
713 isl_pw_aff *aff1, *aff2;
715 fd = expr->getDirectCallee();
716 if (!fd) {
717 unsupported(expr);
718 return NULL;
721 name = fd->getDeclName().getAsString();
722 if (!(expr->getNumArgs() == 2 && name == "min") &&
723 !(expr->getNumArgs() == 2 && name == "max") &&
724 !(expr->getNumArgs() == 2 && name == "floord") &&
725 !(expr->getNumArgs() == 2 && name == "ceild")) {
726 unsupported(expr);
727 return NULL;
730 if (name == "min" || name == "max") {
731 aff1 = extract_affine(expr->getArg(0));
732 aff2 = extract_affine(expr->getArg(1));
734 if (name == "min")
735 aff1 = isl_pw_aff_min(aff1, aff2);
736 else
737 aff1 = isl_pw_aff_max(aff1, aff2);
738 } else if (name == "floord" || name == "ceild") {
739 isl_val *v;
740 Expr *arg2 = expr->getArg(1);
742 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
743 unsupported(expr);
744 return NULL;
746 aff1 = extract_affine(expr->getArg(0));
747 v = extract_int(cast<IntegerLiteral>(arg2));
748 aff1 = isl_pw_aff_scale_down_val(aff1, v);
749 if (name == "floord")
750 aff1 = isl_pw_aff_floor(aff1);
751 else
752 aff1 = isl_pw_aff_ceil(aff1);
753 } else {
754 unsupported(expr);
755 return NULL;
758 return aff1;
761 /* This method is called when we come across an access that is
762 * nested in what is supposed to be an affine expression.
763 * If nesting is allowed, we return a new parameter that corresponds
764 * to this nested access. Otherwise, we simply complain.
766 * Note that we currently don't allow nested accesses themselves
767 * to contain any nested accesses, so we check if we can extract
768 * the access without any nesting and complain if we can't.
770 * The new parameter is resolved in resolve_nested.
772 isl_pw_aff *PetScan::nested_access(Expr *expr)
774 isl_id *id;
775 isl_space *dim;
776 isl_aff *aff;
777 isl_set *dom;
778 isl_map *access;
780 if (!nesting_enabled) {
781 unsupported(expr);
782 return NULL;
785 allow_nested = false;
786 access = extract_access(expr);
787 allow_nested = true;
788 if (!access) {
789 unsupported(expr);
790 return NULL;
792 isl_map_free(access);
794 id = isl_id_alloc(ctx, NULL, expr);
795 dim = isl_space_params_alloc(ctx, 1);
797 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
799 dom = isl_set_universe(isl_space_copy(dim));
800 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
801 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
803 return isl_pw_aff_alloc(dom, aff);
806 /* Affine expressions are not supposed to contain array accesses,
807 * but if nesting is allowed, we return a parameter corresponding
808 * to the array access.
810 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
812 return nested_access(expr);
815 /* Extract an affine expression from a conditional operation.
817 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
819 isl_pw_aff *cond, *lhs, *rhs, *res;
821 cond = extract_condition(expr->getCond());
822 lhs = extract_affine(expr->getTrueExpr());
823 rhs = extract_affine(expr->getFalseExpr());
825 return isl_pw_aff_cond(cond, lhs, rhs);
828 /* Extract an affine expression, if possible, from "expr".
829 * Otherwise return NULL.
831 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
833 switch (expr->getStmtClass()) {
834 case Stmt::ImplicitCastExprClass:
835 return extract_affine(cast<ImplicitCastExpr>(expr));
836 case Stmt::IntegerLiteralClass:
837 return extract_affine(cast<IntegerLiteral>(expr));
838 case Stmt::DeclRefExprClass:
839 return extract_affine(cast<DeclRefExpr>(expr));
840 case Stmt::BinaryOperatorClass:
841 return extract_affine(cast<BinaryOperator>(expr));
842 case Stmt::UnaryOperatorClass:
843 return extract_affine(cast<UnaryOperator>(expr));
844 case Stmt::ParenExprClass:
845 return extract_affine(cast<ParenExpr>(expr));
846 case Stmt::CallExprClass:
847 return extract_affine(cast<CallExpr>(expr));
848 case Stmt::ArraySubscriptExprClass:
849 return extract_affine(cast<ArraySubscriptExpr>(expr));
850 case Stmt::ConditionalOperatorClass:
851 return extract_affine(cast<ConditionalOperator>(expr));
852 default:
853 unsupported(expr);
855 return NULL;
858 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
860 return extract_access(expr->getSubExpr());
863 /* Return the depth of an array of the given type.
865 static int array_depth(const Type *type)
867 if (type->isPointerType())
868 return 1 + array_depth(type->getPointeeType().getTypePtr());
869 if (type->isArrayType()) {
870 const ArrayType *atype;
871 type = type->getCanonicalTypeInternal().getTypePtr();
872 atype = cast<ArrayType>(type);
873 return 1 + array_depth(atype->getElementType().getTypePtr());
875 return 0;
878 /* Return the element type of the given array type.
880 static QualType base_type(QualType qt)
882 const Type *type = qt.getTypePtr();
884 if (type->isPointerType())
885 return base_type(type->getPointeeType());
886 if (type->isArrayType()) {
887 const ArrayType *atype;
888 type = type->getCanonicalTypeInternal().getTypePtr();
889 atype = cast<ArrayType>(type);
890 return base_type(atype->getElementType());
892 return qt;
895 /* Extract an access relation from a reference to a variable.
896 * If the variable has name "A" and its type corresponds to an
897 * array of depth d, then the returned access relation is of the
898 * form
900 * { [] -> A[i_1,...,i_d] }
902 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
904 return extract_access(expr->getDecl());
907 /* Extract an access relation from a variable.
908 * If the variable has name "A" and its type corresponds to an
909 * array of depth d, then the returned access relation is of the
910 * form
912 * { [] -> A[i_1,...,i_d] }
914 __isl_give isl_map *PetScan::extract_access(ValueDecl *decl)
916 int depth = array_depth(decl->getType().getTypePtr());
917 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
918 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
919 isl_map *access_rel;
921 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
923 access_rel = isl_map_universe(dim);
925 return access_rel;
928 /* Extract an access relation from an integer contant.
929 * If the value of the constant is "v", then the returned access relation
930 * is
932 * { [] -> [v] }
934 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
936 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
939 /* Try and extract an access relation from the given Expr.
940 * Return NULL if it doesn't work out.
942 __isl_give isl_map *PetScan::extract_access(Expr *expr)
944 switch (expr->getStmtClass()) {
945 case Stmt::ImplicitCastExprClass:
946 return extract_access(cast<ImplicitCastExpr>(expr));
947 case Stmt::DeclRefExprClass:
948 return extract_access(cast<DeclRefExpr>(expr));
949 case Stmt::ArraySubscriptExprClass:
950 return extract_access(cast<ArraySubscriptExpr>(expr));
951 case Stmt::IntegerLiteralClass:
952 return extract_access(cast<IntegerLiteral>(expr));
953 default:
954 unsupported(expr);
956 return NULL;
959 /* Assign the affine expression "index" to the output dimension "pos" of "map",
960 * restrict the domain to those values that result in a non-negative index
961 * and return the result.
963 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
964 __isl_take isl_pw_aff *index)
966 isl_map *index_map;
967 int len = isl_map_dim(map, isl_dim_out);
968 isl_id *id;
969 isl_set *domain;
971 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
972 index = isl_pw_aff_intersect_domain(index, domain);
973 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
974 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
975 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
976 id = isl_map_get_tuple_id(map, isl_dim_out);
977 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
979 map = isl_map_intersect(map, index_map);
981 return map;
984 /* Extract an access relation from the given array subscript expression.
985 * If nesting is allowed in general, then we turn it on while
986 * examining the index expression.
988 * We first extract an access relation from the base.
989 * This will result in an access relation with a range that corresponds
990 * to the array being accessed and with earlier indices filled in already.
991 * We then extract the current index and fill that in as well.
992 * The position of the current index is based on the type of base.
993 * If base is the actual array variable, then the depth of this type
994 * will be the same as the depth of the array and we will fill in
995 * the first array index.
996 * Otherwise, the depth of the base type will be smaller and we will fill
997 * in a later index.
999 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
1001 Expr *base = expr->getBase();
1002 Expr *idx = expr->getIdx();
1003 isl_pw_aff *index;
1004 isl_map *base_access;
1005 isl_map *access;
1006 int depth = array_depth(base->getType().getTypePtr());
1007 int pos;
1008 bool save_nesting = nesting_enabled;
1010 nesting_enabled = allow_nested;
1012 base_access = extract_access(base);
1013 index = extract_affine(idx);
1015 nesting_enabled = save_nesting;
1017 pos = isl_map_dim(base_access, isl_dim_out) - depth;
1018 access = set_index(base_access, pos, index);
1020 return access;
1023 /* Check if "expr" calls function "minmax" with two arguments and if so
1024 * make lhs and rhs refer to these two arguments.
1026 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1028 CallExpr *call;
1029 FunctionDecl *fd;
1030 string name;
1032 if (expr->getStmtClass() != Stmt::CallExprClass)
1033 return false;
1035 call = cast<CallExpr>(expr);
1036 fd = call->getDirectCallee();
1037 if (!fd)
1038 return false;
1040 if (call->getNumArgs() != 2)
1041 return false;
1043 name = fd->getDeclName().getAsString();
1044 if (name != minmax)
1045 return false;
1047 lhs = call->getArg(0);
1048 rhs = call->getArg(1);
1050 return true;
1053 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1054 * lhs and rhs refer to the two arguments.
1056 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1058 return is_minmax(expr, "min", lhs, rhs);
1061 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1062 * lhs and rhs refer to the two arguments.
1064 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1066 return is_minmax(expr, "max", lhs, rhs);
1069 /* Return "lhs && rhs", defined on the shared definition domain.
1071 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1072 __isl_take isl_pw_aff *rhs)
1074 isl_set *cond;
1075 isl_set *dom;
1077 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1078 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1079 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1080 isl_pw_aff_non_zero_set(rhs));
1081 return indicator_function(cond, dom);
1084 /* Return "lhs && rhs", with shortcut semantics.
1085 * That is, if lhs is false, then the result is defined even if rhs is not.
1086 * In practice, we compute lhs ? rhs : lhs.
1088 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1089 __isl_take isl_pw_aff *rhs)
1091 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1094 /* Return "lhs || rhs", with shortcut semantics.
1095 * That is, if lhs is true, then the result is defined even if rhs is not.
1096 * In practice, we compute lhs ? lhs : rhs.
1098 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1099 __isl_take isl_pw_aff *rhs)
1101 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1104 /* Extract an affine expressions representing the comparison "LHS op RHS"
1105 * "comp" is the original statement that "LHS op RHS" is derived from
1106 * and is used for diagnostics.
1108 * If the comparison is of the form
1110 * a <= min(b,c)
1112 * then the expression is constructed as the conjunction of
1113 * the comparisons
1115 * a <= b and a <= c
1117 * A similar optimization is performed for max(a,b) <= c.
1118 * We do this because that will lead to simpler representations
1119 * of the expression.
1120 * If isl is ever enhanced to explicitly deal with min and max expressions,
1121 * this optimization can be removed.
1123 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1124 Expr *LHS, Expr *RHS, Stmt *comp)
1126 isl_pw_aff *lhs;
1127 isl_pw_aff *rhs;
1128 isl_pw_aff *res;
1129 isl_set *cond;
1130 isl_set *dom;
1132 if (op == BO_GT)
1133 return extract_comparison(BO_LT, RHS, LHS, comp);
1134 if (op == BO_GE)
1135 return extract_comparison(BO_LE, RHS, LHS, comp);
1137 if (op == BO_LT || op == BO_LE) {
1138 Expr *expr1, *expr2;
1139 if (is_min(RHS, expr1, expr2)) {
1140 lhs = extract_comparison(op, LHS, expr1, comp);
1141 rhs = extract_comparison(op, LHS, expr2, comp);
1142 return pw_aff_and(lhs, rhs);
1144 if (is_max(LHS, expr1, expr2)) {
1145 lhs = extract_comparison(op, expr1, RHS, comp);
1146 rhs = extract_comparison(op, expr2, RHS, comp);
1147 return pw_aff_and(lhs, rhs);
1151 lhs = extract_affine(LHS);
1152 rhs = extract_affine(RHS);
1154 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1155 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1157 switch (op) {
1158 case BO_LT:
1159 cond = isl_pw_aff_lt_set(lhs, rhs);
1160 break;
1161 case BO_LE:
1162 cond = isl_pw_aff_le_set(lhs, rhs);
1163 break;
1164 case BO_EQ:
1165 cond = isl_pw_aff_eq_set(lhs, rhs);
1166 break;
1167 case BO_NE:
1168 cond = isl_pw_aff_ne_set(lhs, rhs);
1169 break;
1170 default:
1171 isl_pw_aff_free(lhs);
1172 isl_pw_aff_free(rhs);
1173 isl_set_free(dom);
1174 unsupported(comp);
1175 return NULL;
1178 cond = isl_set_coalesce(cond);
1179 res = indicator_function(cond, dom);
1181 return res;
1184 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1186 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1187 comp->getRHS(), comp);
1190 /* Extract an affine expression representing the negation (logical not)
1191 * of a subexpression.
1193 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1195 isl_set *set_cond, *dom;
1196 isl_pw_aff *cond, *res;
1198 cond = extract_condition(op->getSubExpr());
1200 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1202 set_cond = isl_pw_aff_zero_set(cond);
1204 res = indicator_function(set_cond, dom);
1206 return res;
1209 /* Extract an affine expression representing the disjunction (logical or)
1210 * or conjunction (logical and) of two subexpressions.
1212 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1214 isl_pw_aff *lhs, *rhs;
1216 lhs = extract_condition(comp->getLHS());
1217 rhs = extract_condition(comp->getRHS());
1219 switch (comp->getOpcode()) {
1220 case BO_LAnd:
1221 return pw_aff_and_then(lhs, rhs);
1222 case BO_LOr:
1223 return pw_aff_or_else(lhs, rhs);
1224 default:
1225 isl_pw_aff_free(lhs);
1226 isl_pw_aff_free(rhs);
1229 unsupported(comp);
1230 return NULL;
1233 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1235 switch (expr->getOpcode()) {
1236 case UO_LNot:
1237 return extract_boolean(expr);
1238 default:
1239 unsupported(expr);
1240 return NULL;
1244 /* Extract the affine expression "expr != 0 ? 1 : 0".
1246 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1248 isl_pw_aff *res;
1249 isl_set *set, *dom;
1251 res = extract_affine(expr);
1253 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1254 set = isl_pw_aff_non_zero_set(res);
1256 res = indicator_function(set, dom);
1258 return res;
1261 /* Extract an affine expression from a boolean expression.
1262 * In particular, return the expression "expr ? 1 : 0".
1264 * If the expression doesn't look like a condition, we assume it
1265 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1267 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1269 BinaryOperator *comp;
1271 if (!expr) {
1272 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1273 return indicator_function(u, isl_set_copy(u));
1276 if (expr->getStmtClass() == Stmt::ParenExprClass)
1277 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1279 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1280 return extract_condition(cast<UnaryOperator>(expr));
1282 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1283 return extract_implicit_condition(expr);
1285 comp = cast<BinaryOperator>(expr);
1286 switch (comp->getOpcode()) {
1287 case BO_LT:
1288 case BO_LE:
1289 case BO_GT:
1290 case BO_GE:
1291 case BO_EQ:
1292 case BO_NE:
1293 return extract_comparison(comp);
1294 case BO_LAnd:
1295 case BO_LOr:
1296 return extract_boolean(comp);
1297 default:
1298 return extract_implicit_condition(expr);
1302 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1304 switch (kind) {
1305 case UO_Minus:
1306 return pet_op_minus;
1307 case UO_PostInc:
1308 return pet_op_post_inc;
1309 case UO_PostDec:
1310 return pet_op_post_dec;
1311 case UO_PreInc:
1312 return pet_op_pre_inc;
1313 case UO_PreDec:
1314 return pet_op_pre_dec;
1315 default:
1316 return pet_op_last;
1320 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1322 switch (kind) {
1323 case BO_AddAssign:
1324 return pet_op_add_assign;
1325 case BO_SubAssign:
1326 return pet_op_sub_assign;
1327 case BO_MulAssign:
1328 return pet_op_mul_assign;
1329 case BO_DivAssign:
1330 return pet_op_div_assign;
1331 case BO_Assign:
1332 return pet_op_assign;
1333 case BO_Add:
1334 return pet_op_add;
1335 case BO_Sub:
1336 return pet_op_sub;
1337 case BO_Mul:
1338 return pet_op_mul;
1339 case BO_Div:
1340 return pet_op_div;
1341 case BO_Rem:
1342 return pet_op_mod;
1343 case BO_EQ:
1344 return pet_op_eq;
1345 case BO_LE:
1346 return pet_op_le;
1347 case BO_LT:
1348 return pet_op_lt;
1349 case BO_GT:
1350 return pet_op_gt;
1351 default:
1352 return pet_op_last;
1356 /* Construct a pet_expr representing a unary operator expression.
1358 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1360 struct pet_expr *arg;
1361 enum pet_op_type op;
1363 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1364 if (op == pet_op_last) {
1365 unsupported(expr);
1366 return NULL;
1369 arg = extract_expr(expr->getSubExpr());
1371 if (expr->isIncrementDecrementOp() &&
1372 arg && arg->type == pet_expr_access) {
1373 mark_write(arg);
1374 arg->acc.read = 1;
1377 return pet_expr_new_unary(ctx, op, arg);
1380 /* Mark the given access pet_expr as a write.
1381 * If a scalar is being accessed, then mark its value
1382 * as unknown in assigned_value.
1384 void PetScan::mark_write(struct pet_expr *access)
1386 isl_id *id;
1387 ValueDecl *decl;
1389 if (!access)
1390 return;
1392 access->acc.write = 1;
1393 access->acc.read = 0;
1395 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1396 return;
1398 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1399 decl = (ValueDecl *) isl_id_get_user(id);
1400 clear_assignment(assigned_value, decl);
1401 isl_id_free(id);
1404 /* Assign "rhs" to "lhs".
1406 * In particular, if "lhs" is a scalar variable, then mark
1407 * the variable as having been assigned. If, furthermore, "rhs"
1408 * is an affine expression, then keep track of this value in assigned_value
1409 * so that we can plug it in when we later come across the same variable.
1411 void PetScan::assign(struct pet_expr *lhs, Expr *rhs)
1413 isl_id *id;
1414 ValueDecl *decl;
1415 isl_pw_aff *pa;
1417 if (!lhs)
1418 return;
1419 if (lhs->type != pet_expr_access)
1420 return;
1421 if (isl_map_dim(lhs->acc.access, isl_dim_out) != 0)
1422 return;
1424 id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1425 decl = (ValueDecl *) isl_id_get_user(id);
1426 isl_id_free(id);
1428 pa = try_extract_affine(rhs);
1429 clear_assignment(assigned_value, decl);
1430 if (!pa)
1431 return;
1432 assigned_value[decl] = pa;
1433 insert_expression(pa);
1436 /* Construct a pet_expr representing a binary operator expression.
1438 * If the top level operator is an assignment and the LHS is an access,
1439 * then we mark that access as a write. If the operator is a compound
1440 * assignment, the access is marked as both a read and a write.
1442 * If "expr" assigns something to a scalar variable, then we mark
1443 * the variable as having been assigned. If, furthermore, the expression
1444 * is affine, then keep track of this value in assigned_value
1445 * so that we can plug it in when we later come across the same variable.
1447 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1449 struct pet_expr *lhs, *rhs;
1450 enum pet_op_type op;
1452 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1453 if (op == pet_op_last) {
1454 unsupported(expr);
1455 return NULL;
1458 lhs = extract_expr(expr->getLHS());
1459 rhs = extract_expr(expr->getRHS());
1461 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1462 mark_write(lhs);
1463 if (expr->isCompoundAssignmentOp())
1464 lhs->acc.read = 1;
1467 if (expr->getOpcode() == BO_Assign)
1468 assign(lhs, expr->getRHS());
1470 return pet_expr_new_binary(ctx, op, lhs, rhs);
1473 /* Construct a pet_scop with a single statement killing the entire
1474 * array "array".
1476 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1478 isl_map *access;
1479 struct pet_expr *expr;
1481 if (!array)
1482 return NULL;
1483 access = isl_map_from_range(isl_set_copy(array->extent));
1484 expr = pet_expr_kill_from_access(access);
1485 return extract(stmt, expr);
1488 /* Construct a pet_scop for a (single) variable declaration.
1490 * The scop contains the variable being declared (as an array)
1491 * and a statement killing the array.
1493 * If the variable is initialized in the AST, then the scop
1494 * also contains an assignment to the variable.
1496 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1498 Decl *decl;
1499 VarDecl *vd;
1500 struct pet_expr *lhs, *rhs, *pe;
1501 struct pet_scop *scop_decl, *scop;
1502 struct pet_array *array;
1504 if (!stmt->isSingleDecl()) {
1505 unsupported(stmt);
1506 return NULL;
1509 decl = stmt->getSingleDecl();
1510 vd = cast<VarDecl>(decl);
1512 array = extract_array(ctx, vd);
1513 if (array)
1514 array->declared = 1;
1515 scop_decl = kill(stmt, array);
1516 scop_decl = pet_scop_add_array(scop_decl, array);
1518 if (!vd->getInit())
1519 return scop_decl;
1521 lhs = pet_expr_from_access(extract_access(vd));
1522 rhs = extract_expr(vd->getInit());
1524 mark_write(lhs);
1525 assign(lhs, vd->getInit());
1527 pe = pet_expr_new_binary(ctx, pet_op_assign, lhs, rhs);
1528 scop = extract(stmt, pe);
1530 scop_decl = pet_scop_prefix(scop_decl, 0);
1531 scop = pet_scop_prefix(scop, 1);
1533 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1535 return scop;
1538 /* Construct a pet_expr representing a conditional operation.
1540 * We first try to extract the condition as an affine expression.
1541 * If that fails, we construct a pet_expr tree representing the condition.
1543 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1545 struct pet_expr *cond, *lhs, *rhs;
1546 isl_pw_aff *pa;
1548 pa = try_extract_affine(expr->getCond());
1549 if (pa) {
1550 isl_set *test = isl_set_from_pw_aff(pa);
1551 cond = pet_expr_from_access(isl_map_from_range(test));
1552 } else
1553 cond = extract_expr(expr->getCond());
1554 lhs = extract_expr(expr->getTrueExpr());
1555 rhs = extract_expr(expr->getFalseExpr());
1557 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1560 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1562 return extract_expr(expr->getSubExpr());
1565 /* Construct a pet_expr representing a floating point value.
1567 * If the floating point literal does not appear in a macro,
1568 * then we use the original representation in the source code
1569 * as the string representation. Otherwise, we use the pretty
1570 * printer to produce a string representation.
1572 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1574 double d;
1575 string s;
1576 const LangOptions &LO = PP.getLangOpts();
1577 SourceLocation loc = expr->getLocation();
1579 if (!loc.isMacroID()) {
1580 SourceManager &SM = PP.getSourceManager();
1581 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1582 s = string(SM.getCharacterData(loc), len);
1583 } else {
1584 llvm::raw_string_ostream S(s);
1585 expr->printPretty(S, 0, PrintingPolicy(LO));
1586 S.str();
1588 d = expr->getValueAsApproximateDouble();
1589 return pet_expr_new_double(ctx, d, s.c_str());
1592 /* Extract an access relation from "expr" and then convert it into
1593 * a pet_expr.
1595 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1597 isl_map *access;
1598 struct pet_expr *pe;
1600 access = extract_access(expr);
1602 pe = pet_expr_from_access(access);
1604 return pe;
1607 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1609 return extract_expr(expr->getSubExpr());
1612 /* Construct a pet_expr representing a function call.
1614 * If we are passing along a pointer to an array element
1615 * or an entire row or even higher dimensional slice of an array,
1616 * then the function being called may write into the array.
1618 * We assume here that if the function is declared to take a pointer
1619 * to a const type, then the function will perform a read
1620 * and that otherwise, it will perform a write.
1622 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1624 struct pet_expr *res = NULL;
1625 FunctionDecl *fd;
1626 string name;
1628 fd = expr->getDirectCallee();
1629 if (!fd) {
1630 unsupported(expr);
1631 return NULL;
1634 name = fd->getDeclName().getAsString();
1635 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1636 if (!res)
1637 return NULL;
1639 for (int i = 0; i < expr->getNumArgs(); ++i) {
1640 Expr *arg = expr->getArg(i);
1641 int is_addr = 0;
1642 pet_expr *main_arg;
1644 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1645 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1646 arg = ice->getSubExpr();
1648 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1649 UnaryOperator *op = cast<UnaryOperator>(arg);
1650 if (op->getOpcode() == UO_AddrOf) {
1651 is_addr = 1;
1652 arg = op->getSubExpr();
1655 res->args[i] = PetScan::extract_expr(arg);
1656 main_arg = res->args[i];
1657 if (is_addr)
1658 res->args[i] = pet_expr_new_unary(ctx,
1659 pet_op_address_of, res->args[i]);
1660 if (!res->args[i])
1661 goto error;
1662 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1663 array_depth(arg->getType().getTypePtr()) > 0)
1664 is_addr = 1;
1665 if (is_addr && main_arg->type == pet_expr_access) {
1666 ParmVarDecl *parm;
1667 if (!fd->hasPrototype()) {
1668 unsupported(expr, "prototype required");
1669 goto error;
1671 parm = fd->getParamDecl(i);
1672 if (!const_base(parm->getType()))
1673 mark_write(main_arg);
1677 return res;
1678 error:
1679 pet_expr_free(res);
1680 return NULL;
1683 /* Construct a pet_expr representing a (C style) cast.
1685 struct pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1687 struct pet_expr *arg;
1688 QualType type;
1690 arg = extract_expr(expr->getSubExpr());
1691 if (!arg)
1692 return NULL;
1694 type = expr->getTypeAsWritten();
1695 return pet_expr_new_cast(ctx, type.getAsString().c_str(), arg);
1698 /* Try and onstruct a pet_expr representing "expr".
1700 struct pet_expr *PetScan::extract_expr(Expr *expr)
1702 switch (expr->getStmtClass()) {
1703 case Stmt::UnaryOperatorClass:
1704 return extract_expr(cast<UnaryOperator>(expr));
1705 case Stmt::CompoundAssignOperatorClass:
1706 case Stmt::BinaryOperatorClass:
1707 return extract_expr(cast<BinaryOperator>(expr));
1708 case Stmt::ImplicitCastExprClass:
1709 return extract_expr(cast<ImplicitCastExpr>(expr));
1710 case Stmt::ArraySubscriptExprClass:
1711 case Stmt::DeclRefExprClass:
1712 case Stmt::IntegerLiteralClass:
1713 return extract_access_expr(expr);
1714 case Stmt::FloatingLiteralClass:
1715 return extract_expr(cast<FloatingLiteral>(expr));
1716 case Stmt::ParenExprClass:
1717 return extract_expr(cast<ParenExpr>(expr));
1718 case Stmt::ConditionalOperatorClass:
1719 return extract_expr(cast<ConditionalOperator>(expr));
1720 case Stmt::CallExprClass:
1721 return extract_expr(cast<CallExpr>(expr));
1722 case Stmt::CStyleCastExprClass:
1723 return extract_expr(cast<CStyleCastExpr>(expr));
1724 default:
1725 unsupported(expr);
1727 return NULL;
1730 /* Check if the given initialization statement is an assignment.
1731 * If so, return that assignment. Otherwise return NULL.
1733 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1735 BinaryOperator *ass;
1737 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1738 return NULL;
1740 ass = cast<BinaryOperator>(init);
1741 if (ass->getOpcode() != BO_Assign)
1742 return NULL;
1744 return ass;
1747 /* Check if the given initialization statement is a declaration
1748 * of a single variable.
1749 * If so, return that declaration. Otherwise return NULL.
1751 Decl *PetScan::initialization_declaration(Stmt *init)
1753 DeclStmt *decl;
1755 if (init->getStmtClass() != Stmt::DeclStmtClass)
1756 return NULL;
1758 decl = cast<DeclStmt>(init);
1760 if (!decl->isSingleDecl())
1761 return NULL;
1763 return decl->getSingleDecl();
1766 /* Given the assignment operator in the initialization of a for loop,
1767 * extract the induction variable, i.e., the (integer)variable being
1768 * assigned.
1770 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1772 Expr *lhs;
1773 DeclRefExpr *ref;
1774 ValueDecl *decl;
1775 const Type *type;
1777 lhs = init->getLHS();
1778 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1779 unsupported(init);
1780 return NULL;
1783 ref = cast<DeclRefExpr>(lhs);
1784 decl = ref->getDecl();
1785 type = decl->getType().getTypePtr();
1787 if (!type->isIntegerType()) {
1788 unsupported(lhs);
1789 return NULL;
1792 return decl;
1795 /* Given the initialization statement of a for loop and the single
1796 * declaration in this initialization statement,
1797 * extract the induction variable, i.e., the (integer) variable being
1798 * declared.
1800 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1802 VarDecl *vd;
1804 vd = cast<VarDecl>(decl);
1806 const QualType type = vd->getType();
1807 if (!type->isIntegerType()) {
1808 unsupported(init);
1809 return NULL;
1812 if (!vd->getInit()) {
1813 unsupported(init);
1814 return NULL;
1817 return vd;
1820 /* Check that op is of the form iv++ or iv--.
1821 * Return an affine expression "1" or "-1" accordingly.
1823 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
1824 clang::UnaryOperator *op, clang::ValueDecl *iv)
1826 Expr *sub;
1827 DeclRefExpr *ref;
1828 isl_space *space;
1829 isl_aff *aff;
1831 if (!op->isIncrementDecrementOp()) {
1832 unsupported(op);
1833 return NULL;
1836 sub = op->getSubExpr();
1837 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1838 unsupported(op);
1839 return NULL;
1842 ref = cast<DeclRefExpr>(sub);
1843 if (ref->getDecl() != iv) {
1844 unsupported(op);
1845 return NULL;
1848 space = isl_space_params_alloc(ctx, 0);
1849 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1851 if (op->isIncrementOp())
1852 aff = isl_aff_add_constant_si(aff, 1);
1853 else
1854 aff = isl_aff_add_constant_si(aff, -1);
1856 return isl_pw_aff_from_aff(aff);
1859 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1860 * has a single constant expression, then put this constant in *user.
1861 * The caller is assumed to have checked that this function will
1862 * be called exactly once.
1864 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1865 void *user)
1867 isl_val **inc = (isl_val **)user;
1868 int res = 0;
1870 if (isl_aff_is_cst(aff))
1871 *inc = isl_aff_get_constant_val(aff);
1872 else
1873 res = -1;
1875 isl_set_free(set);
1876 isl_aff_free(aff);
1878 return res;
1881 /* Check if op is of the form
1883 * iv = iv + inc
1885 * and return inc as an affine expression.
1887 * We extract an affine expression from the RHS, subtract iv and return
1888 * the result.
1890 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
1891 clang::ValueDecl *iv)
1893 Expr *lhs;
1894 DeclRefExpr *ref;
1895 isl_id *id;
1896 isl_space *dim;
1897 isl_aff *aff;
1898 isl_pw_aff *val;
1900 if (op->getOpcode() != BO_Assign) {
1901 unsupported(op);
1902 return NULL;
1905 lhs = op->getLHS();
1906 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1907 unsupported(op);
1908 return NULL;
1911 ref = cast<DeclRefExpr>(lhs);
1912 if (ref->getDecl() != iv) {
1913 unsupported(op);
1914 return NULL;
1917 val = extract_affine(op->getRHS());
1919 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1921 dim = isl_space_params_alloc(ctx, 1);
1922 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1923 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1924 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1926 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1928 return val;
1931 /* Check that op is of the form iv += cst or iv -= cst
1932 * and return an affine expression corresponding oto cst or -cst accordingly.
1934 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
1935 CompoundAssignOperator *op, clang::ValueDecl *iv)
1937 Expr *lhs;
1938 DeclRefExpr *ref;
1939 bool neg = false;
1940 isl_pw_aff *val;
1941 BinaryOperatorKind opcode;
1943 opcode = op->getOpcode();
1944 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1945 unsupported(op);
1946 return NULL;
1948 if (opcode == BO_SubAssign)
1949 neg = true;
1951 lhs = op->getLHS();
1952 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1953 unsupported(op);
1954 return NULL;
1957 ref = cast<DeclRefExpr>(lhs);
1958 if (ref->getDecl() != iv) {
1959 unsupported(op);
1960 return NULL;
1963 val = extract_affine(op->getRHS());
1964 if (neg)
1965 val = isl_pw_aff_neg(val);
1967 return val;
1970 /* Check that the increment of the given for loop increments
1971 * (or decrements) the induction variable "iv" and return
1972 * the increment as an affine expression if successful.
1974 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
1975 ValueDecl *iv)
1977 Stmt *inc = stmt->getInc();
1979 if (!inc) {
1980 unsupported(stmt);
1981 return NULL;
1984 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1985 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1986 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1987 return extract_compound_increment(
1988 cast<CompoundAssignOperator>(inc), iv);
1989 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1990 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1992 unsupported(inc);
1993 return NULL;
1996 /* Embed the given iteration domain in an extra outer loop
1997 * with induction variable "var".
1998 * If this variable appeared as a parameter in the constraints,
1999 * it is replaced by the new outermost dimension.
2001 static __isl_give isl_set *embed(__isl_take isl_set *set,
2002 __isl_take isl_id *var)
2004 int pos;
2006 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
2007 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
2008 if (pos >= 0) {
2009 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
2010 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2013 isl_id_free(var);
2014 return set;
2017 /* Return those elements in the space of "cond" that come after
2018 * (based on "sign") an element in "cond".
2020 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
2022 isl_map *previous_to_this;
2024 if (sign > 0)
2025 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
2026 else
2027 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
2029 cond = isl_set_apply(cond, previous_to_this);
2031 return cond;
2034 /* Create the infinite iteration domain
2036 * { [id] : id >= 0 }
2038 * If "scop" has an affine skip of type pet_skip_later,
2039 * then remove those iterations i that have an earlier iteration
2040 * where the skip condition is satisfied, meaning that iteration i
2041 * is not executed.
2042 * Since we are dealing with a loop without loop iterator,
2043 * the skip condition cannot refer to the current loop iterator and
2044 * so effectively, the returned set is of the form
2046 * { [0]; [id] : id >= 1 and not skip }
2048 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
2049 struct pet_scop *scop)
2051 isl_ctx *ctx = isl_id_get_ctx(id);
2052 isl_set *domain;
2053 isl_set *skip;
2055 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
2056 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
2058 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
2059 return domain;
2061 skip = pet_scop_get_skip(scop, pet_skip_later);
2062 skip = isl_set_fix_si(skip, isl_dim_set, 0, 1);
2063 skip = isl_set_params(skip);
2064 skip = embed(skip, isl_id_copy(id));
2065 skip = isl_set_intersect(skip , isl_set_copy(domain));
2066 domain = isl_set_subtract(domain, after(skip, 1));
2068 return domain;
2071 /* Create an identity mapping on the space containing "domain".
2073 static __isl_give isl_map *identity_map(__isl_keep isl_set *domain)
2075 isl_space *space;
2076 isl_map *id;
2078 space = isl_space_map_from_set(isl_set_get_space(domain));
2079 id = isl_map_identity(space);
2081 return id;
2084 /* Add a filter to "scop" that imposes that it is only executed
2085 * when "break_access" has a zero value for all previous iterations
2086 * of "domain".
2088 * The input "break_access" has a zero-dimensional domain and range.
2090 static struct pet_scop *scop_add_break(struct pet_scop *scop,
2091 __isl_take isl_map *break_access, __isl_take isl_set *domain, int sign)
2093 isl_ctx *ctx = isl_set_get_ctx(domain);
2094 isl_id *id_test;
2095 isl_map *prev;
2097 id_test = isl_map_get_tuple_id(break_access, isl_dim_out);
2098 break_access = isl_map_add_dims(break_access, isl_dim_in, 1);
2099 break_access = isl_map_add_dims(break_access, isl_dim_out, 1);
2100 break_access = isl_map_intersect_range(break_access, domain);
2101 break_access = isl_map_set_tuple_id(break_access, isl_dim_out, id_test);
2102 if (sign > 0)
2103 prev = isl_map_lex_gt_first(isl_map_get_space(break_access), 1);
2104 else
2105 prev = isl_map_lex_lt_first(isl_map_get_space(break_access), 1);
2106 break_access = isl_map_intersect(break_access, prev);
2107 scop = pet_scop_filter(scop, break_access, 0);
2108 scop = pet_scop_merge_filters(scop);
2110 return scop;
2113 /* Construct a pet_scop for an infinite loop around the given body.
2115 * We extract a pet_scop for the body and then embed it in a loop with
2116 * iteration domain
2118 * { [t] : t >= 0 }
2120 * and schedule
2122 * { [t] -> [t] }
2124 * If the body contains any break, then it is taken into
2125 * account in infinite_domain (if the skip condition is affine)
2126 * or in scop_add_break (if the skip condition is not affine).
2128 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2130 isl_id *id;
2131 isl_set *domain;
2132 isl_map *ident;
2133 isl_map *access;
2134 struct pet_scop *scop;
2135 bool has_var_break;
2137 scop = extract(body);
2138 if (!scop)
2139 return NULL;
2141 id = isl_id_alloc(ctx, "t", NULL);
2142 domain = infinite_domain(isl_id_copy(id), scop);
2143 ident = identity_map(domain);
2145 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2146 if (has_var_break)
2147 access = pet_scop_get_skip_map(scop, pet_skip_later);
2149 scop = pet_scop_embed(scop, isl_set_copy(domain),
2150 isl_map_copy(ident), ident, id);
2151 if (has_var_break)
2152 scop = scop_add_break(scop, access, domain, 1);
2153 else
2154 isl_set_free(domain);
2156 return scop;
2159 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2161 * for (;;)
2162 * body
2165 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2167 return extract_infinite_loop(stmt->getBody());
2170 /* Create an access to a virtual array representing the result
2171 * of a condition.
2172 * Unlike other accessed data, the id of the array is NULL as
2173 * there is no ValueDecl in the program corresponding to the virtual
2174 * array.
2175 * The array starts out as a scalar, but grows along with the
2176 * statement writing to the array in pet_scop_embed.
2178 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2180 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2181 isl_id *id;
2182 char name[50];
2184 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2185 id = isl_id_alloc(ctx, name, NULL);
2186 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2187 return isl_map_universe(dim);
2190 /* Add an array with the given extent ("access") to the list
2191 * of arrays in "scop" and return the extended pet_scop.
2192 * The array is marked as attaining values 0 and 1 only and
2193 * as each element being assigned at most once.
2195 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2196 __isl_keep isl_map *access, clang::ASTContext &ast_ctx)
2198 isl_ctx *ctx = isl_map_get_ctx(access);
2199 isl_space *dim;
2200 struct pet_array *array;
2202 if (!scop)
2203 return NULL;
2204 if (!ctx)
2205 goto error;
2207 array = isl_calloc_type(ctx, struct pet_array);
2208 if (!array)
2209 goto error;
2211 array->extent = isl_map_range(isl_map_copy(access));
2212 dim = isl_space_params_alloc(ctx, 0);
2213 array->context = isl_set_universe(dim);
2214 dim = isl_space_set_alloc(ctx, 0, 1);
2215 array->value_bounds = isl_set_universe(dim);
2216 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2217 isl_dim_set, 0, 0);
2218 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2219 isl_dim_set, 0, 1);
2220 array->element_type = strdup("int");
2221 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2222 array->uniquely_defined = 1;
2224 if (!array->extent || !array->context)
2225 array = pet_array_free(array);
2227 scop = pet_scop_add_array(scop, array);
2229 return scop;
2230 error:
2231 pet_scop_free(scop);
2232 return NULL;
2235 /* Construct a pet_scop for a while loop of the form
2237 * while (pa)
2238 * body
2240 * In particular, construct a scop for an infinite loop around body and
2241 * intersect the domain with the affine expression.
2242 * Note that this intersection may result in an empty loop.
2244 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2245 Stmt *body)
2247 struct pet_scop *scop;
2248 isl_set *dom;
2249 isl_set *valid;
2251 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2252 dom = isl_pw_aff_non_zero_set(pa);
2253 scop = extract_infinite_loop(body);
2254 scop = pet_scop_restrict(scop, dom);
2255 scop = pet_scop_restrict_context(scop, valid);
2257 return scop;
2260 /* Construct a scop for a while, given the scops for the condition
2261 * and the body, the filter access and the iteration domain of
2262 * the while loop.
2264 * In particular, the scop for the condition is filtered to depend
2265 * on "test_access" evaluating to true for all previous iterations
2266 * of the loop, while the scop for the body is filtered to depend
2267 * on "test_access" evaluating to true for all iterations up to the
2268 * current iteration.
2270 * These filtered scops are then combined into a single scop.
2272 * "sign" is positive if the iterator increases and negative
2273 * if it decreases.
2275 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2276 struct pet_scop *scop_body, __isl_take isl_map *test_access,
2277 __isl_take isl_set *domain, int sign)
2279 isl_ctx *ctx = isl_set_get_ctx(domain);
2280 isl_id *id_test;
2281 isl_map *prev;
2283 id_test = isl_map_get_tuple_id(test_access, isl_dim_out);
2284 test_access = isl_map_add_dims(test_access, isl_dim_in, 1);
2285 test_access = isl_map_add_dims(test_access, isl_dim_out, 1);
2286 test_access = isl_map_intersect_range(test_access, domain);
2287 test_access = isl_map_set_tuple_id(test_access, isl_dim_out, id_test);
2288 if (sign > 0)
2289 prev = isl_map_lex_ge_first(isl_map_get_space(test_access), 1);
2290 else
2291 prev = isl_map_lex_le_first(isl_map_get_space(test_access), 1);
2292 test_access = isl_map_intersect(test_access, prev);
2293 scop_body = pet_scop_filter(scop_body, isl_map_copy(test_access), 1);
2294 if (sign > 0)
2295 prev = isl_map_lex_gt_first(isl_map_get_space(test_access), 1);
2296 else
2297 prev = isl_map_lex_lt_first(isl_map_get_space(test_access), 1);
2298 test_access = isl_map_intersect(test_access, prev);
2299 scop_cond = pet_scop_filter(scop_cond, test_access, 1);
2301 return pet_scop_add_seq(ctx, scop_cond, scop_body);
2304 /* Check if the while loop is of the form
2306 * while (affine expression)
2307 * body
2309 * If so, call extract_affine_while to construct a scop.
2311 * Otherwise, construct a generic while scop, with iteration domain
2312 * { [t] : t >= 0 }. The scop consists of two parts, one for
2313 * evaluating the condition and one for the body.
2314 * The schedule is adjusted to reflect that the condition is evaluated
2315 * before the body is executed and the body is filtered to depend
2316 * on the result of the condition evaluating to true on all iterations
2317 * up to the current iteration, while the evaluation the condition itself
2318 * is filtered to depend on the result of the condition evaluating to true
2319 * on all previous iterations.
2320 * The context of the scop representing the body is dropped
2321 * because we don't know how many times the body will be executed,
2322 * if at all.
2324 * If the body contains any break, then it is taken into
2325 * account in infinite_domain (if the skip condition is affine)
2326 * or in scop_add_break (if the skip condition is not affine).
2328 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2330 Expr *cond;
2331 isl_id *id;
2332 isl_map *test_access;
2333 isl_set *domain;
2334 isl_map *ident;
2335 isl_pw_aff *pa;
2336 struct pet_scop *scop, *scop_body;
2337 bool has_var_break;
2338 isl_map *break_access;
2340 cond = stmt->getCond();
2341 if (!cond) {
2342 unsupported(stmt);
2343 return NULL;
2346 clear_assignments clear(assigned_value);
2347 clear.TraverseStmt(stmt->getBody());
2349 pa = try_extract_affine_condition(cond);
2350 if (pa)
2351 return extract_affine_while(pa, stmt->getBody());
2353 if (!allow_nested) {
2354 unsupported(stmt);
2355 return NULL;
2358 test_access = create_test_access(ctx, n_test++);
2359 scop = extract_non_affine_condition(cond, isl_map_copy(test_access));
2360 scop = scop_add_array(scop, test_access, ast_context);
2361 scop_body = extract(stmt->getBody());
2363 id = isl_id_alloc(ctx, "t", NULL);
2364 domain = infinite_domain(isl_id_copy(id), scop_body);
2365 ident = identity_map(domain);
2367 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2368 if (has_var_break)
2369 break_access = pet_scop_get_skip_map(scop_body, pet_skip_later);
2371 scop = pet_scop_prefix(scop, 0);
2372 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_map_copy(ident),
2373 isl_map_copy(ident), isl_id_copy(id));
2374 scop_body = pet_scop_reset_context(scop_body);
2375 scop_body = pet_scop_prefix(scop_body, 1);
2376 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2377 isl_map_copy(ident), ident, id);
2379 if (has_var_break) {
2380 scop = scop_add_break(scop, isl_map_copy(break_access),
2381 isl_set_copy(domain), 1);
2382 scop_body = scop_add_break(scop_body, break_access,
2383 isl_set_copy(domain), 1);
2385 scop = scop_add_while(scop, scop_body, test_access, domain, 1);
2387 return scop;
2390 /* Check whether "cond" expresses a simple loop bound
2391 * on the only set dimension.
2392 * In particular, if "up" is set then "cond" should contain only
2393 * upper bounds on the set dimension.
2394 * Otherwise, it should contain only lower bounds.
2396 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2398 if (isl_val_is_pos(inc))
2399 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2400 else
2401 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2404 /* Extend a condition on a given iteration of a loop to one that
2405 * imposes the same condition on all previous iterations.
2406 * "domain" expresses the lower [upper] bound on the iterations
2407 * when inc is positive [negative].
2409 * In particular, we construct the condition (when inc is positive)
2411 * forall i' : (domain(i') and i' <= i) => cond(i')
2413 * which is equivalent to
2415 * not exists i' : domain(i') and i' <= i and not cond(i')
2417 * We construct this set by negating cond, applying a map
2419 * { [i'] -> [i] : domain(i') and i' <= i }
2421 * and then negating the result again.
2423 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2424 __isl_take isl_set *domain, __isl_take isl_val *inc)
2426 isl_map *previous_to_this;
2428 if (isl_val_is_pos(inc))
2429 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2430 else
2431 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2433 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2435 cond = isl_set_complement(cond);
2436 cond = isl_set_apply(cond, previous_to_this);
2437 cond = isl_set_complement(cond);
2439 isl_val_free(inc);
2441 return cond;
2444 /* Construct a domain of the form
2446 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2448 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2449 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2451 isl_aff *aff;
2452 isl_space *dim;
2453 isl_set *set;
2455 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2456 dim = isl_pw_aff_get_domain_space(init);
2457 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2458 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2459 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2461 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2462 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2463 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2464 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2466 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2468 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2470 return isl_set_params(set);
2473 /* Assuming "cond" represents a bound on a loop where the loop
2474 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2475 * is possible.
2477 * Under the given assumptions, wrapping is only possible if "cond" allows
2478 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2479 * increasing iterator and 0 in case of a decreasing iterator.
2481 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2482 __isl_keep isl_val *inc)
2484 bool cw;
2485 isl_ctx *ctx;
2486 isl_val *limit;
2487 isl_set *test;
2489 test = isl_set_copy(cond);
2491 ctx = isl_set_get_ctx(test);
2492 if (isl_val_is_neg(inc))
2493 limit = isl_val_zero(ctx);
2494 else {
2495 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2496 limit = isl_val_2exp(limit);
2497 limit = isl_val_sub_ui(limit, 1);
2500 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2501 cw = !isl_set_is_empty(test);
2502 isl_set_free(test);
2504 return cw;
2507 /* Given a one-dimensional space, construct the following mapping on this
2508 * space
2510 * { [v] -> [v mod 2^width] }
2512 * where width is the number of bits used to represent the values
2513 * of the unsigned variable "iv".
2515 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
2516 ValueDecl *iv)
2518 isl_ctx *ctx;
2519 isl_val *mod;
2520 isl_aff *aff;
2521 isl_map *map;
2523 ctx = isl_space_get_ctx(dim);
2524 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2525 mod = isl_val_2exp(mod);
2527 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2528 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2529 aff = isl_aff_mod_val(aff, mod);
2531 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2532 map = isl_map_reverse(map);
2535 /* Project out the parameter "id" from "set".
2537 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2538 __isl_keep isl_id *id)
2540 int pos;
2542 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2543 if (pos >= 0)
2544 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2546 return set;
2549 /* Compute the set of parameters for which "set1" is a subset of "set2".
2551 * set1 is a subset of set2 if
2553 * forall i in set1 : i in set2
2555 * or
2557 * not exists i in set1 and i not in set2
2559 * i.e.,
2561 * not exists i in set1 \ set2
2563 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2564 __isl_take isl_set *set2)
2566 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2569 /* Compute the set of parameter values for which "cond" holds
2570 * on the next iteration for each element of "dom".
2572 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2573 * and then compute the set of parameters for which the result is a subset
2574 * of "cond".
2576 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2577 __isl_take isl_set *dom, __isl_take isl_val *inc)
2579 isl_space *space;
2580 isl_aff *aff;
2581 isl_map *next;
2583 space = isl_set_get_space(dom);
2584 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2585 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2586 aff = isl_aff_add_constant_val(aff, inc);
2587 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2589 dom = isl_set_apply(dom, next);
2591 return enforce_subset(dom, cond);
2594 /* Does "id" refer to a nested access?
2596 static bool is_nested_parameter(__isl_keep isl_id *id)
2598 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2601 /* Does parameter "pos" of "space" refer to a nested access?
2603 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2605 bool nested;
2606 isl_id *id;
2608 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2609 nested = is_nested_parameter(id);
2610 isl_id_free(id);
2612 return nested;
2615 /* Does "space" involve any parameters that refer to nested
2616 * accesses, i.e., parameters with no name?
2618 static bool has_nested(__isl_keep isl_space *space)
2620 int nparam;
2622 nparam = isl_space_dim(space, isl_dim_param);
2623 for (int i = 0; i < nparam; ++i)
2624 if (is_nested_parameter(space, i))
2625 return true;
2627 return false;
2630 /* Does "pa" involve any parameters that refer to nested
2631 * accesses, i.e., parameters with no name?
2633 static bool has_nested(__isl_keep isl_pw_aff *pa)
2635 isl_space *space;
2636 bool nested;
2638 space = isl_pw_aff_get_space(pa);
2639 nested = has_nested(space);
2640 isl_space_free(space);
2642 return nested;
2645 /* Construct a pet_scop for a for statement.
2646 * The for loop is required to be of the form
2648 * for (i = init; condition; ++i)
2650 * or
2652 * for (i = init; condition; --i)
2654 * The initialization of the for loop should either be an assignment
2655 * to an integer variable, or a declaration of such a variable with
2656 * initialization.
2658 * The condition is allowed to contain nested accesses, provided
2659 * they are not being written to inside the body of the loop.
2660 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2661 * essentially treated as a while loop, with iteration domain
2662 * { [i] : i >= init }.
2664 * We extract a pet_scop for the body and then embed it in a loop with
2665 * iteration domain and schedule
2667 * { [i] : i >= init and condition' }
2668 * { [i] -> [i] }
2670 * or
2672 * { [i] : i <= init and condition' }
2673 * { [i] -> [-i] }
2675 * Where condition' is equal to condition if the latter is
2676 * a simple upper [lower] bound and a condition that is extended
2677 * to apply to all previous iterations otherwise.
2679 * If the condition is non-affine, then we drop the condition from the
2680 * iteration domain and instead create a separate statement
2681 * for evaluating the condition. The body is then filtered to depend
2682 * on the result of the condition evaluating to true on all iterations
2683 * up to the current iteration, while the evaluation the condition itself
2684 * is filtered to depend on the result of the condition evaluating to true
2685 * on all previous iterations.
2686 * The context of the scop representing the body is dropped
2687 * because we don't know how many times the body will be executed,
2688 * if at all.
2690 * If the stride of the loop is not 1, then "i >= init" is replaced by
2692 * (exists a: i = init + stride * a and a >= 0)
2694 * If the loop iterator i is unsigned, then wrapping may occur.
2695 * During the computation, we work with a virtual iterator that
2696 * does not wrap. However, the condition in the code applies
2697 * to the wrapped value, so we need to change condition(i)
2698 * into condition([i % 2^width]).
2699 * After computing the virtual domain and schedule, we apply
2700 * the function { [v] -> [v % 2^width] } to the domain and the domain
2701 * of the schedule. In order not to lose any information, we also
2702 * need to intersect the domain of the schedule with the virtual domain
2703 * first, since some iterations in the wrapped domain may be scheduled
2704 * several times, typically an infinite number of times.
2705 * Note that there may be no need to perform this final wrapping
2706 * if the loop condition (after wrapping) satisfies certain conditions.
2707 * However, the is_simple_bound condition is not enough since it doesn't
2708 * check if there even is an upper bound.
2710 * If the loop condition is non-affine, then we keep the virtual
2711 * iterator in the iteration domain and instead replace all accesses
2712 * to the original iterator by the wrapping of the virtual iterator.
2714 * Wrapping on unsigned iterators can be avoided entirely if
2715 * loop condition is simple, the loop iterator is incremented
2716 * [decremented] by one and the last value before wrapping cannot
2717 * possibly satisfy the loop condition.
2719 * Before extracting a pet_scop from the body we remove all
2720 * assignments in assigned_value to variables that are assigned
2721 * somewhere in the body of the loop.
2723 * Valid parameters for a for loop are those for which the initial
2724 * value itself, the increment on each domain iteration and
2725 * the condition on both the initial value and
2726 * the result of incrementing the iterator for each iteration of the domain
2727 * can be evaluated.
2728 * If the loop condition is non-affine, then we only consider validity
2729 * of the initial value.
2731 * If the body contains any break, then we keep track of it in "skip"
2732 * (if the skip condition is affine) or it is handled in scop_add_break
2733 * (if the skip condition is not affine).
2734 * Note that the affine break condition needs to be considered with
2735 * respect to previous iterations in the virtual domain (if any)
2736 * and that the domain needs to be kept virtual if there is a non-affine
2737 * break condition.
2739 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2741 BinaryOperator *ass;
2742 Decl *decl;
2743 Stmt *init;
2744 Expr *lhs, *rhs;
2745 ValueDecl *iv;
2746 isl_space *space;
2747 isl_set *domain;
2748 isl_map *sched;
2749 isl_set *cond = NULL;
2750 isl_set *skip = NULL;
2751 isl_id *id;
2752 struct pet_scop *scop, *scop_cond = NULL;
2753 assigned_value_cache cache(assigned_value);
2754 isl_val *inc;
2755 bool is_one;
2756 bool is_unsigned;
2757 bool is_simple;
2758 bool is_virtual;
2759 bool keep_virtual = false;
2760 bool has_affine_break;
2761 bool has_var_break;
2762 isl_map *wrap = NULL;
2763 isl_pw_aff *pa, *pa_inc, *init_val;
2764 isl_set *valid_init;
2765 isl_set *valid_cond;
2766 isl_set *valid_cond_init;
2767 isl_set *valid_cond_next;
2768 isl_set *valid_inc;
2769 isl_map *test_access = NULL, *break_access = NULL;
2770 int stmt_id;
2772 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2773 return extract_infinite_for(stmt);
2775 init = stmt->getInit();
2776 if (!init) {
2777 unsupported(stmt);
2778 return NULL;
2780 if ((ass = initialization_assignment(init)) != NULL) {
2781 iv = extract_induction_variable(ass);
2782 if (!iv)
2783 return NULL;
2784 lhs = ass->getLHS();
2785 rhs = ass->getRHS();
2786 } else if ((decl = initialization_declaration(init)) != NULL) {
2787 VarDecl *var = extract_induction_variable(init, decl);
2788 if (!var)
2789 return NULL;
2790 iv = var;
2791 rhs = var->getInit();
2792 lhs = create_DeclRefExpr(var);
2793 } else {
2794 unsupported(stmt->getInit());
2795 return NULL;
2798 pa_inc = extract_increment(stmt, iv);
2799 if (!pa_inc)
2800 return NULL;
2802 inc = NULL;
2803 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
2804 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
2805 isl_pw_aff_free(pa_inc);
2806 unsupported(stmt->getInc());
2807 isl_val_free(inc);
2808 return NULL;
2810 valid_inc = isl_pw_aff_domain(pa_inc);
2812 is_unsigned = iv->getType()->isUnsignedIntegerType();
2814 assigned_value.erase(iv);
2815 clear_assignments clear(assigned_value);
2816 clear.TraverseStmt(stmt->getBody());
2818 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2820 pa = try_extract_nested_condition(stmt->getCond());
2821 if (allow_nested && (!pa || has_nested(pa)))
2822 stmt_id = n_stmt++;
2824 scop = extract(stmt->getBody());
2826 has_affine_break = scop &&
2827 pet_scop_has_affine_skip(scop, pet_skip_later);
2828 if (has_affine_break) {
2829 skip = pet_scop_get_skip(scop, pet_skip_later);
2830 skip = isl_set_fix_si(skip, isl_dim_set, 0, 1);
2831 skip = isl_set_params(skip);
2833 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
2834 if (has_var_break) {
2835 break_access = pet_scop_get_skip_map(scop, pet_skip_later);
2836 keep_virtual = true;
2839 if (pa && !is_nested_allowed(pa, scop)) {
2840 isl_pw_aff_free(pa);
2841 pa = NULL;
2844 if (!allow_nested && !pa)
2845 pa = try_extract_affine_condition(stmt->getCond());
2846 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2847 cond = isl_pw_aff_non_zero_set(pa);
2848 if (allow_nested && !cond) {
2849 int save_n_stmt = n_stmt;
2850 test_access = create_test_access(ctx, n_test++);
2851 n_stmt = stmt_id;
2852 scop_cond = extract_non_affine_condition(stmt->getCond(),
2853 isl_map_copy(test_access));
2854 n_stmt = save_n_stmt;
2855 scop_cond = scop_add_array(scop_cond, test_access, ast_context);
2856 scop_cond = pet_scop_prefix(scop_cond, 0);
2857 scop = pet_scop_reset_context(scop);
2858 scop = pet_scop_prefix(scop, 1);
2859 keep_virtual = true;
2860 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2863 cond = embed(cond, isl_id_copy(id));
2864 skip = embed(skip, isl_id_copy(id));
2865 valid_cond = isl_set_coalesce(valid_cond);
2866 valid_cond = embed(valid_cond, isl_id_copy(id));
2867 valid_inc = embed(valid_inc, isl_id_copy(id));
2868 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
2869 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2871 init_val = extract_affine(rhs);
2872 valid_cond_init = enforce_subset(
2873 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
2874 isl_set_copy(valid_cond));
2875 if (is_one && !is_virtual) {
2876 isl_pw_aff_free(init_val);
2877 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
2878 lhs, rhs, init);
2879 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2880 valid_init = set_project_out_by_id(valid_init, id);
2881 domain = isl_pw_aff_non_zero_set(pa);
2882 } else {
2883 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2884 domain = strided_domain(isl_id_copy(id), init_val,
2885 isl_val_copy(inc));
2888 domain = embed(domain, isl_id_copy(id));
2889 if (is_virtual) {
2890 isl_map *rev_wrap;
2891 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2892 rev_wrap = isl_map_reverse(isl_map_copy(wrap));
2893 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2894 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
2895 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2896 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2898 is_simple = is_simple_bound(cond, inc);
2899 if (!is_simple) {
2900 cond = isl_set_gist(cond, isl_set_copy(domain));
2901 is_simple = is_simple_bound(cond, inc);
2903 if (!is_simple)
2904 cond = valid_for_each_iteration(cond,
2905 isl_set_copy(domain), isl_val_copy(inc));
2906 domain = isl_set_intersect(domain, cond);
2907 if (has_affine_break) {
2908 skip = isl_set_intersect(skip , isl_set_copy(domain));
2909 skip = after(skip, isl_val_sgn(inc));
2910 domain = isl_set_subtract(domain, skip);
2912 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2913 space = isl_space_from_domain(isl_set_get_space(domain));
2914 space = isl_space_add_dims(space, isl_dim_out, 1);
2915 sched = isl_map_universe(space);
2916 if (isl_val_is_pos(inc))
2917 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2918 else
2919 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2921 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
2922 isl_val_copy(inc));
2923 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2925 if (is_virtual && !keep_virtual) {
2926 wrap = isl_map_set_dim_id(wrap,
2927 isl_dim_out, 0, isl_id_copy(id));
2928 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2929 domain = isl_set_apply(domain, isl_map_copy(wrap));
2930 sched = isl_map_apply_domain(sched, wrap);
2932 if (!(is_virtual && keep_virtual)) {
2933 space = isl_set_get_space(domain);
2934 wrap = isl_map_identity(isl_space_map_from_set(space));
2937 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
2938 isl_map_copy(sched), isl_map_copy(wrap), isl_id_copy(id));
2939 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
2940 scop = resolve_nested(scop);
2941 if (has_var_break)
2942 scop = scop_add_break(scop, break_access, isl_set_copy(domain),
2943 isl_val_sgn(inc));
2944 if (test_access) {
2945 scop = scop_add_while(scop_cond, scop, test_access, domain,
2946 isl_val_sgn(inc));
2947 isl_set_free(valid_inc);
2948 } else {
2949 scop = pet_scop_restrict_context(scop, valid_inc);
2950 scop = pet_scop_restrict_context(scop, valid_cond_next);
2951 scop = pet_scop_restrict_context(scop, valid_cond_init);
2952 isl_set_free(domain);
2954 clear_assignment(assigned_value, iv);
2956 isl_val_free(inc);
2958 scop = pet_scop_restrict_context(scop, valid_init);
2960 return scop;
2963 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
2965 return extract(stmt->children(), true, skip_declarations);
2968 /* Does parameter "pos" of "map" refer to a nested access?
2970 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2972 bool nested;
2973 isl_id *id;
2975 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2976 nested = is_nested_parameter(id);
2977 isl_id_free(id);
2979 return nested;
2982 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2984 static int n_nested_parameter(__isl_keep isl_space *space)
2986 int n = 0;
2987 int nparam;
2989 nparam = isl_space_dim(space, isl_dim_param);
2990 for (int i = 0; i < nparam; ++i)
2991 if (is_nested_parameter(space, i))
2992 ++n;
2994 return n;
2997 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2999 static int n_nested_parameter(__isl_keep isl_map *map)
3001 isl_space *space;
3002 int n;
3004 space = isl_map_get_space(map);
3005 n = n_nested_parameter(space);
3006 isl_space_free(space);
3008 return n;
3011 /* For each nested access parameter in "space",
3012 * construct a corresponding pet_expr, place it in args and
3013 * record its position in "param2pos".
3014 * "n_arg" is the number of elements that are already in args.
3015 * The position recorded in "param2pos" takes this number into account.
3016 * If the pet_expr corresponding to a parameter is identical to
3017 * the pet_expr corresponding to an earlier parameter, then these two
3018 * parameters are made to refer to the same element in args.
3020 * Return the final number of elements in args or -1 if an error has occurred.
3022 int PetScan::extract_nested(__isl_keep isl_space *space,
3023 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
3025 int nparam;
3027 nparam = isl_space_dim(space, isl_dim_param);
3028 for (int i = 0; i < nparam; ++i) {
3029 int j;
3030 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3031 Expr *nested;
3033 if (!is_nested_parameter(id)) {
3034 isl_id_free(id);
3035 continue;
3038 nested = (Expr *) isl_id_get_user(id);
3039 args[n_arg] = extract_expr(nested);
3040 if (!args[n_arg])
3041 return -1;
3043 for (j = 0; j < n_arg; ++j)
3044 if (pet_expr_is_equal(args[j], args[n_arg]))
3045 break;
3047 if (j < n_arg) {
3048 pet_expr_free(args[n_arg]);
3049 args[n_arg] = NULL;
3050 param2pos[i] = j;
3051 } else
3052 param2pos[i] = n_arg++;
3054 isl_id_free(id);
3057 return n_arg;
3060 /* For each nested access parameter in the access relations in "expr",
3061 * construct a corresponding pet_expr, place it in expr->args and
3062 * record its position in "param2pos".
3063 * n is the number of nested access parameters.
3065 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
3066 std::map<int,int> &param2pos)
3068 isl_space *space;
3070 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
3071 expr->n_arg = n;
3072 if (!expr->args)
3073 goto error;
3075 space = isl_map_get_space(expr->acc.access);
3076 n = extract_nested(space, 0, expr->args, param2pos);
3077 isl_space_free(space);
3079 if (n < 0)
3080 goto error;
3082 expr->n_arg = n;
3083 return expr;
3084 error:
3085 pet_expr_free(expr);
3086 return NULL;
3089 /* Look for parameters in any access relation in "expr" that
3090 * refer to nested accesses. In particular, these are
3091 * parameters with no name.
3093 * If there are any such parameters, then the domain of the access
3094 * relation, which is still [] at this point, is replaced by
3095 * [[] -> [t_1,...,t_n]], with n the number of these parameters
3096 * (after identifying identical nested accesses).
3097 * The parameters are then equated to the corresponding t dimensions
3098 * and subsequently projected out.
3099 * param2pos maps the position of the parameter to the position
3100 * of the corresponding t dimension.
3102 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
3104 int n;
3105 int nparam;
3106 int n_in;
3107 isl_space *dim;
3108 isl_map *map;
3109 std::map<int,int> param2pos;
3111 if (!expr)
3112 return expr;
3114 for (int i = 0; i < expr->n_arg; ++i) {
3115 expr->args[i] = resolve_nested(expr->args[i]);
3116 if (!expr->args[i]) {
3117 pet_expr_free(expr);
3118 return NULL;
3122 if (expr->type != pet_expr_access)
3123 return expr;
3125 n = n_nested_parameter(expr->acc.access);
3126 if (n == 0)
3127 return expr;
3129 expr = extract_nested(expr, n, param2pos);
3130 if (!expr)
3131 return NULL;
3133 n = expr->n_arg;
3134 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
3135 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
3136 dim = isl_map_get_space(expr->acc.access);
3137 dim = isl_space_domain(dim);
3138 dim = isl_space_from_domain(dim);
3139 dim = isl_space_add_dims(dim, isl_dim_out, n);
3140 map = isl_map_universe(dim);
3141 map = isl_map_domain_map(map);
3142 map = isl_map_reverse(map);
3143 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
3145 for (int i = nparam - 1; i >= 0; --i) {
3146 isl_id *id = isl_map_get_dim_id(expr->acc.access,
3147 isl_dim_param, i);
3148 if (!is_nested_parameter(id)) {
3149 isl_id_free(id);
3150 continue;
3153 expr->acc.access = isl_map_equate(expr->acc.access,
3154 isl_dim_param, i, isl_dim_in,
3155 n_in + param2pos[i]);
3156 expr->acc.access = isl_map_project_out(expr->acc.access,
3157 isl_dim_param, i, 1);
3159 isl_id_free(id);
3162 return expr;
3163 error:
3164 pet_expr_free(expr);
3165 return NULL;
3168 /* Return the file offset of the expansion location of "Loc".
3170 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3172 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3175 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3177 /* Return a SourceLocation for the location after the first semicolon
3178 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3179 * call it and also skip trailing spaces and newline.
3181 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3182 const LangOptions &LO)
3184 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3187 #else
3189 /* Return a SourceLocation for the location after the first semicolon
3190 * after "loc". If Lexer::findLocationAfterToken is not available,
3191 * we look in the underlying character data for the first semicolon.
3193 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3194 const LangOptions &LO)
3196 const char *semi;
3197 const char *s = SM.getCharacterData(loc);
3199 semi = strchr(s, ';');
3200 if (!semi)
3201 return SourceLocation();
3202 return loc.getFileLocWithOffset(semi + 1 - s);
3205 #endif
3207 /* If the token at "loc" is the first token on the line, then return
3208 * a location referring to the start of the line.
3209 * Otherwise, return "loc".
3211 * This function is used to extend a scop to the start of the line
3212 * if the first token of the scop is also the first token on the line.
3214 * We look for the first token on the line. If its location is equal to "loc",
3215 * then the latter is the location of the first token on the line.
3217 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3218 SourceManager &SM, const LangOptions &LO)
3220 std::pair<FileID, unsigned> file_offset_pair;
3221 llvm::StringRef file;
3222 const char *pos;
3223 Token tok;
3224 SourceLocation token_loc, line_loc;
3225 int col;
3227 loc = SM.getExpansionLoc(loc);
3228 col = SM.getExpansionColumnNumber(loc);
3229 line_loc = loc.getLocWithOffset(1 - col);
3230 file_offset_pair = SM.getDecomposedLoc(line_loc);
3231 file = SM.getBufferData(file_offset_pair.first, NULL);
3232 pos = file.data() + file_offset_pair.second;
3234 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3235 file.begin(), pos, file.end());
3236 lexer.LexFromRawLexer(tok);
3237 token_loc = tok.getLocation();
3239 if (token_loc == loc)
3240 return line_loc;
3241 else
3242 return loc;
3245 /* Convert a top-level pet_expr to a pet_scop with one statement.
3246 * This mainly involves resolving nested expression parameters
3247 * and setting the name of the iteration space.
3248 * The name is given by "label" if it is non-NULL. Otherwise,
3249 * it is of the form S_<n_stmt>.
3250 * start and end of the pet_scop are derived from those of "stmt".
3252 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
3253 __isl_take isl_id *label)
3255 struct pet_stmt *ps;
3256 struct pet_scop *scop;
3257 SourceLocation loc = stmt->getLocStart();
3258 SourceManager &SM = PP.getSourceManager();
3259 const LangOptions &LO = PP.getLangOpts();
3260 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3261 unsigned start, end;
3263 expr = resolve_nested(expr);
3264 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
3265 scop = pet_scop_from_pet_stmt(ctx, ps);
3267 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3268 start = getExpansionOffset(SM, loc);
3269 loc = stmt->getLocEnd();
3270 loc = location_after_semi(loc, SM, LO);
3271 end = getExpansionOffset(SM, loc);
3273 scop = pet_scop_update_start_end(scop, start, end);
3274 return scop;
3277 /* Check if we can extract an affine expression from "expr".
3278 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3279 * We turn on autodetection so that we won't generate any warnings
3280 * and turn off nesting, so that we won't accept any non-affine constructs.
3282 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3284 isl_pw_aff *pwaff;
3285 int save_autodetect = options->autodetect;
3286 bool save_nesting = nesting_enabled;
3288 options->autodetect = 1;
3289 nesting_enabled = false;
3291 pwaff = extract_affine(expr);
3293 options->autodetect = save_autodetect;
3294 nesting_enabled = save_nesting;
3296 return pwaff;
3299 /* Check whether "expr" is an affine expression.
3301 bool PetScan::is_affine(Expr *expr)
3303 isl_pw_aff *pwaff;
3305 pwaff = try_extract_affine(expr);
3306 isl_pw_aff_free(pwaff);
3308 return pwaff != NULL;
3311 /* Check if we can extract an affine constraint from "expr".
3312 * Return the constraint as an isl_set if we can and NULL otherwise.
3313 * We turn on autodetection so that we won't generate any warnings
3314 * and turn off nesting, so that we won't accept any non-affine constructs.
3316 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3318 isl_pw_aff *cond;
3319 int save_autodetect = options->autodetect;
3320 bool save_nesting = nesting_enabled;
3322 options->autodetect = 1;
3323 nesting_enabled = false;
3325 cond = extract_condition(expr);
3327 options->autodetect = save_autodetect;
3328 nesting_enabled = save_nesting;
3330 return cond;
3333 /* Check whether "expr" is an affine constraint.
3335 bool PetScan::is_affine_condition(Expr *expr)
3337 isl_pw_aff *cond;
3339 cond = try_extract_affine_condition(expr);
3340 isl_pw_aff_free(cond);
3342 return cond != NULL;
3345 /* Check if we can extract a condition from "expr".
3346 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3347 * If allow_nested is set, then the condition may involve parameters
3348 * corresponding to nested accesses.
3349 * We turn on autodetection so that we won't generate any warnings.
3351 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3353 isl_pw_aff *cond;
3354 int save_autodetect = options->autodetect;
3355 bool save_nesting = nesting_enabled;
3357 options->autodetect = 1;
3358 nesting_enabled = allow_nested;
3359 cond = extract_condition(expr);
3361 options->autodetect = save_autodetect;
3362 nesting_enabled = save_nesting;
3364 return cond;
3367 /* If the top-level expression of "stmt" is an assignment, then
3368 * return that assignment as a BinaryOperator.
3369 * Otherwise return NULL.
3371 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3373 BinaryOperator *ass;
3375 if (!stmt)
3376 return NULL;
3377 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3378 return NULL;
3380 ass = cast<BinaryOperator>(stmt);
3381 if(ass->getOpcode() != BO_Assign)
3382 return NULL;
3384 return ass;
3387 /* Check if the given if statement is a conditional assignement
3388 * with a non-affine condition. If so, construct a pet_scop
3389 * corresponding to this conditional assignment. Otherwise return NULL.
3391 * In particular we check if "stmt" is of the form
3393 * if (condition)
3394 * a = f(...);
3395 * else
3396 * a = g(...);
3398 * where a is some array or scalar access.
3399 * The constructed pet_scop then corresponds to the expression
3401 * a = condition ? f(...) : g(...)
3403 * All access relations in f(...) are intersected with condition
3404 * while all access relation in g(...) are intersected with the complement.
3406 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3408 BinaryOperator *ass_then, *ass_else;
3409 isl_map *write_then, *write_else;
3410 isl_set *cond, *comp;
3411 isl_map *map;
3412 isl_pw_aff *pa;
3413 int equal;
3414 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3415 bool save_nesting = nesting_enabled;
3417 if (!options->detect_conditional_assignment)
3418 return NULL;
3420 ass_then = top_assignment_or_null(stmt->getThen());
3421 ass_else = top_assignment_or_null(stmt->getElse());
3423 if (!ass_then || !ass_else)
3424 return NULL;
3426 if (is_affine_condition(stmt->getCond()))
3427 return NULL;
3429 write_then = extract_access(ass_then->getLHS());
3430 write_else = extract_access(ass_else->getLHS());
3432 equal = isl_map_is_equal(write_then, write_else);
3433 isl_map_free(write_else);
3434 if (equal < 0 || !equal) {
3435 isl_map_free(write_then);
3436 return NULL;
3439 nesting_enabled = allow_nested;
3440 pa = extract_condition(stmt->getCond());
3441 nesting_enabled = save_nesting;
3442 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3443 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3444 map = isl_map_from_range(isl_set_from_pw_aff(pa));
3446 pe_cond = pet_expr_from_access(map);
3448 pe_then = extract_expr(ass_then->getRHS());
3449 pe_then = pet_expr_restrict(pe_then, cond);
3450 pe_else = extract_expr(ass_else->getRHS());
3451 pe_else = pet_expr_restrict(pe_else, comp);
3453 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
3454 pe_write = pet_expr_from_access(write_then);
3455 if (pe_write) {
3456 pe_write->acc.write = 1;
3457 pe_write->acc.read = 0;
3459 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
3460 return extract(stmt, pe);
3463 /* Create a pet_scop with a single statement evaluating "cond"
3464 * and writing the result to a virtual scalar, as expressed by
3465 * "access".
3467 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
3468 __isl_take isl_map *access)
3470 struct pet_expr *expr, *write;
3471 struct pet_stmt *ps;
3472 struct pet_scop *scop;
3473 SourceLocation loc = cond->getLocStart();
3474 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3476 write = pet_expr_from_access(access);
3477 if (write) {
3478 write->acc.write = 1;
3479 write->acc.read = 0;
3481 expr = extract_expr(cond);
3482 expr = resolve_nested(expr);
3483 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
3484 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
3485 scop = pet_scop_from_pet_stmt(ctx, ps);
3486 scop = resolve_nested(scop);
3488 return scop;
3491 extern "C" {
3492 static struct pet_expr *embed_access(struct pet_expr *expr, void *user);
3495 /* Apply the map pointed to by "user" to the domain of the access
3496 * relation associated to "expr", thereby embedding it in the range of the map.
3497 * The domain of both relations is the zero-dimensional domain.
3499 static struct pet_expr *embed_access(struct pet_expr *expr, void *user)
3501 isl_map *map = (isl_map *) user;
3503 expr->acc.access = isl_map_apply_domain(expr->acc.access,
3504 isl_map_copy(map));
3505 if (!expr->acc.access)
3506 goto error;
3508 return expr;
3509 error:
3510 pet_expr_free(expr);
3511 return NULL;
3514 /* Apply "map" to all access relations in "expr".
3516 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
3518 return pet_expr_map_access(expr, &embed_access, map);
3521 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3523 static int n_nested_parameter(__isl_keep isl_set *set)
3525 isl_space *space;
3526 int n;
3528 space = isl_set_get_space(set);
3529 n = n_nested_parameter(space);
3530 isl_space_free(space);
3532 return n;
3535 /* Remove all parameters from "map" that refer to nested accesses.
3537 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
3539 int nparam;
3540 isl_space *space;
3542 space = isl_map_get_space(map);
3543 nparam = isl_space_dim(space, isl_dim_param);
3544 for (int i = nparam - 1; i >= 0; --i)
3545 if (is_nested_parameter(space, i))
3546 map = isl_map_project_out(map, isl_dim_param, i, 1);
3547 isl_space_free(space);
3549 return map;
3552 /* Remove all parameters from the access relation of "expr"
3553 * that refer to nested accesses.
3555 static struct pet_expr *remove_nested_parameters(struct pet_expr *expr)
3557 expr->acc.access = remove_nested_parameters(expr->acc.access);
3558 if (!expr->acc.access)
3559 goto error;
3561 return expr;
3562 error:
3563 pet_expr_free(expr);
3564 return NULL;
3567 extern "C" {
3568 static struct pet_expr *expr_remove_nested_parameters(
3569 struct pet_expr *expr, void *user);
3572 static struct pet_expr *expr_remove_nested_parameters(
3573 struct pet_expr *expr, void *user)
3575 return remove_nested_parameters(expr);
3578 /* Remove all nested access parameters from the schedule and all
3579 * accesses of "stmt".
3580 * There is no need to remove them from the domain as these parameters
3581 * have already been removed from the domain when this function is called.
3583 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
3585 if (!stmt)
3586 return NULL;
3587 stmt->schedule = remove_nested_parameters(stmt->schedule);
3588 stmt->body = pet_expr_map_access(stmt->body,
3589 &expr_remove_nested_parameters, NULL);
3590 if (!stmt->schedule || !stmt->body)
3591 goto error;
3592 for (int i = 0; i < stmt->n_arg; ++i) {
3593 stmt->args[i] = pet_expr_map_access(stmt->args[i],
3594 &expr_remove_nested_parameters, NULL);
3595 if (!stmt->args[i])
3596 goto error;
3599 return stmt;
3600 error:
3601 pet_stmt_free(stmt);
3602 return NULL;
3605 /* For each nested access parameter in the domain of "stmt",
3606 * construct a corresponding pet_expr, place it before the original
3607 * elements in stmt->args and record its position in "param2pos".
3608 * n is the number of nested access parameters.
3610 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3611 std::map<int,int> &param2pos)
3613 int i;
3614 isl_space *space;
3615 int n_arg;
3616 struct pet_expr **args;
3618 n_arg = stmt->n_arg;
3619 args = isl_calloc_array(ctx, struct pet_expr *, n + n_arg);
3620 if (!args)
3621 goto error;
3623 space = isl_set_get_space(stmt->domain);
3624 n_arg = extract_nested(space, 0, args, param2pos);
3625 isl_space_free(space);
3627 if (n_arg < 0)
3628 goto error;
3630 for (i = 0; i < stmt->n_arg; ++i)
3631 args[n_arg + i] = stmt->args[i];
3632 free(stmt->args);
3633 stmt->args = args;
3634 stmt->n_arg += n_arg;
3636 return stmt;
3637 error:
3638 if (args) {
3639 for (i = 0; i < n; ++i)
3640 pet_expr_free(args[i]);
3641 free(args);
3643 pet_stmt_free(stmt);
3644 return NULL;
3647 /* Check whether any of the arguments i of "stmt" starting at position "n"
3648 * is equal to one of the first "n" arguments j.
3649 * If so, combine the constraints on arguments i and j and remove
3650 * argument i.
3652 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3654 int i, j;
3655 isl_map *map;
3657 if (!stmt)
3658 return NULL;
3659 if (n == 0)
3660 return stmt;
3661 if (n == stmt->n_arg)
3662 return stmt;
3664 map = isl_set_unwrap(stmt->domain);
3666 for (i = stmt->n_arg - 1; i >= n; --i) {
3667 for (j = 0; j < n; ++j)
3668 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3669 break;
3670 if (j >= n)
3671 continue;
3673 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3674 map = isl_map_project_out(map, isl_dim_out, i, 1);
3676 pet_expr_free(stmt->args[i]);
3677 for (j = i; j + 1 < stmt->n_arg; ++j)
3678 stmt->args[j] = stmt->args[j + 1];
3679 stmt->n_arg--;
3682 stmt->domain = isl_map_wrap(map);
3683 if (!stmt->domain)
3684 goto error;
3685 return stmt;
3686 error:
3687 pet_stmt_free(stmt);
3688 return NULL;
3691 /* Look for parameters in the iteration domain of "stmt" that
3692 * refer to nested accesses. In particular, these are
3693 * parameters with no name.
3695 * If there are any such parameters, then as many extra variables
3696 * (after identifying identical nested accesses) are inserted in the
3697 * range of the map wrapped inside the domain, before the original variables.
3698 * If the original domain is not a wrapped map, then a new wrapped
3699 * map is created with zero output dimensions.
3700 * The parameters are then equated to the corresponding output dimensions
3701 * and subsequently projected out, from the iteration domain,
3702 * the schedule and the access relations.
3703 * For each of the output dimensions, a corresponding argument
3704 * expression is inserted. Initially they are created with
3705 * a zero-dimensional domain, so they have to be embedded
3706 * in the current iteration domain.
3707 * param2pos maps the position of the parameter to the position
3708 * of the corresponding output dimension in the wrapped map.
3710 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3712 int n;
3713 int nparam;
3714 unsigned n_arg;
3715 isl_map *map;
3716 std::map<int,int> param2pos;
3718 if (!stmt)
3719 return NULL;
3721 n = n_nested_parameter(stmt->domain);
3722 if (n == 0)
3723 return stmt;
3725 n_arg = stmt->n_arg;
3726 stmt = extract_nested(stmt, n, param2pos);
3727 if (!stmt)
3728 return NULL;
3730 n = stmt->n_arg - n_arg;
3731 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3732 if (isl_set_is_wrapping(stmt->domain))
3733 map = isl_set_unwrap(stmt->domain);
3734 else
3735 map = isl_map_from_domain(stmt->domain);
3736 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3738 for (int i = nparam - 1; i >= 0; --i) {
3739 isl_id *id;
3741 if (!is_nested_parameter(map, i))
3742 continue;
3744 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
3745 isl_dim_out);
3746 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3747 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3748 param2pos[i]);
3749 map = isl_map_project_out(map, isl_dim_param, i, 1);
3752 stmt->domain = isl_map_wrap(map);
3754 map = isl_set_unwrap(isl_set_copy(stmt->domain));
3755 map = isl_map_from_range(isl_map_domain(map));
3756 for (int pos = 0; pos < n; ++pos)
3757 stmt->args[pos] = embed(stmt->args[pos], map);
3758 isl_map_free(map);
3760 stmt = remove_nested_parameters(stmt);
3761 stmt = remove_duplicate_arguments(stmt, n);
3763 return stmt;
3764 error:
3765 pet_stmt_free(stmt);
3766 return NULL;
3769 /* For each statement in "scop", move the parameters that correspond
3770 * to nested access into the ranges of the domains and create
3771 * corresponding argument expressions.
3773 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3775 if (!scop)
3776 return NULL;
3778 for (int i = 0; i < scop->n_stmt; ++i) {
3779 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3780 if (!scop->stmts[i])
3781 goto error;
3784 return scop;
3785 error:
3786 pet_scop_free(scop);
3787 return NULL;
3790 /* Given an access expression "expr", is the variable accessed by
3791 * "expr" assigned anywhere inside "scop"?
3793 static bool is_assigned(pet_expr *expr, pet_scop *scop)
3795 bool assigned = false;
3796 isl_id *id;
3798 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
3799 assigned = pet_scop_writes(scop, id);
3800 isl_id_free(id);
3802 return assigned;
3805 /* Are all nested access parameters in "pa" allowed given "scop".
3806 * In particular, is none of them written by anywhere inside "scop".
3808 * If "scop" has any skip conditions, then no nested access parameters
3809 * are allowed. In particular, if there is any nested access in a guard
3810 * for a piece of code containing a "continue", then we want to introduce
3811 * a separate statement for evaluating this guard so that we can express
3812 * that the result is false for all previous iterations.
3814 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3816 int nparam;
3818 if (!scop)
3819 return true;
3821 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3822 for (int i = 0; i < nparam; ++i) {
3823 Expr *nested;
3824 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3825 pet_expr *expr;
3826 bool allowed;
3828 if (!is_nested_parameter(id)) {
3829 isl_id_free(id);
3830 continue;
3833 if (pet_scop_has_skip(scop, pet_skip_now)) {
3834 isl_id_free(id);
3835 return false;
3838 nested = (Expr *) isl_id_get_user(id);
3839 expr = extract_expr(nested);
3840 allowed = expr && expr->type == pet_expr_access &&
3841 !is_assigned(expr, scop);
3843 pet_expr_free(expr);
3844 isl_id_free(id);
3846 if (!allowed)
3847 return false;
3850 return true;
3853 /* Do we need to construct a skip condition of the given type
3854 * on an if statement, given that the if condition is non-affine?
3856 * pet_scop_filter_skip can only handle the case where the if condition
3857 * holds (the then branch) and the skip condition is universal.
3858 * In any other case, we need to construct a new skip condition.
3860 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3861 bool have_else, enum pet_skip type)
3863 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
3864 return true;
3865 if (scop_then && pet_scop_has_skip(scop_then, type) &&
3866 !pet_scop_has_universal_skip(scop_then, type))
3867 return true;
3868 return false;
3871 /* Do we need to construct a skip condition of the given type
3872 * on an if statement, given that the if condition is affine?
3874 * There is no need to construct a new skip condition if all
3875 * the skip conditions are affine.
3877 static bool need_skip_aff(struct pet_scop *scop_then,
3878 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
3880 if (scop_then && pet_scop_has_var_skip(scop_then, type))
3881 return true;
3882 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
3883 return true;
3884 return false;
3887 /* Do we need to construct a skip condition of the given type
3888 * on an if statement?
3890 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3891 bool have_else, enum pet_skip type, bool affine)
3893 if (affine)
3894 return need_skip_aff(scop_then, scop_else, have_else, type);
3895 else
3896 return need_skip(scop_then, scop_else, have_else, type);
3899 /* Construct an affine expression pet_expr that evaluates
3900 * to the constant "val".
3902 static struct pet_expr *universally(isl_ctx *ctx, int val)
3904 isl_space *space;
3905 isl_map *map;
3907 space = isl_space_alloc(ctx, 0, 0, 1);
3908 map = isl_map_universe(space);
3909 map = isl_map_fix_si(map, isl_dim_out, 0, val);
3911 return pet_expr_from_access(map);
3914 /* Construct an affine expression pet_expr that evaluates
3915 * to the constant 1.
3917 static struct pet_expr *universally_true(isl_ctx *ctx)
3919 return universally(ctx, 1);
3922 /* Construct an affine expression pet_expr that evaluates
3923 * to the constant 0.
3925 static struct pet_expr *universally_false(isl_ctx *ctx)
3927 return universally(ctx, 0);
3930 /* Given an access relation "test_access" for the if condition,
3931 * an access relation "skip_access" for the skip condition and
3932 * scops for the then and else branches, construct a scop for
3933 * computing "skip_access".
3935 * The computed scop contains a single statement that essentially does
3937 * skip_cond = test_cond ? skip_cond_then : skip_cond_else
3939 * If the skip conditions of the then and/or else branch are not affine,
3940 * then they need to be filtered by test_access.
3941 * If they are missing, then this means the skip condition is false.
3943 * Since we are constructing a skip condition for the if statement,
3944 * the skip conditions on the then and else branches are removed.
3946 static struct pet_scop *extract_skip(PetScan *scan,
3947 __isl_take isl_map *test_access, __isl_take isl_map *skip_access,
3948 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
3949 enum pet_skip type)
3951 struct pet_expr *expr_then, *expr_else, *expr, *expr_skip;
3952 struct pet_stmt *stmt;
3953 struct pet_scop *scop;
3954 isl_ctx *ctx = scan->ctx;
3956 if (!scop_then)
3957 goto error;
3958 if (have_else && !scop_else)
3959 goto error;
3961 if (pet_scop_has_skip(scop_then, type)) {
3962 expr_then = pet_scop_get_skip_expr(scop_then, type);
3963 pet_scop_reset_skip(scop_then, type);
3964 if (!pet_expr_is_affine(expr_then))
3965 expr_then = pet_expr_filter(expr_then,
3966 isl_map_copy(test_access), 1);
3967 } else
3968 expr_then = universally_false(ctx);
3970 if (have_else && pet_scop_has_skip(scop_else, type)) {
3971 expr_else = pet_scop_get_skip_expr(scop_else, type);
3972 pet_scop_reset_skip(scop_else, type);
3973 if (!pet_expr_is_affine(expr_else))
3974 expr_else = pet_expr_filter(expr_else,
3975 isl_map_copy(test_access), 0);
3976 } else
3977 expr_else = universally_false(ctx);
3979 expr = pet_expr_from_access(test_access);
3980 expr = pet_expr_new_ternary(ctx, expr, expr_then, expr_else);
3981 expr_skip = pet_expr_from_access(isl_map_copy(skip_access));
3982 if (expr_skip) {
3983 expr_skip->acc.write = 1;
3984 expr_skip->acc.read = 0;
3986 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
3987 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, scan->n_stmt++, expr);
3989 scop = pet_scop_from_pet_stmt(ctx, stmt);
3990 scop = scop_add_array(scop, skip_access, scan->ast_context);
3991 isl_map_free(skip_access);
3993 return scop;
3994 error:
3995 isl_map_free(test_access);
3996 isl_map_free(skip_access);
3997 return NULL;
4000 /* Is scop's skip_now condition equal to its skip_later condition?
4001 * In particular, this means that it either has no skip_now condition
4002 * or both a skip_now and a skip_later condition (that are equal to each other).
4004 static bool skip_equals_skip_later(struct pet_scop *scop)
4006 int has_skip_now, has_skip_later;
4007 int equal;
4008 isl_set *skip_now, *skip_later;
4010 if (!scop)
4011 return false;
4012 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
4013 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
4014 if (has_skip_now != has_skip_later)
4015 return false;
4016 if (!has_skip_now)
4017 return true;
4019 skip_now = pet_scop_get_skip(scop, pet_skip_now);
4020 skip_later = pet_scop_get_skip(scop, pet_skip_later);
4021 equal = isl_set_is_equal(skip_now, skip_later);
4022 isl_set_free(skip_now);
4023 isl_set_free(skip_later);
4025 return equal;
4028 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
4030 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
4032 pet_scop_reset_skip(scop1, pet_skip_later);
4033 pet_scop_reset_skip(scop2, pet_skip_later);
4036 /* Structure that handles the construction of skip conditions.
4038 * scop_then and scop_else represent the then and else branches
4039 * of the if statement
4041 * skip[type] is true if we need to construct a skip condition of that type
4042 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
4043 * are equal to each other
4044 * access[type] is the virtual array representing the skip condition
4045 * scop[type] is a scop for computing the skip condition
4047 struct pet_skip_info {
4048 isl_ctx *ctx;
4050 bool skip[2];
4051 bool equal;
4052 isl_map *access[2];
4053 struct pet_scop *scop[2];
4055 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
4057 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
4060 /* Structure that handles the construction of skip conditions on if statements.
4062 * scop_then and scop_else represent the then and else branches
4063 * of the if statement
4065 struct pet_skip_info_if : public pet_skip_info {
4066 struct pet_scop *scop_then, *scop_else;
4067 bool have_else;
4069 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4070 struct pet_scop *scop_else, bool have_else, bool affine);
4071 void extract(PetScan *scan, __isl_keep isl_map *access,
4072 enum pet_skip type);
4073 void extract(PetScan *scan, __isl_keep isl_map *access);
4074 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
4075 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4076 int offset);
4077 struct pet_scop *add(struct pet_scop *scop, int offset);
4080 /* Initialize a pet_skip_info_if structure based on the then and else branches
4081 * and based on whether the if condition is affine or not.
4083 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4084 struct pet_scop *scop_else, bool have_else, bool affine) :
4085 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
4086 have_else(have_else)
4088 skip[pet_skip_now] =
4089 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
4090 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
4091 (!have_else || skip_equals_skip_later(scop_else));
4092 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4093 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
4096 /* If we need to construct a skip condition of the given type,
4097 * then do so now.
4099 * "map" represents the if condition.
4101 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_map *map,
4102 enum pet_skip type)
4104 if (!skip[type])
4105 return;
4107 access[type] = create_test_access(isl_map_get_ctx(map), scan->n_test++);
4108 scop[type] = extract_skip(scan, isl_map_copy(map),
4109 isl_map_copy(access[type]),
4110 scop_then, scop_else, have_else, type);
4113 /* Construct the required skip conditions, given the if condition "map".
4115 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_map *map)
4117 extract(scan, map, pet_skip_now);
4118 extract(scan, map, pet_skip_later);
4119 if (equal)
4120 drop_skip_later(scop_then, scop_else);
4123 /* Construct the required skip conditions, given the if condition "cond".
4125 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
4127 isl_set *test_set;
4128 isl_map *test;
4130 if (!skip[pet_skip_now] && !skip[pet_skip_later])
4131 return;
4133 test_set = isl_set_from_pw_aff(isl_pw_aff_copy(cond));
4134 test = isl_map_from_range(test_set);
4135 extract(scan, test);
4136 isl_map_free(test);
4139 /* Add the computed skip condition of the give type to "main" and
4140 * add the scop for computing the condition at the given offset.
4142 * If equal is set, then we only computed a skip condition for pet_skip_now,
4143 * but we also need to set it as main's pet_skip_later.
4145 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
4146 enum pet_skip type, int offset)
4148 isl_set *skip_set;
4150 if (!skip[type])
4151 return main;
4153 skip_set = isl_map_range(access[type]);
4154 access[type] = NULL;
4155 scop[type] = pet_scop_prefix(scop[type], offset);
4156 main = pet_scop_add_par(ctx, main, scop[type]);
4157 scop[type] = NULL;
4159 if (equal)
4160 main = pet_scop_set_skip(main, pet_skip_later,
4161 isl_set_copy(skip_set));
4163 main = pet_scop_set_skip(main, type, skip_set);
4165 return main;
4168 /* Add the computed skip conditions to "main" and
4169 * add the scops for computing the conditions at the given offset.
4171 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
4173 scop = add(scop, pet_skip_now, offset);
4174 scop = add(scop, pet_skip_later, offset);
4176 return scop;
4179 /* Construct a pet_scop for a non-affine if statement.
4181 * We create a separate statement that writes the result
4182 * of the non-affine condition to a virtual scalar.
4183 * A constraint requiring the value of this virtual scalar to be one
4184 * is added to the iteration domains of the then branch.
4185 * Similarly, a constraint requiring the value of this virtual scalar
4186 * to be zero is added to the iteration domains of the else branch, if any.
4187 * We adjust the schedules to ensure that the virtual scalar is written
4188 * before it is read.
4190 * If there are any breaks or continues in the then and/or else
4191 * branches, then we may have to compute a new skip condition.
4192 * This is handled using a pet_skip_info_if object.
4193 * On initialization, the object checks if skip conditions need
4194 * to be computed. If so, it does so in "extract" and adds them in "add".
4196 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
4197 struct pet_scop *scop_then, struct pet_scop *scop_else,
4198 bool have_else, int stmt_id)
4200 struct pet_scop *scop;
4201 isl_map *test_access;
4202 int save_n_stmt = n_stmt;
4204 test_access = create_test_access(ctx, n_test++);
4205 n_stmt = stmt_id;
4206 scop = extract_non_affine_condition(cond, isl_map_copy(test_access));
4207 n_stmt = save_n_stmt;
4208 scop = scop_add_array(scop, test_access, ast_context);
4210 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
4211 skip.extract(this, test_access);
4213 scop = pet_scop_prefix(scop, 0);
4214 scop_then = pet_scop_prefix(scop_then, 1);
4215 scop_then = pet_scop_filter(scop_then, isl_map_copy(test_access), 1);
4216 if (have_else) {
4217 scop_else = pet_scop_prefix(scop_else, 1);
4218 scop_else = pet_scop_filter(scop_else, test_access, 0);
4219 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
4220 } else
4221 isl_map_free(test_access);
4223 scop = pet_scop_add_seq(ctx, scop, scop_then);
4225 scop = skip.add(scop, 2);
4227 return scop;
4230 /* Construct a pet_scop for an if statement.
4232 * If the condition fits the pattern of a conditional assignment,
4233 * then it is handled by extract_conditional_assignment.
4234 * Otherwise, we do the following.
4236 * If the condition is affine, then the condition is added
4237 * to the iteration domains of the then branch, while the
4238 * opposite of the condition in added to the iteration domains
4239 * of the else branch, if any.
4240 * We allow the condition to be dynamic, i.e., to refer to
4241 * scalars or array elements that may be written to outside
4242 * of the given if statement. These nested accesses are then represented
4243 * as output dimensions in the wrapping iteration domain.
4244 * If it also written _inside_ the then or else branch, then
4245 * we treat the condition as non-affine.
4246 * As explained in extract_non_affine_if, this will introduce
4247 * an extra statement.
4248 * For aesthetic reasons, we want this statement to have a statement
4249 * number that is lower than those of the then and else branches.
4250 * In order to evaluate if will need such a statement, however, we
4251 * first construct scops for the then and else branches.
4252 * We therefore reserve a statement number if we might have to
4253 * introduce such an extra statement.
4255 * If the condition is not affine, then the scop is created in
4256 * extract_non_affine_if.
4258 * If there are any breaks or continues in the then and/or else
4259 * branches, then we may have to compute a new skip condition.
4260 * This is handled using a pet_skip_info_if object.
4261 * On initialization, the object checks if skip conditions need
4262 * to be computed. If so, it does so in "extract" and adds them in "add".
4264 struct pet_scop *PetScan::extract(IfStmt *stmt)
4266 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4267 isl_pw_aff *cond;
4268 int stmt_id;
4269 isl_set *set;
4270 isl_set *valid;
4272 scop = extract_conditional_assignment(stmt);
4273 if (scop)
4274 return scop;
4276 cond = try_extract_nested_condition(stmt->getCond());
4277 if (allow_nested && (!cond || has_nested(cond)))
4278 stmt_id = n_stmt++;
4281 assigned_value_cache cache(assigned_value);
4282 scop_then = extract(stmt->getThen());
4285 if (stmt->getElse()) {
4286 assigned_value_cache cache(assigned_value);
4287 scop_else = extract(stmt->getElse());
4288 if (options->autodetect) {
4289 if (scop_then && !scop_else) {
4290 partial = true;
4291 isl_pw_aff_free(cond);
4292 return scop_then;
4294 if (!scop_then && scop_else) {
4295 partial = true;
4296 isl_pw_aff_free(cond);
4297 return scop_else;
4302 if (cond &&
4303 (!is_nested_allowed(cond, scop_then) ||
4304 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4305 isl_pw_aff_free(cond);
4306 cond = NULL;
4308 if (allow_nested && !cond)
4309 return extract_non_affine_if(stmt->getCond(), scop_then,
4310 scop_else, stmt->getElse(), stmt_id);
4312 if (!cond)
4313 cond = extract_condition(stmt->getCond());
4315 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4316 skip.extract(this, cond);
4318 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4319 set = isl_pw_aff_non_zero_set(cond);
4320 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4322 if (stmt->getElse()) {
4323 set = isl_set_subtract(isl_set_copy(valid), set);
4324 scop_else = pet_scop_restrict(scop_else, set);
4325 scop = pet_scop_add_par(ctx, scop, scop_else);
4326 } else
4327 isl_set_free(set);
4328 scop = resolve_nested(scop);
4329 scop = pet_scop_restrict_context(scop, valid);
4331 if (skip)
4332 scop = pet_scop_prefix(scop, 0);
4333 scop = skip.add(scop, 1);
4335 return scop;
4338 /* Try and construct a pet_scop for a label statement.
4339 * We currently only allow labels on expression statements.
4341 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4343 isl_id *label;
4344 Stmt *sub;
4346 sub = stmt->getSubStmt();
4347 if (!isa<Expr>(sub)) {
4348 unsupported(stmt);
4349 return NULL;
4352 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4354 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4357 /* Construct a pet_scop for a continue statement.
4359 * We simply create an empty scop with a universal pet_skip_now
4360 * skip condition. This skip condition will then be taken into
4361 * account by the enclosing loop construct, possibly after
4362 * being incorporated into outer skip conditions.
4364 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4366 pet_scop *scop;
4367 isl_space *space;
4368 isl_set *set;
4370 scop = pet_scop_empty(ctx);
4371 if (!scop)
4372 return NULL;
4374 space = isl_space_set_alloc(ctx, 0, 1);
4375 set = isl_set_universe(space);
4376 set = isl_set_fix_si(set, isl_dim_set, 0, 1);
4377 scop = pet_scop_set_skip(scop, pet_skip_now, set);
4379 return scop;
4382 /* Construct a pet_scop for a break statement.
4384 * We simply create an empty scop with both a universal pet_skip_now
4385 * skip condition and a universal pet_skip_later skip condition.
4386 * These skip conditions will then be taken into
4387 * account by the enclosing loop construct, possibly after
4388 * being incorporated into outer skip conditions.
4390 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4392 pet_scop *scop;
4393 isl_space *space;
4394 isl_set *set;
4396 scop = pet_scop_empty(ctx);
4397 if (!scop)
4398 return NULL;
4400 space = isl_space_set_alloc(ctx, 0, 1);
4401 set = isl_set_universe(space);
4402 set = isl_set_fix_si(set, isl_dim_set, 0, 1);
4403 scop = pet_scop_set_skip(scop, pet_skip_now, isl_set_copy(set));
4404 scop = pet_scop_set_skip(scop, pet_skip_later, set);
4406 return scop;
4409 /* Try and construct a pet_scop corresponding to "stmt".
4411 * If "stmt" is a compound statement, then "skip_declarations"
4412 * indicates whether we should skip initial declarations in the
4413 * compound statement.
4415 * If the constructed pet_scop is not a (possibly) partial representation
4416 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4417 * In particular, if skip_declarations, then we may have skipped declarations
4418 * inside "stmt" and so the pet_scop may not represent the entire "stmt".
4419 * Note that this function may be called with "stmt" referring to the entire
4420 * body of the function, including the outer braces. In such cases,
4421 * skip_declarations will be set and the braces will not be taken into
4422 * account in scop->start and scop->end.
4424 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
4426 struct pet_scop *scop;
4427 unsigned start, end;
4428 SourceLocation loc;
4429 SourceManager &SM = PP.getSourceManager();
4430 const LangOptions &LO = PP.getLangOpts();
4432 if (isa<Expr>(stmt))
4433 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4435 switch (stmt->getStmtClass()) {
4436 case Stmt::WhileStmtClass:
4437 scop = extract(cast<WhileStmt>(stmt));
4438 break;
4439 case Stmt::ForStmtClass:
4440 scop = extract_for(cast<ForStmt>(stmt));
4441 break;
4442 case Stmt::IfStmtClass:
4443 scop = extract(cast<IfStmt>(stmt));
4444 break;
4445 case Stmt::CompoundStmtClass:
4446 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
4447 break;
4448 case Stmt::LabelStmtClass:
4449 scop = extract(cast<LabelStmt>(stmt));
4450 break;
4451 case Stmt::ContinueStmtClass:
4452 scop = extract(cast<ContinueStmt>(stmt));
4453 break;
4454 case Stmt::BreakStmtClass:
4455 scop = extract(cast<BreakStmt>(stmt));
4456 break;
4457 case Stmt::DeclStmtClass:
4458 scop = extract(cast<DeclStmt>(stmt));
4459 break;
4460 default:
4461 unsupported(stmt);
4462 return NULL;
4465 if (partial || skip_declarations)
4466 return scop;
4468 loc = stmt->getLocStart();
4469 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
4470 start = getExpansionOffset(SM, loc);
4471 loc = PP.getLocForEndOfToken(stmt->getLocEnd());
4472 end = getExpansionOffset(SM, loc);
4473 scop = pet_scop_update_start_end(scop, start, end);
4475 return scop;
4478 /* Do we need to construct a skip condition of the given type
4479 * on a sequence of statements?
4481 * There is no need to construct a new skip condition if only
4482 * only of the two statements has a skip condition or if both
4483 * of their skip conditions are affine.
4485 * In principle we also don't need a new continuation variable if
4486 * the continuation of scop2 is affine, but then we would need
4487 * to allow more complicated forms of continuations.
4489 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4490 enum pet_skip type)
4492 if (!scop1 || !pet_scop_has_skip(scop1, type))
4493 return false;
4494 if (!scop2 || !pet_scop_has_skip(scop2, type))
4495 return false;
4496 if (pet_scop_has_affine_skip(scop1, type) &&
4497 pet_scop_has_affine_skip(scop2, type))
4498 return false;
4499 return true;
4502 /* Construct a scop for computing the skip condition of the given type and
4503 * with access relation "skip_access" for a sequence of two scops "scop1"
4504 * and "scop2".
4506 * The computed scop contains a single statement that essentially does
4508 * skip_cond = skip_cond_1 ? 1 : skip_cond_2
4510 * or, in other words, skip_cond1 || skip_cond2.
4511 * In this expression, skip_cond_2 is filtered to reflect that it is
4512 * only evaluated when skip_cond_1 is false.
4514 * The skip condition on scop1 is not removed because it still needs
4515 * to be applied to scop2 when these two scops are combined.
4517 static struct pet_scop *extract_skip_seq(PetScan *ps,
4518 __isl_take isl_map *skip_access,
4519 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4521 isl_map *access;
4522 struct pet_expr *expr1, *expr2, *expr, *expr_skip;
4523 struct pet_stmt *stmt;
4524 struct pet_scop *scop;
4525 isl_ctx *ctx = ps->ctx;
4527 if (!scop1 || !scop2)
4528 goto error;
4530 expr1 = pet_scop_get_skip_expr(scop1, type);
4531 expr2 = pet_scop_get_skip_expr(scop2, type);
4532 pet_scop_reset_skip(scop2, type);
4534 expr2 = pet_expr_filter(expr2, isl_map_copy(expr1->acc.access), 0);
4536 expr = universally_true(ctx);
4537 expr = pet_expr_new_ternary(ctx, expr1, expr, expr2);
4538 expr_skip = pet_expr_from_access(isl_map_copy(skip_access));
4539 if (expr_skip) {
4540 expr_skip->acc.write = 1;
4541 expr_skip->acc.read = 0;
4543 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4544 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, ps->n_stmt++, expr);
4546 scop = pet_scop_from_pet_stmt(ctx, stmt);
4547 scop = scop_add_array(scop, skip_access, ps->ast_context);
4548 isl_map_free(skip_access);
4550 return scop;
4551 error:
4552 isl_map_free(skip_access);
4553 return NULL;
4556 /* Structure that handles the construction of skip conditions
4557 * on sequences of statements.
4559 * scop1 and scop2 represent the two statements that are combined
4561 struct pet_skip_info_seq : public pet_skip_info {
4562 struct pet_scop *scop1, *scop2;
4564 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4565 struct pet_scop *scop2);
4566 void extract(PetScan *scan, enum pet_skip type);
4567 void extract(PetScan *scan);
4568 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4569 int offset);
4570 struct pet_scop *add(struct pet_scop *scop, int offset);
4573 /* Initialize a pet_skip_info_seq structure based on
4574 * on the two statements that are going to be combined.
4576 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4577 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
4579 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
4580 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
4581 skip_equals_skip_later(scop2);
4582 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4583 need_skip_seq(scop1, scop2, pet_skip_later);
4586 /* If we need to construct a skip condition of the given type,
4587 * then do so now.
4589 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
4591 if (!skip[type])
4592 return;
4594 access[type] = create_test_access(ctx, scan->n_test++);
4595 scop[type] = extract_skip_seq(scan, isl_map_copy(access[type]),
4596 scop1, scop2, type);
4599 /* Construct the required skip conditions.
4601 void pet_skip_info_seq::extract(PetScan *scan)
4603 extract(scan, pet_skip_now);
4604 extract(scan, pet_skip_later);
4605 if (equal)
4606 drop_skip_later(scop1, scop2);
4609 /* Add the computed skip condition of the given type to "main" and
4610 * add the scop for computing the condition at the given offset (the statement
4611 * number). Within this offset, the condition is computed at position 1
4612 * to ensure that it is computed after the corresponding statement.
4614 * If equal is set, then we only computed a skip condition for pet_skip_now,
4615 * but we also need to set it as main's pet_skip_later.
4617 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
4618 enum pet_skip type, int offset)
4620 isl_set *skip_set;
4622 if (!skip[type])
4623 return main;
4625 skip_set = isl_map_range(access[type]);
4626 access[type] = NULL;
4627 scop[type] = pet_scop_prefix(scop[type], 1);
4628 scop[type] = pet_scop_prefix(scop[type], offset);
4629 main = pet_scop_add_par(ctx, main, scop[type]);
4630 scop[type] = NULL;
4632 if (equal)
4633 main = pet_scop_set_skip(main, pet_skip_later,
4634 isl_set_copy(skip_set));
4636 main = pet_scop_set_skip(main, type, skip_set);
4638 return main;
4641 /* Add the computed skip conditions to "main" and
4642 * add the scops for computing the conditions at the given offset.
4644 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
4646 scop = add(scop, pet_skip_now, offset);
4647 scop = add(scop, pet_skip_later, offset);
4649 return scop;
4652 /* Extract a clone of the kill statement in "scop".
4653 * "scop" is expected to have been created from a DeclStmt
4654 * and should have the kill as its first statement.
4656 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
4658 struct pet_expr *kill;
4659 struct pet_stmt *stmt;
4660 isl_map *access;
4662 if (!scop)
4663 return NULL;
4664 if (scop->n_stmt < 1)
4665 isl_die(ctx, isl_error_internal,
4666 "expecting at least one statement", return NULL);
4667 stmt = scop->stmts[0];
4668 if (stmt->body->type != pet_expr_unary ||
4669 stmt->body->op != pet_op_kill)
4670 isl_die(ctx, isl_error_internal,
4671 "expecting kill statement", return NULL);
4673 access = isl_map_copy(stmt->body->args[0]->acc.access);
4674 access = isl_map_reset_tuple_id(access, isl_dim_in);
4675 kill = pet_expr_kill_from_access(access);
4676 return pet_stmt_from_pet_expr(ctx, stmt->line, NULL, n_stmt++, kill);
4679 /* Mark all arrays in "scop" as being exposed.
4681 static struct pet_scop *mark_exposed(struct pet_scop *scop)
4683 if (!scop)
4684 return NULL;
4685 for (int i = 0; i < scop->n_array; ++i)
4686 scop->arrays[i]->exposed = 1;
4687 return scop;
4690 /* Try and construct a pet_scop corresponding to (part of)
4691 * a sequence of statements.
4693 * "block" is set if the sequence respresents the children of
4694 * a compound statement.
4695 * "skip_declarations" is set if we should skip initial declarations
4696 * in the sequence of statements.
4698 * If there are any breaks or continues in the individual statements,
4699 * then we may have to compute a new skip condition.
4700 * This is handled using a pet_skip_info_seq object.
4701 * On initialization, the object checks if skip conditions need
4702 * to be computed. If so, it does so in "extract" and adds them in "add".
4704 * If "block" is set, then we need to insert kill statements at
4705 * the end of the block for any array that has been declared by
4706 * one of the statements in the sequence. Each of these declarations
4707 * results in the construction of a kill statement at the place
4708 * of the declaration, so we simply collect duplicates of
4709 * those kill statements and append these duplicates to the constructed scop.
4711 * If "block" is not set, then any array declared by one of the statements
4712 * in the sequence is marked as being exposed.
4714 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
4715 bool skip_declarations)
4717 pet_scop *scop;
4718 StmtIterator i;
4719 int j;
4720 bool partial_range = false;
4721 set<struct pet_stmt *> kills;
4722 set<struct pet_stmt *>::iterator it;
4724 scop = pet_scop_empty(ctx);
4725 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4726 Stmt *child = *i;
4727 struct pet_scop *scop_i;
4729 if (skip_declarations &&
4730 child->getStmtClass() == Stmt::DeclStmtClass)
4731 continue;
4733 scop_i = extract(child);
4734 if (scop && partial) {
4735 pet_scop_free(scop_i);
4736 break;
4738 pet_skip_info_seq skip(ctx, scop, scop_i);
4739 skip.extract(this);
4740 if (skip)
4741 scop_i = pet_scop_prefix(scop_i, 0);
4742 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4743 if (block)
4744 kills.insert(extract_kill(scop_i));
4745 else
4746 scop_i = mark_exposed(scop_i);
4748 scop_i = pet_scop_prefix(scop_i, j);
4749 if (options->autodetect) {
4750 if (scop_i)
4751 scop = pet_scop_add_seq(ctx, scop, scop_i);
4752 else
4753 partial_range = true;
4754 if (scop->n_stmt != 0 && !scop_i)
4755 partial = true;
4756 } else {
4757 scop = pet_scop_add_seq(ctx, scop, scop_i);
4760 scop = skip.add(scop, j);
4762 if (partial)
4763 break;
4766 for (it = kills.begin(); it != kills.end(); ++it) {
4767 pet_scop *scop_j;
4768 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4769 scop_j = pet_scop_prefix(scop_j, j);
4770 scop = pet_scop_add_seq(ctx, scop, scop_j);
4773 if (scop && partial_range) {
4774 if (scop->n_stmt == 0) {
4775 pet_scop_free(scop);
4776 return NULL;
4778 partial = true;
4781 return scop;
4784 /* Check if the scop marked by the user is exactly this Stmt
4785 * or part of this Stmt.
4786 * If so, return a pet_scop corresponding to the marked region.
4787 * Otherwise, return NULL.
4789 struct pet_scop *PetScan::scan(Stmt *stmt)
4791 SourceManager &SM = PP.getSourceManager();
4792 unsigned start_off, end_off;
4794 start_off = getExpansionOffset(SM, stmt->getLocStart());
4795 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4797 if (start_off > loc.end)
4798 return NULL;
4799 if (end_off < loc.start)
4800 return NULL;
4801 if (start_off >= loc.start && end_off <= loc.end) {
4802 return extract(stmt);
4805 StmtIterator start;
4806 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4807 Stmt *child = *start;
4808 if (!child)
4809 continue;
4810 start_off = getExpansionOffset(SM, child->getLocStart());
4811 end_off = getExpansionOffset(SM, child->getLocEnd());
4812 if (start_off < loc.start && end_off >= loc.end)
4813 return scan(child);
4814 if (start_off >= loc.start)
4815 break;
4818 StmtIterator end;
4819 for (end = start; end != stmt->child_end(); ++end) {
4820 Stmt *child = *end;
4821 start_off = SM.getFileOffset(child->getLocStart());
4822 if (start_off >= loc.end)
4823 break;
4826 return extract(StmtRange(start, end), false, false);
4829 /* Set the size of index "pos" of "array" to "size".
4830 * In particular, add a constraint of the form
4832 * i_pos < size
4834 * to array->extent and a constraint of the form
4836 * size >= 0
4838 * to array->context.
4840 static struct pet_array *update_size(struct pet_array *array, int pos,
4841 __isl_take isl_pw_aff *size)
4843 isl_set *valid;
4844 isl_set *univ;
4845 isl_set *bound;
4846 isl_space *dim;
4847 isl_aff *aff;
4848 isl_pw_aff *index;
4849 isl_id *id;
4851 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
4852 array->context = isl_set_intersect(array->context, valid);
4854 dim = isl_set_get_space(array->extent);
4855 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
4856 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
4857 univ = isl_set_universe(isl_aff_get_domain_space(aff));
4858 index = isl_pw_aff_alloc(univ, aff);
4860 size = isl_pw_aff_add_dims(size, isl_dim_in,
4861 isl_set_dim(array->extent, isl_dim_set));
4862 id = isl_set_get_tuple_id(array->extent);
4863 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
4864 bound = isl_pw_aff_lt_set(index, size);
4866 array->extent = isl_set_intersect(array->extent, bound);
4868 if (!array->context || !array->extent)
4869 goto error;
4871 return array;
4872 error:
4873 pet_array_free(array);
4874 return NULL;
4877 /* Figure out the size of the array at position "pos" and all
4878 * subsequent positions from "type" and update "array" accordingly.
4880 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
4881 const Type *type, int pos)
4883 const ArrayType *atype;
4884 isl_pw_aff *size;
4886 if (!array)
4887 return NULL;
4889 if (type->isPointerType()) {
4890 type = type->getPointeeType().getTypePtr();
4891 return set_upper_bounds(array, type, pos + 1);
4893 if (!type->isArrayType())
4894 return array;
4896 type = type->getCanonicalTypeInternal().getTypePtr();
4897 atype = cast<ArrayType>(type);
4899 if (type->isConstantArrayType()) {
4900 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
4901 size = extract_affine(ca->getSize());
4902 array = update_size(array, pos, size);
4903 } else if (type->isVariableArrayType()) {
4904 const VariableArrayType *vla = cast<VariableArrayType>(atype);
4905 size = extract_affine(vla->getSizeExpr());
4906 array = update_size(array, pos, size);
4909 type = atype->getElementType().getTypePtr();
4911 return set_upper_bounds(array, type, pos + 1);
4914 /* Is "T" the type of a variable length array with static size?
4916 static bool is_vla_with_static_size(QualType T)
4918 const VariableArrayType *vlatype;
4920 if (!T->isVariableArrayType())
4921 return false;
4922 vlatype = cast<VariableArrayType>(T);
4923 return vlatype->getSizeModifier() == VariableArrayType::Static;
4926 /* Return the type of "decl" as an array.
4928 * In particular, if "decl" is a parameter declaration that
4929 * is a variable length array with a static size, then
4930 * return the original type (i.e., the variable length array).
4931 * Otherwise, return the type of decl.
4933 static QualType get_array_type(ValueDecl *decl)
4935 ParmVarDecl *parm;
4936 QualType T;
4938 parm = dyn_cast<ParmVarDecl>(decl);
4939 if (!parm)
4940 return decl->getType();
4942 T = parm->getOriginalType();
4943 if (!is_vla_with_static_size(T))
4944 return decl->getType();
4945 return T;
4948 /* Construct and return a pet_array corresponding to the variable "decl".
4949 * In particular, initialize array->extent to
4951 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4953 * and then call set_upper_bounds to set the upper bounds on the indices
4954 * based on the type of the variable.
4956 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
4958 struct pet_array *array;
4959 QualType qt = get_array_type(decl);
4960 const Type *type = qt.getTypePtr();
4961 int depth = array_depth(type);
4962 QualType base = base_type(qt);
4963 string name;
4964 isl_id *id;
4965 isl_space *dim;
4967 array = isl_calloc_type(ctx, struct pet_array);
4968 if (!array)
4969 return NULL;
4971 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
4972 dim = isl_space_set_alloc(ctx, 0, depth);
4973 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
4975 array->extent = isl_set_nat_universe(dim);
4977 dim = isl_space_params_alloc(ctx, 0);
4978 array->context = isl_set_universe(dim);
4980 array = set_upper_bounds(array, type, 0);
4981 if (!array)
4982 return NULL;
4984 name = base.getAsString();
4985 array->element_type = strdup(name.c_str());
4986 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
4988 return array;
4991 /* Construct a list of pet_arrays, one for each array (or scalar)
4992 * accessed inside "scop", add this list to "scop" and return the result.
4994 * The context of "scop" is updated with the intersection of
4995 * the contexts of all arrays, i.e., constraints on the parameters
4996 * that ensure that the arrays have a valid (non-negative) size.
4998 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
5000 int i;
5001 set<ValueDecl *> arrays;
5002 set<ValueDecl *>::iterator it;
5003 int n_array;
5004 struct pet_array **scop_arrays;
5006 if (!scop)
5007 return NULL;
5009 pet_scop_collect_arrays(scop, arrays);
5010 if (arrays.size() == 0)
5011 return scop;
5013 n_array = scop->n_array;
5015 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
5016 n_array + arrays.size());
5017 if (!scop_arrays)
5018 goto error;
5019 scop->arrays = scop_arrays;
5021 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
5022 struct pet_array *array;
5023 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
5024 if (!scop->arrays[n_array + i])
5025 goto error;
5026 scop->n_array++;
5027 scop->context = isl_set_intersect(scop->context,
5028 isl_set_copy(array->context));
5029 if (!scop->context)
5030 goto error;
5033 return scop;
5034 error:
5035 pet_scop_free(scop);
5036 return NULL;
5039 /* Bound all parameters in scop->context to the possible values
5040 * of the corresponding C variable.
5042 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
5044 int n;
5046 if (!scop)
5047 return NULL;
5049 n = isl_set_dim(scop->context, isl_dim_param);
5050 for (int i = 0; i < n; ++i) {
5051 isl_id *id;
5052 ValueDecl *decl;
5054 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
5055 if (is_nested_parameter(id)) {
5056 isl_id_free(id);
5057 isl_die(isl_set_get_ctx(scop->context),
5058 isl_error_internal,
5059 "unresolved nested parameter", goto error);
5061 decl = (ValueDecl *) isl_id_get_user(id);
5062 isl_id_free(id);
5064 scop->context = set_parameter_bounds(scop->context, i, decl);
5066 if (!scop->context)
5067 goto error;
5070 return scop;
5071 error:
5072 pet_scop_free(scop);
5073 return NULL;
5076 /* Construct a pet_scop from the given function.
5078 * If the scop was delimited by scop and endscop pragmas, then we override
5079 * the file offsets by those derived from the pragmas.
5081 struct pet_scop *PetScan::scan(FunctionDecl *fd)
5083 pet_scop *scop;
5084 Stmt *stmt;
5086 stmt = fd->getBody();
5088 if (options->autodetect)
5089 scop = extract(stmt, true);
5090 else {
5091 scop = scan(stmt);
5092 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
5094 scop = pet_scop_detect_parameter_accesses(scop);
5095 scop = scan_arrays(scop);
5096 scop = add_parameter_bounds(scop);
5097 scop = pet_scop_gist(scop, value_bounds);
5099 return scop;