pet_check_code.c: add missing include
[pet.git] / scan.cc
blobd548fc5a02a8b888a5ff385a17d806ac265f94a1
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" and store it in "v".
294 int PetScan::extract_int(IntegerLiteral *expr, isl_int *v)
296 const Type *type = expr->getType().getTypePtr();
297 int is_signed = type->hasSignedIntegerRepresentation();
299 if (is_signed) {
300 int64_t i = expr->getValue().getSExtValue();
301 isl_int_set_si(*v, i);
302 } else {
303 uint64_t i = expr->getValue().getZExtValue();
304 isl_int_set_ui(*v, i);
307 return 0;
310 /* Extract an integer from "expr" and store it in "v".
311 * Return -1 if "expr" does not (obviously) represent an integer.
313 int PetScan::extract_int(clang::ParenExpr *expr, isl_int *v)
315 return extract_int(expr->getSubExpr(), v);
318 /* Extract an integer from "expr" and store it in "v".
319 * Return -1 if "expr" does not (obviously) represent an integer.
321 int PetScan::extract_int(clang::Expr *expr, isl_int *v)
323 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
324 return extract_int(cast<IntegerLiteral>(expr), v);
325 if (expr->getStmtClass() == Stmt::ParenExprClass)
326 return extract_int(cast<ParenExpr>(expr), v);
328 unsupported(expr);
329 return -1;
332 /* Extract an affine expression from the IntegerLiteral "expr".
334 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
336 isl_space *dim = isl_space_params_alloc(ctx, 0);
337 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
338 isl_aff *aff = isl_aff_zero_on_domain(ls);
339 isl_set *dom = isl_set_universe(dim);
340 isl_int v;
342 isl_int_init(v);
343 extract_int(expr, &v);
344 aff = isl_aff_add_constant(aff, v);
345 isl_int_clear(v);
347 return isl_pw_aff_alloc(dom, aff);
350 /* Extract an affine expression from the APInt "val".
352 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
354 isl_space *dim = isl_space_params_alloc(ctx, 0);
355 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
356 isl_aff *aff = isl_aff_zero_on_domain(ls);
357 isl_set *dom = isl_set_universe(dim);
358 isl_int v;
360 isl_int_init(v);
361 isl_int_set_ui(v, val.getZExtValue());
362 aff = isl_aff_add_constant(aff, v);
363 isl_int_clear(v);
365 return isl_pw_aff_alloc(dom, aff);
368 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
370 return extract_affine(expr->getSubExpr());
373 static unsigned get_type_size(ValueDecl *decl)
375 return decl->getASTContext().getIntWidth(decl->getType());
378 /* Bound parameter "pos" of "set" to the possible values of "decl".
380 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
381 unsigned pos, ValueDecl *decl)
383 unsigned width;
384 isl_int v;
386 isl_int_init(v);
388 width = get_type_size(decl);
389 if (decl->getType()->isUnsignedIntegerType()) {
390 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
391 isl_int_set_si(v, 1);
392 isl_int_mul_2exp(v, v, width);
393 isl_int_sub_ui(v, v, 1);
394 set = isl_set_upper_bound(set, isl_dim_param, pos, v);
395 } else {
396 isl_int_set_si(v, 1);
397 isl_int_mul_2exp(v, v, width - 1);
398 isl_int_sub_ui(v, v, 1);
399 set = isl_set_upper_bound(set, isl_dim_param, pos, v);
400 isl_int_neg(v, v);
401 isl_int_sub_ui(v, v, 1);
402 set = isl_set_lower_bound(set, isl_dim_param, pos, v);
405 isl_int_clear(v);
407 return set;
410 /* Extract an affine expression from the DeclRefExpr "expr".
412 * If the variable has been assigned a value, then we check whether
413 * we know what (affine) value was assigned.
414 * If so, we return this value. Otherwise we convert "expr"
415 * to an extra parameter (provided nesting_enabled is set).
417 * Otherwise, we simply return an expression that is equal
418 * to a parameter corresponding to the referenced variable.
420 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
422 ValueDecl *decl = expr->getDecl();
423 const Type *type = decl->getType().getTypePtr();
424 isl_id *id;
425 isl_space *dim;
426 isl_aff *aff;
427 isl_set *dom;
429 if (!type->isIntegerType()) {
430 unsupported(expr);
431 return NULL;
434 if (assigned_value.find(decl) != assigned_value.end()) {
435 if (assigned_value[decl])
436 return isl_pw_aff_copy(assigned_value[decl]);
437 else
438 return nested_access(expr);
441 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
442 dim = isl_space_params_alloc(ctx, 1);
444 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
446 dom = isl_set_universe(isl_space_copy(dim));
447 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
448 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
450 return isl_pw_aff_alloc(dom, aff);
453 /* Extract an affine expression from an integer division operation.
454 * In particular, if "expr" is lhs/rhs, then return
456 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
458 * The second argument (rhs) is required to be a (positive) integer constant.
460 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
462 int is_cst;
463 isl_pw_aff *rhs, *lhs;
465 rhs = extract_affine(expr->getRHS());
466 is_cst = isl_pw_aff_is_cst(rhs);
467 if (is_cst < 0 || !is_cst) {
468 isl_pw_aff_free(rhs);
469 if (!is_cst)
470 unsupported(expr);
471 return NULL;
474 lhs = extract_affine(expr->getLHS());
476 return isl_pw_aff_tdiv_q(lhs, rhs);
479 /* Extract an affine expression from a modulo operation.
480 * In particular, if "expr" is lhs/rhs, then return
482 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
484 * The second argument (rhs) is required to be a (positive) integer constant.
486 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
488 int is_cst;
489 isl_pw_aff *rhs, *lhs;
491 rhs = extract_affine(expr->getRHS());
492 is_cst = isl_pw_aff_is_cst(rhs);
493 if (is_cst < 0 || !is_cst) {
494 isl_pw_aff_free(rhs);
495 if (!is_cst)
496 unsupported(expr);
497 return NULL;
500 lhs = extract_affine(expr->getLHS());
502 return isl_pw_aff_tdiv_r(lhs, rhs);
505 /* Extract an affine expression from a multiplication operation.
506 * This is only allowed if at least one of the two arguments
507 * is a (piecewise) constant.
509 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
511 isl_pw_aff *lhs;
512 isl_pw_aff *rhs;
514 lhs = extract_affine(expr->getLHS());
515 rhs = extract_affine(expr->getRHS());
517 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
518 isl_pw_aff_free(lhs);
519 isl_pw_aff_free(rhs);
520 unsupported(expr);
521 return NULL;
524 return isl_pw_aff_mul(lhs, rhs);
527 /* Extract an affine expression from an addition or subtraction operation.
529 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
531 isl_pw_aff *lhs;
532 isl_pw_aff *rhs;
534 lhs = extract_affine(expr->getLHS());
535 rhs = extract_affine(expr->getRHS());
537 switch (expr->getOpcode()) {
538 case BO_Add:
539 return isl_pw_aff_add(lhs, rhs);
540 case BO_Sub:
541 return isl_pw_aff_sub(lhs, rhs);
542 default:
543 isl_pw_aff_free(lhs);
544 isl_pw_aff_free(rhs);
545 return NULL;
550 /* Compute
552 * pwaff mod 2^width
554 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
555 unsigned width)
557 isl_int mod;
559 isl_int_init(mod);
560 isl_int_set_si(mod, 1);
561 isl_int_mul_2exp(mod, mod, width);
563 pwaff = isl_pw_aff_mod(pwaff, mod);
565 isl_int_clear(mod);
567 return pwaff;
570 /* Limit the domain of "pwaff" to those elements where the function
571 * value satisfies
573 * 2^{width-1} <= pwaff < 2^{width-1}
575 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
576 unsigned width)
578 isl_int v;
579 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
580 isl_local_space *ls = isl_local_space_from_space(space);
581 isl_aff *bound;
582 isl_set *dom;
583 isl_pw_aff *b;
585 isl_int_init(v);
586 isl_int_set_si(v, 1);
587 isl_int_mul_2exp(v, v, width - 1);
589 bound = isl_aff_zero_on_domain(ls);
590 bound = isl_aff_add_constant(bound, v);
591 b = isl_pw_aff_from_aff(bound);
593 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
594 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
596 b = isl_pw_aff_neg(b);
597 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
598 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
600 isl_int_clear(v);
602 return pwaff;
605 /* Handle potential overflows on signed computations.
607 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
608 * the we adjust the domain of "pa" to avoid overflows.
610 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
611 unsigned width)
613 if (options->signed_overflow == PET_OVERFLOW_AVOID)
614 pa = avoid_overflow(pa, width);
616 return pa;
619 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
621 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
622 __isl_take isl_set *dom)
624 isl_pw_aff *pa;
625 pa = isl_set_indicator_function(set);
626 pa = isl_pw_aff_intersect_domain(pa, dom);
627 return pa;
630 /* Extract an affine expression from some binary operations.
631 * If the result of the expression is unsigned, then we wrap it
632 * based on the size of the type. Otherwise, we ensure that
633 * no overflow occurs.
635 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
637 isl_pw_aff *res;
638 unsigned width;
640 switch (expr->getOpcode()) {
641 case BO_Add:
642 case BO_Sub:
643 res = extract_affine_add(expr);
644 break;
645 case BO_Div:
646 res = extract_affine_div(expr);
647 break;
648 case BO_Rem:
649 res = extract_affine_mod(expr);
650 break;
651 case BO_Mul:
652 res = extract_affine_mul(expr);
653 break;
654 case BO_LT:
655 case BO_LE:
656 case BO_GT:
657 case BO_GE:
658 case BO_EQ:
659 case BO_NE:
660 case BO_LAnd:
661 case BO_LOr:
662 return extract_condition(expr);
663 default:
664 unsupported(expr);
665 return NULL;
668 width = ast_context.getIntWidth(expr->getType());
669 if (expr->getType()->isUnsignedIntegerType())
670 res = wrap(res, width);
671 else
672 res = signed_overflow(res, width);
674 return res;
677 /* Extract an affine expression from a negation operation.
679 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
681 if (expr->getOpcode() == UO_Minus)
682 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
683 if (expr->getOpcode() == UO_LNot)
684 return extract_condition(expr);
686 unsupported(expr);
687 return NULL;
690 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
692 return extract_affine(expr->getSubExpr());
695 /* Extract an affine expression from some special function calls.
696 * In particular, we handle "min", "max", "ceild" and "floord".
697 * In case of the latter two, the second argument needs to be
698 * a (positive) integer constant.
700 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
702 FunctionDecl *fd;
703 string name;
704 isl_pw_aff *aff1, *aff2;
706 fd = expr->getDirectCallee();
707 if (!fd) {
708 unsupported(expr);
709 return NULL;
712 name = fd->getDeclName().getAsString();
713 if (!(expr->getNumArgs() == 2 && name == "min") &&
714 !(expr->getNumArgs() == 2 && name == "max") &&
715 !(expr->getNumArgs() == 2 && name == "floord") &&
716 !(expr->getNumArgs() == 2 && name == "ceild")) {
717 unsupported(expr);
718 return NULL;
721 if (name == "min" || name == "max") {
722 aff1 = extract_affine(expr->getArg(0));
723 aff2 = extract_affine(expr->getArg(1));
725 if (name == "min")
726 aff1 = isl_pw_aff_min(aff1, aff2);
727 else
728 aff1 = isl_pw_aff_max(aff1, aff2);
729 } else if (name == "floord" || name == "ceild") {
730 isl_int v;
731 Expr *arg2 = expr->getArg(1);
733 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
734 unsupported(expr);
735 return NULL;
737 aff1 = extract_affine(expr->getArg(0));
738 isl_int_init(v);
739 extract_int(cast<IntegerLiteral>(arg2), &v);
740 aff1 = isl_pw_aff_scale_down(aff1, v);
741 isl_int_clear(v);
742 if (name == "floord")
743 aff1 = isl_pw_aff_floor(aff1);
744 else
745 aff1 = isl_pw_aff_ceil(aff1);
746 } else {
747 unsupported(expr);
748 return NULL;
751 return aff1;
754 /* This method is called when we come across an access that is
755 * nested in what is supposed to be an affine expression.
756 * If nesting is allowed, we return a new parameter that corresponds
757 * to this nested access. Otherwise, we simply complain.
759 * Note that we currently don't allow nested accesses themselves
760 * to contain any nested accesses, so we check if we can extract
761 * the access without any nesting and complain if we can't.
763 * The new parameter is resolved in resolve_nested.
765 isl_pw_aff *PetScan::nested_access(Expr *expr)
767 isl_id *id;
768 isl_space *dim;
769 isl_aff *aff;
770 isl_set *dom;
771 isl_map *access;
773 if (!nesting_enabled) {
774 unsupported(expr);
775 return NULL;
778 allow_nested = false;
779 access = extract_access(expr);
780 allow_nested = true;
781 if (!access) {
782 unsupported(expr);
783 return NULL;
785 isl_map_free(access);
787 id = isl_id_alloc(ctx, NULL, expr);
788 dim = isl_space_params_alloc(ctx, 1);
790 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
792 dom = isl_set_universe(isl_space_copy(dim));
793 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
794 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
796 return isl_pw_aff_alloc(dom, aff);
799 /* Affine expressions are not supposed to contain array accesses,
800 * but if nesting is allowed, we return a parameter corresponding
801 * to the array access.
803 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
805 return nested_access(expr);
808 /* Extract an affine expression from a conditional operation.
810 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
812 isl_pw_aff *cond, *lhs, *rhs, *res;
814 cond = extract_condition(expr->getCond());
815 lhs = extract_affine(expr->getTrueExpr());
816 rhs = extract_affine(expr->getFalseExpr());
818 return isl_pw_aff_cond(cond, lhs, rhs);
821 /* Extract an affine expression, if possible, from "expr".
822 * Otherwise return NULL.
824 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
826 switch (expr->getStmtClass()) {
827 case Stmt::ImplicitCastExprClass:
828 return extract_affine(cast<ImplicitCastExpr>(expr));
829 case Stmt::IntegerLiteralClass:
830 return extract_affine(cast<IntegerLiteral>(expr));
831 case Stmt::DeclRefExprClass:
832 return extract_affine(cast<DeclRefExpr>(expr));
833 case Stmt::BinaryOperatorClass:
834 return extract_affine(cast<BinaryOperator>(expr));
835 case Stmt::UnaryOperatorClass:
836 return extract_affine(cast<UnaryOperator>(expr));
837 case Stmt::ParenExprClass:
838 return extract_affine(cast<ParenExpr>(expr));
839 case Stmt::CallExprClass:
840 return extract_affine(cast<CallExpr>(expr));
841 case Stmt::ArraySubscriptExprClass:
842 return extract_affine(cast<ArraySubscriptExpr>(expr));
843 case Stmt::ConditionalOperatorClass:
844 return extract_affine(cast<ConditionalOperator>(expr));
845 default:
846 unsupported(expr);
848 return NULL;
851 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
853 return extract_access(expr->getSubExpr());
856 /* Return the depth of an array of the given type.
858 static int array_depth(const Type *type)
860 if (type->isPointerType())
861 return 1 + array_depth(type->getPointeeType().getTypePtr());
862 if (type->isArrayType()) {
863 const ArrayType *atype;
864 type = type->getCanonicalTypeInternal().getTypePtr();
865 atype = cast<ArrayType>(type);
866 return 1 + array_depth(atype->getElementType().getTypePtr());
868 return 0;
871 /* Return the element type of the given array type.
873 static QualType base_type(QualType qt)
875 const Type *type = qt.getTypePtr();
877 if (type->isPointerType())
878 return base_type(type->getPointeeType());
879 if (type->isArrayType()) {
880 const ArrayType *atype;
881 type = type->getCanonicalTypeInternal().getTypePtr();
882 atype = cast<ArrayType>(type);
883 return base_type(atype->getElementType());
885 return qt;
888 /* Extract an access relation from a reference to a variable.
889 * If the variable has name "A" and its type corresponds to an
890 * array of depth d, then the returned access relation is of the
891 * form
893 * { [] -> A[i_1,...,i_d] }
895 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
897 return extract_access(expr->getDecl());
900 /* Extract an access relation from a variable.
901 * If the variable has name "A" and its type corresponds to an
902 * array of depth d, then the returned access relation is of the
903 * form
905 * { [] -> A[i_1,...,i_d] }
907 __isl_give isl_map *PetScan::extract_access(ValueDecl *decl)
909 int depth = array_depth(decl->getType().getTypePtr());
910 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
911 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
912 isl_map *access_rel;
914 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
916 access_rel = isl_map_universe(dim);
918 return access_rel;
921 /* Extract an access relation from an integer contant.
922 * If the value of the constant is "v", then the returned access relation
923 * is
925 * { [] -> [v] }
927 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
929 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
932 /* Try and extract an access relation from the given Expr.
933 * Return NULL if it doesn't work out.
935 __isl_give isl_map *PetScan::extract_access(Expr *expr)
937 switch (expr->getStmtClass()) {
938 case Stmt::ImplicitCastExprClass:
939 return extract_access(cast<ImplicitCastExpr>(expr));
940 case Stmt::DeclRefExprClass:
941 return extract_access(cast<DeclRefExpr>(expr));
942 case Stmt::ArraySubscriptExprClass:
943 return extract_access(cast<ArraySubscriptExpr>(expr));
944 case Stmt::IntegerLiteralClass:
945 return extract_access(cast<IntegerLiteral>(expr));
946 default:
947 unsupported(expr);
949 return NULL;
952 /* Assign the affine expression "index" to the output dimension "pos" of "map",
953 * restrict the domain to those values that result in a non-negative index
954 * and return the result.
956 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
957 __isl_take isl_pw_aff *index)
959 isl_map *index_map;
960 int len = isl_map_dim(map, isl_dim_out);
961 isl_id *id;
962 isl_set *domain;
964 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
965 index = isl_pw_aff_intersect_domain(index, domain);
966 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
967 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
968 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
969 id = isl_map_get_tuple_id(map, isl_dim_out);
970 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
972 map = isl_map_intersect(map, index_map);
974 return map;
977 /* Extract an access relation from the given array subscript expression.
978 * If nesting is allowed in general, then we turn it on while
979 * examining the index expression.
981 * We first extract an access relation from the base.
982 * This will result in an access relation with a range that corresponds
983 * to the array being accessed and with earlier indices filled in already.
984 * We then extract the current index and fill that in as well.
985 * The position of the current index is based on the type of base.
986 * If base is the actual array variable, then the depth of this type
987 * will be the same as the depth of the array and we will fill in
988 * the first array index.
989 * Otherwise, the depth of the base type will be smaller and we will fill
990 * in a later index.
992 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
994 Expr *base = expr->getBase();
995 Expr *idx = expr->getIdx();
996 isl_pw_aff *index;
997 isl_map *base_access;
998 isl_map *access;
999 int depth = array_depth(base->getType().getTypePtr());
1000 int pos;
1001 bool save_nesting = nesting_enabled;
1003 nesting_enabled = allow_nested;
1005 base_access = extract_access(base);
1006 index = extract_affine(idx);
1008 nesting_enabled = save_nesting;
1010 pos = isl_map_dim(base_access, isl_dim_out) - depth;
1011 access = set_index(base_access, pos, index);
1013 return access;
1016 /* Check if "expr" calls function "minmax" with two arguments and if so
1017 * make lhs and rhs refer to these two arguments.
1019 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1021 CallExpr *call;
1022 FunctionDecl *fd;
1023 string name;
1025 if (expr->getStmtClass() != Stmt::CallExprClass)
1026 return false;
1028 call = cast<CallExpr>(expr);
1029 fd = call->getDirectCallee();
1030 if (!fd)
1031 return false;
1033 if (call->getNumArgs() != 2)
1034 return false;
1036 name = fd->getDeclName().getAsString();
1037 if (name != minmax)
1038 return false;
1040 lhs = call->getArg(0);
1041 rhs = call->getArg(1);
1043 return true;
1046 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1047 * lhs and rhs refer to the two arguments.
1049 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1051 return is_minmax(expr, "min", lhs, rhs);
1054 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1055 * lhs and rhs refer to the two arguments.
1057 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1059 return is_minmax(expr, "max", lhs, rhs);
1062 /* Return "lhs && rhs", defined on the shared definition domain.
1064 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1065 __isl_take isl_pw_aff *rhs)
1067 isl_set *cond;
1068 isl_set *dom;
1070 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1071 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1072 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1073 isl_pw_aff_non_zero_set(rhs));
1074 return indicator_function(cond, dom);
1077 /* Return "lhs && rhs", with shortcut semantics.
1078 * That is, if lhs is false, then the result is defined even if rhs is not.
1079 * In practice, we compute lhs ? rhs : lhs.
1081 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1082 __isl_take isl_pw_aff *rhs)
1084 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1087 /* Return "lhs || rhs", with shortcut semantics.
1088 * That is, if lhs is true, then the result is defined even if rhs is not.
1089 * In practice, we compute lhs ? lhs : rhs.
1091 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1092 __isl_take isl_pw_aff *rhs)
1094 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1097 /* Extract an affine expressions representing the comparison "LHS op RHS"
1098 * "comp" is the original statement that "LHS op RHS" is derived from
1099 * and is used for diagnostics.
1101 * If the comparison is of the form
1103 * a <= min(b,c)
1105 * then the expression is constructed as the conjunction of
1106 * the comparisons
1108 * a <= b and a <= c
1110 * A similar optimization is performed for max(a,b) <= c.
1111 * We do this because that will lead to simpler representations
1112 * of the expression.
1113 * If isl is ever enhanced to explicitly deal with min and max expressions,
1114 * this optimization can be removed.
1116 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1117 Expr *LHS, Expr *RHS, Stmt *comp)
1119 isl_pw_aff *lhs;
1120 isl_pw_aff *rhs;
1121 isl_pw_aff *res;
1122 isl_set *cond;
1123 isl_set *dom;
1125 if (op == BO_GT)
1126 return extract_comparison(BO_LT, RHS, LHS, comp);
1127 if (op == BO_GE)
1128 return extract_comparison(BO_LE, RHS, LHS, comp);
1130 if (op == BO_LT || op == BO_LE) {
1131 Expr *expr1, *expr2;
1132 if (is_min(RHS, expr1, expr2)) {
1133 lhs = extract_comparison(op, LHS, expr1, comp);
1134 rhs = extract_comparison(op, LHS, expr2, comp);
1135 return pw_aff_and(lhs, rhs);
1137 if (is_max(LHS, expr1, expr2)) {
1138 lhs = extract_comparison(op, expr1, RHS, comp);
1139 rhs = extract_comparison(op, expr2, RHS, comp);
1140 return pw_aff_and(lhs, rhs);
1144 lhs = extract_affine(LHS);
1145 rhs = extract_affine(RHS);
1147 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1148 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1150 switch (op) {
1151 case BO_LT:
1152 cond = isl_pw_aff_lt_set(lhs, rhs);
1153 break;
1154 case BO_LE:
1155 cond = isl_pw_aff_le_set(lhs, rhs);
1156 break;
1157 case BO_EQ:
1158 cond = isl_pw_aff_eq_set(lhs, rhs);
1159 break;
1160 case BO_NE:
1161 cond = isl_pw_aff_ne_set(lhs, rhs);
1162 break;
1163 default:
1164 isl_pw_aff_free(lhs);
1165 isl_pw_aff_free(rhs);
1166 isl_set_free(dom);
1167 unsupported(comp);
1168 return NULL;
1171 cond = isl_set_coalesce(cond);
1172 res = indicator_function(cond, dom);
1174 return res;
1177 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1179 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1180 comp->getRHS(), comp);
1183 /* Extract an affine expression representing the negation (logical not)
1184 * of a subexpression.
1186 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1188 isl_set *set_cond, *dom;
1189 isl_pw_aff *cond, *res;
1191 cond = extract_condition(op->getSubExpr());
1193 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1195 set_cond = isl_pw_aff_zero_set(cond);
1197 res = indicator_function(set_cond, dom);
1199 return res;
1202 /* Extract an affine expression representing the disjunction (logical or)
1203 * or conjunction (logical and) of two subexpressions.
1205 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1207 isl_pw_aff *lhs, *rhs;
1209 lhs = extract_condition(comp->getLHS());
1210 rhs = extract_condition(comp->getRHS());
1212 switch (comp->getOpcode()) {
1213 case BO_LAnd:
1214 return pw_aff_and_then(lhs, rhs);
1215 case BO_LOr:
1216 return pw_aff_or_else(lhs, rhs);
1217 default:
1218 isl_pw_aff_free(lhs);
1219 isl_pw_aff_free(rhs);
1222 unsupported(comp);
1223 return NULL;
1226 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1228 switch (expr->getOpcode()) {
1229 case UO_LNot:
1230 return extract_boolean(expr);
1231 default:
1232 unsupported(expr);
1233 return NULL;
1237 /* Extract the affine expression "expr != 0 ? 1 : 0".
1239 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1241 isl_pw_aff *res;
1242 isl_set *set, *dom;
1244 res = extract_affine(expr);
1246 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1247 set = isl_pw_aff_non_zero_set(res);
1249 res = indicator_function(set, dom);
1251 return res;
1254 /* Extract an affine expression from a boolean expression.
1255 * In particular, return the expression "expr ? 1 : 0".
1257 * If the expression doesn't look like a condition, we assume it
1258 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1260 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1262 BinaryOperator *comp;
1264 if (!expr) {
1265 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1266 return indicator_function(u, isl_set_copy(u));
1269 if (expr->getStmtClass() == Stmt::ParenExprClass)
1270 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1272 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1273 return extract_condition(cast<UnaryOperator>(expr));
1275 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1276 return extract_implicit_condition(expr);
1278 comp = cast<BinaryOperator>(expr);
1279 switch (comp->getOpcode()) {
1280 case BO_LT:
1281 case BO_LE:
1282 case BO_GT:
1283 case BO_GE:
1284 case BO_EQ:
1285 case BO_NE:
1286 return extract_comparison(comp);
1287 case BO_LAnd:
1288 case BO_LOr:
1289 return extract_boolean(comp);
1290 default:
1291 return extract_implicit_condition(expr);
1295 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1297 switch (kind) {
1298 case UO_Minus:
1299 return pet_op_minus;
1300 case UO_PostInc:
1301 return pet_op_post_inc;
1302 case UO_PostDec:
1303 return pet_op_post_dec;
1304 case UO_PreInc:
1305 return pet_op_pre_inc;
1306 case UO_PreDec:
1307 return pet_op_pre_dec;
1308 default:
1309 return pet_op_last;
1313 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1315 switch (kind) {
1316 case BO_AddAssign:
1317 return pet_op_add_assign;
1318 case BO_SubAssign:
1319 return pet_op_sub_assign;
1320 case BO_MulAssign:
1321 return pet_op_mul_assign;
1322 case BO_DivAssign:
1323 return pet_op_div_assign;
1324 case BO_Assign:
1325 return pet_op_assign;
1326 case BO_Add:
1327 return pet_op_add;
1328 case BO_Sub:
1329 return pet_op_sub;
1330 case BO_Mul:
1331 return pet_op_mul;
1332 case BO_Div:
1333 return pet_op_div;
1334 case BO_Rem:
1335 return pet_op_mod;
1336 case BO_EQ:
1337 return pet_op_eq;
1338 case BO_LE:
1339 return pet_op_le;
1340 case BO_LT:
1341 return pet_op_lt;
1342 case BO_GT:
1343 return pet_op_gt;
1344 default:
1345 return pet_op_last;
1349 /* Construct a pet_expr representing a unary operator expression.
1351 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1353 struct pet_expr *arg;
1354 enum pet_op_type op;
1356 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1357 if (op == pet_op_last) {
1358 unsupported(expr);
1359 return NULL;
1362 arg = extract_expr(expr->getSubExpr());
1364 if (expr->isIncrementDecrementOp() &&
1365 arg && arg->type == pet_expr_access) {
1366 mark_write(arg);
1367 arg->acc.read = 1;
1370 return pet_expr_new_unary(ctx, op, arg);
1373 /* Mark the given access pet_expr as a write.
1374 * If a scalar is being accessed, then mark its value
1375 * as unknown in assigned_value.
1377 void PetScan::mark_write(struct pet_expr *access)
1379 isl_id *id;
1380 ValueDecl *decl;
1382 if (!access)
1383 return;
1385 access->acc.write = 1;
1386 access->acc.read = 0;
1388 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1389 return;
1391 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1392 decl = (ValueDecl *) isl_id_get_user(id);
1393 clear_assignment(assigned_value, decl);
1394 isl_id_free(id);
1397 /* Assign "rhs" to "lhs".
1399 * In particular, if "lhs" is a scalar variable, then mark
1400 * the variable as having been assigned. If, furthermore, "rhs"
1401 * is an affine expression, then keep track of this value in assigned_value
1402 * so that we can plug it in when we later come across the same variable.
1404 void PetScan::assign(struct pet_expr *lhs, Expr *rhs)
1406 isl_id *id;
1407 ValueDecl *decl;
1408 isl_pw_aff *pa;
1410 if (!lhs)
1411 return;
1412 if (lhs->type != pet_expr_access)
1413 return;
1414 if (isl_map_dim(lhs->acc.access, isl_dim_out) != 0)
1415 return;
1417 id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1418 decl = (ValueDecl *) isl_id_get_user(id);
1419 isl_id_free(id);
1421 pa = try_extract_affine(rhs);
1422 clear_assignment(assigned_value, decl);
1423 if (!pa)
1424 return;
1425 assigned_value[decl] = pa;
1426 insert_expression(pa);
1429 /* Construct a pet_expr representing a binary operator expression.
1431 * If the top level operator is an assignment and the LHS is an access,
1432 * then we mark that access as a write. If the operator is a compound
1433 * assignment, the access is marked as both a read and a write.
1435 * If "expr" assigns something to a scalar variable, then we mark
1436 * the variable as having been assigned. If, furthermore, the expression
1437 * is affine, then keep track of this value in assigned_value
1438 * so that we can plug it in when we later come across the same variable.
1440 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1442 struct pet_expr *lhs, *rhs;
1443 enum pet_op_type op;
1445 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1446 if (op == pet_op_last) {
1447 unsupported(expr);
1448 return NULL;
1451 lhs = extract_expr(expr->getLHS());
1452 rhs = extract_expr(expr->getRHS());
1454 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1455 mark_write(lhs);
1456 if (expr->isCompoundAssignmentOp())
1457 lhs->acc.read = 1;
1460 if (expr->getOpcode() == BO_Assign)
1461 assign(lhs, expr->getRHS());
1463 return pet_expr_new_binary(ctx, op, lhs, rhs);
1466 /* Construct a pet_scop with a single statement killing the entire
1467 * array "array".
1469 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1471 isl_map *access;
1472 struct pet_expr *expr;
1474 if (!array)
1475 return NULL;
1476 access = isl_map_from_range(isl_set_copy(array->extent));
1477 expr = pet_expr_kill_from_access(access);
1478 return extract(stmt, expr);
1481 /* Construct a pet_scop for a (single) variable declaration.
1483 * The scop contains the variable being declared (as an array)
1484 * and a statement killing the array.
1486 * If the variable is initialized in the AST, then the scop
1487 * also contains an assignment to the variable.
1489 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1491 Decl *decl;
1492 VarDecl *vd;
1493 struct pet_expr *lhs, *rhs, *pe;
1494 struct pet_scop *scop_decl, *scop;
1495 struct pet_array *array;
1497 if (!stmt->isSingleDecl()) {
1498 unsupported(stmt);
1499 return NULL;
1502 decl = stmt->getSingleDecl();
1503 vd = cast<VarDecl>(decl);
1505 array = extract_array(ctx, vd);
1506 if (array)
1507 array->declared = 1;
1508 scop_decl = kill(stmt, array);
1509 scop_decl = pet_scop_add_array(scop_decl, array);
1511 if (!vd->getInit())
1512 return scop_decl;
1514 lhs = pet_expr_from_access(extract_access(vd));
1515 rhs = extract_expr(vd->getInit());
1517 mark_write(lhs);
1518 assign(lhs, vd->getInit());
1520 pe = pet_expr_new_binary(ctx, pet_op_assign, lhs, rhs);
1521 scop = extract(stmt, pe);
1523 scop_decl = pet_scop_prefix(scop_decl, 0);
1524 scop = pet_scop_prefix(scop, 1);
1526 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1528 return scop;
1531 /* Construct a pet_expr representing a conditional operation.
1533 * We first try to extract the condition as an affine expression.
1534 * If that fails, we construct a pet_expr tree representing the condition.
1536 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1538 struct pet_expr *cond, *lhs, *rhs;
1539 isl_pw_aff *pa;
1541 pa = try_extract_affine(expr->getCond());
1542 if (pa) {
1543 isl_set *test = isl_set_from_pw_aff(pa);
1544 cond = pet_expr_from_access(isl_map_from_range(test));
1545 } else
1546 cond = extract_expr(expr->getCond());
1547 lhs = extract_expr(expr->getTrueExpr());
1548 rhs = extract_expr(expr->getFalseExpr());
1550 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1553 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1555 return extract_expr(expr->getSubExpr());
1558 /* Construct a pet_expr representing a floating point value.
1560 * If the floating point literal does not appear in a macro,
1561 * then we use the original representation in the source code
1562 * as the string representation. Otherwise, we use the pretty
1563 * printer to produce a string representation.
1565 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1567 double d;
1568 string s;
1569 const LangOptions &LO = PP.getLangOpts();
1570 SourceLocation loc = expr->getLocation();
1572 if (!loc.isMacroID()) {
1573 SourceManager &SM = PP.getSourceManager();
1574 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1575 s = string(SM.getCharacterData(loc), len);
1576 } else {
1577 llvm::raw_string_ostream S(s);
1578 expr->printPretty(S, 0, PrintingPolicy(LO));
1579 S.str();
1581 d = expr->getValueAsApproximateDouble();
1582 return pet_expr_new_double(ctx, d, s.c_str());
1585 /* Extract an access relation from "expr" and then convert it into
1586 * a pet_expr.
1588 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1590 isl_map *access;
1591 struct pet_expr *pe;
1593 access = extract_access(expr);
1595 pe = pet_expr_from_access(access);
1597 return pe;
1600 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1602 return extract_expr(expr->getSubExpr());
1605 /* Construct a pet_expr representing a function call.
1607 * If we are passing along a pointer to an array element
1608 * or an entire row or even higher dimensional slice of an array,
1609 * then the function being called may write into the array.
1611 * We assume here that if the function is declared to take a pointer
1612 * to a const type, then the function will perform a read
1613 * and that otherwise, it will perform a write.
1615 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1617 struct pet_expr *res = NULL;
1618 FunctionDecl *fd;
1619 string name;
1621 fd = expr->getDirectCallee();
1622 if (!fd) {
1623 unsupported(expr);
1624 return NULL;
1627 name = fd->getDeclName().getAsString();
1628 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1629 if (!res)
1630 return NULL;
1632 for (int i = 0; i < expr->getNumArgs(); ++i) {
1633 Expr *arg = expr->getArg(i);
1634 int is_addr = 0;
1635 pet_expr *main_arg;
1637 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1638 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1639 arg = ice->getSubExpr();
1641 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1642 UnaryOperator *op = cast<UnaryOperator>(arg);
1643 if (op->getOpcode() == UO_AddrOf) {
1644 is_addr = 1;
1645 arg = op->getSubExpr();
1648 res->args[i] = PetScan::extract_expr(arg);
1649 main_arg = res->args[i];
1650 if (is_addr)
1651 res->args[i] = pet_expr_new_unary(ctx,
1652 pet_op_address_of, res->args[i]);
1653 if (!res->args[i])
1654 goto error;
1655 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1656 array_depth(arg->getType().getTypePtr()) > 0)
1657 is_addr = 1;
1658 if (is_addr && main_arg->type == pet_expr_access) {
1659 ParmVarDecl *parm;
1660 if (!fd->hasPrototype()) {
1661 unsupported(expr, "prototype required");
1662 goto error;
1664 parm = fd->getParamDecl(i);
1665 if (!const_base(parm->getType()))
1666 mark_write(main_arg);
1670 return res;
1671 error:
1672 pet_expr_free(res);
1673 return NULL;
1676 /* Construct a pet_expr representing a (C style) cast.
1678 struct pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1680 struct pet_expr *arg;
1681 QualType type;
1683 arg = extract_expr(expr->getSubExpr());
1684 if (!arg)
1685 return NULL;
1687 type = expr->getTypeAsWritten();
1688 return pet_expr_new_cast(ctx, type.getAsString().c_str(), arg);
1691 /* Try and onstruct a pet_expr representing "expr".
1693 struct pet_expr *PetScan::extract_expr(Expr *expr)
1695 switch (expr->getStmtClass()) {
1696 case Stmt::UnaryOperatorClass:
1697 return extract_expr(cast<UnaryOperator>(expr));
1698 case Stmt::CompoundAssignOperatorClass:
1699 case Stmt::BinaryOperatorClass:
1700 return extract_expr(cast<BinaryOperator>(expr));
1701 case Stmt::ImplicitCastExprClass:
1702 return extract_expr(cast<ImplicitCastExpr>(expr));
1703 case Stmt::ArraySubscriptExprClass:
1704 case Stmt::DeclRefExprClass:
1705 case Stmt::IntegerLiteralClass:
1706 return extract_access_expr(expr);
1707 case Stmt::FloatingLiteralClass:
1708 return extract_expr(cast<FloatingLiteral>(expr));
1709 case Stmt::ParenExprClass:
1710 return extract_expr(cast<ParenExpr>(expr));
1711 case Stmt::ConditionalOperatorClass:
1712 return extract_expr(cast<ConditionalOperator>(expr));
1713 case Stmt::CallExprClass:
1714 return extract_expr(cast<CallExpr>(expr));
1715 case Stmt::CStyleCastExprClass:
1716 return extract_expr(cast<CStyleCastExpr>(expr));
1717 default:
1718 unsupported(expr);
1720 return NULL;
1723 /* Check if the given initialization statement is an assignment.
1724 * If so, return that assignment. Otherwise return NULL.
1726 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1728 BinaryOperator *ass;
1730 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1731 return NULL;
1733 ass = cast<BinaryOperator>(init);
1734 if (ass->getOpcode() != BO_Assign)
1735 return NULL;
1737 return ass;
1740 /* Check if the given initialization statement is a declaration
1741 * of a single variable.
1742 * If so, return that declaration. Otherwise return NULL.
1744 Decl *PetScan::initialization_declaration(Stmt *init)
1746 DeclStmt *decl;
1748 if (init->getStmtClass() != Stmt::DeclStmtClass)
1749 return NULL;
1751 decl = cast<DeclStmt>(init);
1753 if (!decl->isSingleDecl())
1754 return NULL;
1756 return decl->getSingleDecl();
1759 /* Given the assignment operator in the initialization of a for loop,
1760 * extract the induction variable, i.e., the (integer)variable being
1761 * assigned.
1763 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1765 Expr *lhs;
1766 DeclRefExpr *ref;
1767 ValueDecl *decl;
1768 const Type *type;
1770 lhs = init->getLHS();
1771 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1772 unsupported(init);
1773 return NULL;
1776 ref = cast<DeclRefExpr>(lhs);
1777 decl = ref->getDecl();
1778 type = decl->getType().getTypePtr();
1780 if (!type->isIntegerType()) {
1781 unsupported(lhs);
1782 return NULL;
1785 return decl;
1788 /* Given the initialization statement of a for loop and the single
1789 * declaration in this initialization statement,
1790 * extract the induction variable, i.e., the (integer) variable being
1791 * declared.
1793 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1795 VarDecl *vd;
1797 vd = cast<VarDecl>(decl);
1799 const QualType type = vd->getType();
1800 if (!type->isIntegerType()) {
1801 unsupported(init);
1802 return NULL;
1805 if (!vd->getInit()) {
1806 unsupported(init);
1807 return NULL;
1810 return vd;
1813 /* Check that op is of the form iv++ or iv--.
1814 * Return an affine expression "1" or "-1" accordingly.
1816 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
1817 clang::UnaryOperator *op, clang::ValueDecl *iv)
1819 Expr *sub;
1820 DeclRefExpr *ref;
1821 isl_space *space;
1822 isl_aff *aff;
1824 if (!op->isIncrementDecrementOp()) {
1825 unsupported(op);
1826 return NULL;
1829 sub = op->getSubExpr();
1830 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1831 unsupported(op);
1832 return NULL;
1835 ref = cast<DeclRefExpr>(sub);
1836 if (ref->getDecl() != iv) {
1837 unsupported(op);
1838 return NULL;
1841 space = isl_space_params_alloc(ctx, 0);
1842 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1844 if (op->isIncrementOp())
1845 aff = isl_aff_add_constant_si(aff, 1);
1846 else
1847 aff = isl_aff_add_constant_si(aff, -1);
1849 return isl_pw_aff_from_aff(aff);
1852 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1853 * has a single constant expression, then put this constant in *user.
1854 * The caller is assumed to have checked that this function will
1855 * be called exactly once.
1857 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1858 void *user)
1860 isl_int *inc = (isl_int *)user;
1861 int res = 0;
1863 if (isl_aff_is_cst(aff))
1864 isl_aff_get_constant(aff, inc);
1865 else
1866 res = -1;
1868 isl_set_free(set);
1869 isl_aff_free(aff);
1871 return res;
1874 /* Check if op is of the form
1876 * iv = iv + inc
1878 * and return inc as an affine expression.
1880 * We extract an affine expression from the RHS, subtract iv and return
1881 * the result.
1883 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
1884 clang::ValueDecl *iv)
1886 Expr *lhs;
1887 DeclRefExpr *ref;
1888 isl_id *id;
1889 isl_space *dim;
1890 isl_aff *aff;
1891 isl_pw_aff *val;
1893 if (op->getOpcode() != BO_Assign) {
1894 unsupported(op);
1895 return NULL;
1898 lhs = op->getLHS();
1899 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1900 unsupported(op);
1901 return NULL;
1904 ref = cast<DeclRefExpr>(lhs);
1905 if (ref->getDecl() != iv) {
1906 unsupported(op);
1907 return NULL;
1910 val = extract_affine(op->getRHS());
1912 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1914 dim = isl_space_params_alloc(ctx, 1);
1915 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1916 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1917 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1919 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1921 return val;
1924 /* Check that op is of the form iv += cst or iv -= cst
1925 * and return an affine expression corresponding oto cst or -cst accordingly.
1927 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
1928 CompoundAssignOperator *op, clang::ValueDecl *iv)
1930 Expr *lhs;
1931 DeclRefExpr *ref;
1932 bool neg = false;
1933 isl_pw_aff *val;
1934 BinaryOperatorKind opcode;
1936 opcode = op->getOpcode();
1937 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1938 unsupported(op);
1939 return NULL;
1941 if (opcode == BO_SubAssign)
1942 neg = true;
1944 lhs = op->getLHS();
1945 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1946 unsupported(op);
1947 return NULL;
1950 ref = cast<DeclRefExpr>(lhs);
1951 if (ref->getDecl() != iv) {
1952 unsupported(op);
1953 return NULL;
1956 val = extract_affine(op->getRHS());
1957 if (neg)
1958 val = isl_pw_aff_neg(val);
1960 return val;
1963 /* Check that the increment of the given for loop increments
1964 * (or decrements) the induction variable "iv" and return
1965 * the increment as an affine expression if successful.
1967 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
1968 ValueDecl *iv)
1970 Stmt *inc = stmt->getInc();
1972 if (!inc) {
1973 unsupported(stmt);
1974 return NULL;
1977 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1978 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
1979 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1980 return extract_compound_increment(
1981 cast<CompoundAssignOperator>(inc), iv);
1982 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1983 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
1985 unsupported(inc);
1986 return NULL;
1989 /* Embed the given iteration domain in an extra outer loop
1990 * with induction variable "var".
1991 * If this variable appeared as a parameter in the constraints,
1992 * it is replaced by the new outermost dimension.
1994 static __isl_give isl_set *embed(__isl_take isl_set *set,
1995 __isl_take isl_id *var)
1997 int pos;
1999 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
2000 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
2001 if (pos >= 0) {
2002 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
2003 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2006 isl_id_free(var);
2007 return set;
2010 /* Return those elements in the space of "cond" that come after
2011 * (based on "sign") an element in "cond".
2013 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
2015 isl_map *previous_to_this;
2017 if (sign > 0)
2018 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
2019 else
2020 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
2022 cond = isl_set_apply(cond, previous_to_this);
2024 return cond;
2027 /* Create the infinite iteration domain
2029 * { [id] : id >= 0 }
2031 * If "scop" has an affine skip of type pet_skip_later,
2032 * then remove those iterations i that have an earlier iteration
2033 * where the skip condition is satisfied, meaning that iteration i
2034 * is not executed.
2035 * Since we are dealing with a loop without loop iterator,
2036 * the skip condition cannot refer to the current loop iterator and
2037 * so effectively, the returned set is of the form
2039 * { [0]; [id] : id >= 1 and not skip }
2041 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
2042 struct pet_scop *scop)
2044 isl_ctx *ctx = isl_id_get_ctx(id);
2045 isl_set *domain;
2046 isl_set *skip;
2048 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
2049 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
2051 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
2052 return domain;
2054 skip = pet_scop_get_skip(scop, pet_skip_later);
2055 skip = isl_set_fix_si(skip, isl_dim_set, 0, 1);
2056 skip = isl_set_params(skip);
2057 skip = embed(skip, isl_id_copy(id));
2058 skip = isl_set_intersect(skip , isl_set_copy(domain));
2059 domain = isl_set_subtract(domain, after(skip, 1));
2061 return domain;
2064 /* Create an identity mapping on the space containing "domain".
2066 static __isl_give isl_map *identity_map(__isl_keep isl_set *domain)
2068 isl_space *space;
2069 isl_map *id;
2071 space = isl_space_map_from_set(isl_set_get_space(domain));
2072 id = isl_map_identity(space);
2074 return id;
2077 /* Add a filter to "scop" that imposes that it is only executed
2078 * when "break_access" has a zero value for all previous iterations
2079 * of "domain".
2081 * The input "break_access" has a zero-dimensional domain and range.
2083 static struct pet_scop *scop_add_break(struct pet_scop *scop,
2084 __isl_take isl_map *break_access, __isl_take isl_set *domain, int sign)
2086 isl_ctx *ctx = isl_set_get_ctx(domain);
2087 isl_id *id_test;
2088 isl_map *prev;
2090 id_test = isl_map_get_tuple_id(break_access, isl_dim_out);
2091 break_access = isl_map_add_dims(break_access, isl_dim_in, 1);
2092 break_access = isl_map_add_dims(break_access, isl_dim_out, 1);
2093 break_access = isl_map_intersect_range(break_access, domain);
2094 break_access = isl_map_set_tuple_id(break_access, isl_dim_out, id_test);
2095 if (sign > 0)
2096 prev = isl_map_lex_gt_first(isl_map_get_space(break_access), 1);
2097 else
2098 prev = isl_map_lex_lt_first(isl_map_get_space(break_access), 1);
2099 break_access = isl_map_intersect(break_access, prev);
2100 scop = pet_scop_filter(scop, break_access, 0);
2101 scop = pet_scop_merge_filters(scop);
2103 return scop;
2106 /* Construct a pet_scop for an infinite loop around the given body.
2108 * We extract a pet_scop for the body and then embed it in a loop with
2109 * iteration domain
2111 * { [t] : t >= 0 }
2113 * and schedule
2115 * { [t] -> [t] }
2117 * If the body contains any break, then it is taken into
2118 * account in infinite_domain (if the skip condition is affine)
2119 * or in scop_add_break (if the skip condition is not affine).
2121 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2123 isl_id *id;
2124 isl_set *domain;
2125 isl_map *ident;
2126 isl_map *access;
2127 struct pet_scop *scop;
2128 bool has_var_break;
2130 scop = extract(body);
2131 if (!scop)
2132 return NULL;
2134 id = isl_id_alloc(ctx, "t", NULL);
2135 domain = infinite_domain(isl_id_copy(id), scop);
2136 ident = identity_map(domain);
2138 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2139 if (has_var_break)
2140 access = pet_scop_get_skip_map(scop, pet_skip_later);
2142 scop = pet_scop_embed(scop, isl_set_copy(domain),
2143 isl_map_copy(ident), ident, id);
2144 if (has_var_break)
2145 scop = scop_add_break(scop, access, domain, 1);
2146 else
2147 isl_set_free(domain);
2149 return scop;
2152 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2154 * for (;;)
2155 * body
2158 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2160 return extract_infinite_loop(stmt->getBody());
2163 /* Create an access to a virtual array representing the result
2164 * of a condition.
2165 * Unlike other accessed data, the id of the array is NULL as
2166 * there is no ValueDecl in the program corresponding to the virtual
2167 * array.
2168 * The array starts out as a scalar, but grows along with the
2169 * statement writing to the array in pet_scop_embed.
2171 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2173 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2174 isl_id *id;
2175 char name[50];
2177 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2178 id = isl_id_alloc(ctx, name, NULL);
2179 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2180 return isl_map_universe(dim);
2183 /* Add an array with the given extent ("access") to the list
2184 * of arrays in "scop" and return the extended pet_scop.
2185 * The array is marked as attaining values 0 and 1 only and
2186 * as each element being assigned at most once.
2188 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2189 __isl_keep isl_map *access, clang::ASTContext &ast_ctx)
2191 isl_ctx *ctx = isl_map_get_ctx(access);
2192 isl_space *dim;
2193 struct pet_array *array;
2195 if (!scop)
2196 return NULL;
2197 if (!ctx)
2198 goto error;
2200 array = isl_calloc_type(ctx, struct pet_array);
2201 if (!array)
2202 goto error;
2204 array->extent = isl_map_range(isl_map_copy(access));
2205 dim = isl_space_params_alloc(ctx, 0);
2206 array->context = isl_set_universe(dim);
2207 dim = isl_space_set_alloc(ctx, 0, 1);
2208 array->value_bounds = isl_set_universe(dim);
2209 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2210 isl_dim_set, 0, 0);
2211 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2212 isl_dim_set, 0, 1);
2213 array->element_type = strdup("int");
2214 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2215 array->uniquely_defined = 1;
2217 if (!array->extent || !array->context)
2218 array = pet_array_free(array);
2220 scop = pet_scop_add_array(scop, array);
2222 return scop;
2223 error:
2224 pet_scop_free(scop);
2225 return NULL;
2228 /* Construct a pet_scop for a while loop of the form
2230 * while (pa)
2231 * body
2233 * In particular, construct a scop for an infinite loop around body and
2234 * intersect the domain with the affine expression.
2235 * Note that this intersection may result in an empty loop.
2237 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2238 Stmt *body)
2240 struct pet_scop *scop;
2241 isl_set *dom;
2242 isl_set *valid;
2244 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2245 dom = isl_pw_aff_non_zero_set(pa);
2246 scop = extract_infinite_loop(body);
2247 scop = pet_scop_restrict(scop, dom);
2248 scop = pet_scop_restrict_context(scop, valid);
2250 return scop;
2253 /* Construct a scop for a while, given the scops for the condition
2254 * and the body, the filter access and the iteration domain of
2255 * the while loop.
2257 * In particular, the scop for the condition is filtered to depend
2258 * on "test_access" evaluating to true for all previous iterations
2259 * of the loop, while the scop for the body is filtered to depend
2260 * on "test_access" evaluating to true for all iterations up to the
2261 * current iteration.
2263 * These filtered scops are then combined into a single scop.
2265 * "sign" is positive if the iterator increases and negative
2266 * if it decreases.
2268 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2269 struct pet_scop *scop_body, __isl_take isl_map *test_access,
2270 __isl_take isl_set *domain, int sign)
2272 isl_ctx *ctx = isl_set_get_ctx(domain);
2273 isl_id *id_test;
2274 isl_map *prev;
2276 id_test = isl_map_get_tuple_id(test_access, isl_dim_out);
2277 test_access = isl_map_add_dims(test_access, isl_dim_in, 1);
2278 test_access = isl_map_add_dims(test_access, isl_dim_out, 1);
2279 test_access = isl_map_intersect_range(test_access, domain);
2280 test_access = isl_map_set_tuple_id(test_access, isl_dim_out, id_test);
2281 if (sign > 0)
2282 prev = isl_map_lex_ge_first(isl_map_get_space(test_access), 1);
2283 else
2284 prev = isl_map_lex_le_first(isl_map_get_space(test_access), 1);
2285 test_access = isl_map_intersect(test_access, prev);
2286 scop_body = pet_scop_filter(scop_body, isl_map_copy(test_access), 1);
2287 if (sign > 0)
2288 prev = isl_map_lex_gt_first(isl_map_get_space(test_access), 1);
2289 else
2290 prev = isl_map_lex_lt_first(isl_map_get_space(test_access), 1);
2291 test_access = isl_map_intersect(test_access, prev);
2292 scop_cond = pet_scop_filter(scop_cond, test_access, 1);
2294 return pet_scop_add_seq(ctx, scop_cond, scop_body);
2297 /* Check if the while loop is of the form
2299 * while (affine expression)
2300 * body
2302 * If so, call extract_affine_while to construct a scop.
2304 * Otherwise, construct a generic while scop, with iteration domain
2305 * { [t] : t >= 0 }. The scop consists of two parts, one for
2306 * evaluating the condition and one for the body.
2307 * The schedule is adjusted to reflect that the condition is evaluated
2308 * before the body is executed and the body is filtered to depend
2309 * on the result of the condition evaluating to true on all iterations
2310 * up to the current iteration, while the evaluation the condition itself
2311 * is filtered to depend on the result of the condition evaluating to true
2312 * on all previous iterations.
2313 * The context of the scop representing the body is dropped
2314 * because we don't know how many times the body will be executed,
2315 * if at all.
2317 * If the body contains any break, then it is taken into
2318 * account in infinite_domain (if the skip condition is affine)
2319 * or in scop_add_break (if the skip condition is not affine).
2321 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2323 Expr *cond;
2324 isl_id *id;
2325 isl_map *test_access;
2326 isl_set *domain;
2327 isl_map *ident;
2328 isl_pw_aff *pa;
2329 struct pet_scop *scop, *scop_body;
2330 bool has_var_break;
2331 isl_map *break_access;
2333 cond = stmt->getCond();
2334 if (!cond) {
2335 unsupported(stmt);
2336 return NULL;
2339 clear_assignments clear(assigned_value);
2340 clear.TraverseStmt(stmt->getBody());
2342 pa = try_extract_affine_condition(cond);
2343 if (pa)
2344 return extract_affine_while(pa, stmt->getBody());
2346 if (!allow_nested) {
2347 unsupported(stmt);
2348 return NULL;
2351 test_access = create_test_access(ctx, n_test++);
2352 scop = extract_non_affine_condition(cond, isl_map_copy(test_access));
2353 scop = scop_add_array(scop, test_access, ast_context);
2354 scop_body = extract(stmt->getBody());
2356 id = isl_id_alloc(ctx, "t", NULL);
2357 domain = infinite_domain(isl_id_copy(id), scop_body);
2358 ident = identity_map(domain);
2360 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2361 if (has_var_break)
2362 break_access = pet_scop_get_skip_map(scop_body, pet_skip_later);
2364 scop = pet_scop_prefix(scop, 0);
2365 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_map_copy(ident),
2366 isl_map_copy(ident), isl_id_copy(id));
2367 scop_body = pet_scop_reset_context(scop_body);
2368 scop_body = pet_scop_prefix(scop_body, 1);
2369 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2370 isl_map_copy(ident), ident, id);
2372 if (has_var_break) {
2373 scop = scop_add_break(scop, isl_map_copy(break_access),
2374 isl_set_copy(domain), 1);
2375 scop_body = scop_add_break(scop_body, break_access,
2376 isl_set_copy(domain), 1);
2378 scop = scop_add_while(scop, scop_body, test_access, domain, 1);
2380 return scop;
2383 /* Check whether "cond" expresses a simple loop bound
2384 * on the only set dimension.
2385 * In particular, if "up" is set then "cond" should contain only
2386 * upper bounds on the set dimension.
2387 * Otherwise, it should contain only lower bounds.
2389 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
2391 if (isl_int_is_pos(inc))
2392 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2393 else
2394 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2397 /* Extend a condition on a given iteration of a loop to one that
2398 * imposes the same condition on all previous iterations.
2399 * "domain" expresses the lower [upper] bound on the iterations
2400 * when inc is positive [negative].
2402 * In particular, we construct the condition (when inc is positive)
2404 * forall i' : (domain(i') and i' <= i) => cond(i')
2406 * which is equivalent to
2408 * not exists i' : domain(i') and i' <= i and not cond(i')
2410 * We construct this set by negating cond, applying a map
2412 * { [i'] -> [i] : domain(i') and i' <= i }
2414 * and then negating the result again.
2416 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2417 __isl_take isl_set *domain, isl_int inc)
2419 isl_map *previous_to_this;
2421 if (isl_int_is_pos(inc))
2422 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2423 else
2424 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2426 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2428 cond = isl_set_complement(cond);
2429 cond = isl_set_apply(cond, previous_to_this);
2430 cond = isl_set_complement(cond);
2432 return cond;
2435 /* Construct a domain of the form
2437 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2439 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2440 __isl_take isl_pw_aff *init, isl_int inc)
2442 isl_aff *aff;
2443 isl_space *dim;
2444 isl_set *set;
2446 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2447 dim = isl_pw_aff_get_domain_space(init);
2448 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2449 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
2450 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2452 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2453 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2454 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2455 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2457 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2459 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2461 return isl_set_params(set);
2464 /* Assuming "cond" represents a bound on a loop where the loop
2465 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2466 * is possible.
2468 * Under the given assumptions, wrapping is only possible if "cond" allows
2469 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2470 * increasing iterator and 0 in case of a decreasing iterator.
2472 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
2474 bool cw;
2475 isl_int limit;
2476 isl_set *test;
2478 test = isl_set_copy(cond);
2480 isl_int_init(limit);
2481 if (isl_int_is_neg(inc))
2482 isl_int_set_si(limit, 0);
2483 else {
2484 isl_int_set_si(limit, 1);
2485 isl_int_mul_2exp(limit, limit, get_type_size(iv));
2486 isl_int_sub_ui(limit, limit, 1);
2489 test = isl_set_fix(cond, isl_dim_set, 0, limit);
2490 cw = !isl_set_is_empty(test);
2491 isl_set_free(test);
2493 isl_int_clear(limit);
2495 return cw;
2498 /* Given a one-dimensional space, construct the following mapping on this
2499 * space
2501 * { [v] -> [v mod 2^width] }
2503 * where width is the number of bits used to represent the values
2504 * of the unsigned variable "iv".
2506 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
2507 ValueDecl *iv)
2509 isl_int mod;
2510 isl_aff *aff;
2511 isl_map *map;
2513 isl_int_init(mod);
2514 isl_int_set_si(mod, 1);
2515 isl_int_mul_2exp(mod, mod, get_type_size(iv));
2517 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2518 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2519 aff = isl_aff_mod(aff, mod);
2521 isl_int_clear(mod);
2523 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2524 map = isl_map_reverse(map);
2527 /* Project out the parameter "id" from "set".
2529 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2530 __isl_keep isl_id *id)
2532 int pos;
2534 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2535 if (pos >= 0)
2536 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2538 return set;
2541 /* Compute the set of parameters for which "set1" is a subset of "set2".
2543 * set1 is a subset of set2 if
2545 * forall i in set1 : i in set2
2547 * or
2549 * not exists i in set1 and i not in set2
2551 * i.e.,
2553 * not exists i in set1 \ set2
2555 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2556 __isl_take isl_set *set2)
2558 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2561 /* Compute the set of parameter values for which "cond" holds
2562 * on the next iteration for each element of "dom".
2564 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2565 * and then compute the set of parameters for which the result is a subset
2566 * of "cond".
2568 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2569 __isl_take isl_set *dom, isl_int inc)
2571 isl_space *space;
2572 isl_aff *aff;
2573 isl_map *next;
2575 space = isl_set_get_space(dom);
2576 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2577 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2578 aff = isl_aff_add_constant(aff, inc);
2579 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2581 dom = isl_set_apply(dom, next);
2583 return enforce_subset(dom, cond);
2586 /* Does "id" refer to a nested access?
2588 static bool is_nested_parameter(__isl_keep isl_id *id)
2590 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2593 /* Does parameter "pos" of "space" refer to a nested access?
2595 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2597 bool nested;
2598 isl_id *id;
2600 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2601 nested = is_nested_parameter(id);
2602 isl_id_free(id);
2604 return nested;
2607 /* Does "space" involve any parameters that refer to nested
2608 * accesses, i.e., parameters with no name?
2610 static bool has_nested(__isl_keep isl_space *space)
2612 int nparam;
2614 nparam = isl_space_dim(space, isl_dim_param);
2615 for (int i = 0; i < nparam; ++i)
2616 if (is_nested_parameter(space, i))
2617 return true;
2619 return false;
2622 /* Does "pa" involve any parameters that refer to nested
2623 * accesses, i.e., parameters with no name?
2625 static bool has_nested(__isl_keep isl_pw_aff *pa)
2627 isl_space *space;
2628 bool nested;
2630 space = isl_pw_aff_get_space(pa);
2631 nested = has_nested(space);
2632 isl_space_free(space);
2634 return nested;
2637 /* Construct a pet_scop for a for statement.
2638 * The for loop is required to be of the form
2640 * for (i = init; condition; ++i)
2642 * or
2644 * for (i = init; condition; --i)
2646 * The initialization of the for loop should either be an assignment
2647 * to an integer variable, or a declaration of such a variable with
2648 * initialization.
2650 * The condition is allowed to contain nested accesses, provided
2651 * they are not being written to inside the body of the loop.
2652 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2653 * essentially treated as a while loop, with iteration domain
2654 * { [i] : i >= init }.
2656 * We extract a pet_scop for the body and then embed it in a loop with
2657 * iteration domain and schedule
2659 * { [i] : i >= init and condition' }
2660 * { [i] -> [i] }
2662 * or
2664 * { [i] : i <= init and condition' }
2665 * { [i] -> [-i] }
2667 * Where condition' is equal to condition if the latter is
2668 * a simple upper [lower] bound and a condition that is extended
2669 * to apply to all previous iterations otherwise.
2671 * If the condition is non-affine, then we drop the condition from the
2672 * iteration domain and instead create a separate statement
2673 * for evaluating the condition. The body is then filtered to depend
2674 * on the result of the condition evaluating to true on all iterations
2675 * up to the current iteration, while the evaluation the condition itself
2676 * is filtered to depend on the result of the condition evaluating to true
2677 * on all previous iterations.
2678 * The context of the scop representing the body is dropped
2679 * because we don't know how many times the body will be executed,
2680 * if at all.
2682 * If the stride of the loop is not 1, then "i >= init" is replaced by
2684 * (exists a: i = init + stride * a and a >= 0)
2686 * If the loop iterator i is unsigned, then wrapping may occur.
2687 * During the computation, we work with a virtual iterator that
2688 * does not wrap. However, the condition in the code applies
2689 * to the wrapped value, so we need to change condition(i)
2690 * into condition([i % 2^width]).
2691 * After computing the virtual domain and schedule, we apply
2692 * the function { [v] -> [v % 2^width] } to the domain and the domain
2693 * of the schedule. In order not to lose any information, we also
2694 * need to intersect the domain of the schedule with the virtual domain
2695 * first, since some iterations in the wrapped domain may be scheduled
2696 * several times, typically an infinite number of times.
2697 * Note that there may be no need to perform this final wrapping
2698 * if the loop condition (after wrapping) satisfies certain conditions.
2699 * However, the is_simple_bound condition is not enough since it doesn't
2700 * check if there even is an upper bound.
2702 * If the loop condition is non-affine, then we keep the virtual
2703 * iterator in the iteration domain and instead replace all accesses
2704 * to the original iterator by the wrapping of the virtual iterator.
2706 * Wrapping on unsigned iterators can be avoided entirely if
2707 * loop condition is simple, the loop iterator is incremented
2708 * [decremented] by one and the last value before wrapping cannot
2709 * possibly satisfy the loop condition.
2711 * Before extracting a pet_scop from the body we remove all
2712 * assignments in assigned_value to variables that are assigned
2713 * somewhere in the body of the loop.
2715 * Valid parameters for a for loop are those for which the initial
2716 * value itself, the increment on each domain iteration and
2717 * the condition on both the initial value and
2718 * the result of incrementing the iterator for each iteration of the domain
2719 * can be evaluated.
2720 * If the loop condition is non-affine, then we only consider validity
2721 * of the initial value.
2723 * If the body contains any break, then we keep track of it in "skip"
2724 * (if the skip condition is affine) or it is handled in scop_add_break
2725 * (if the skip condition is not affine).
2726 * Note that the affine break condition needs to be considered with
2727 * respect to previous iterations in the virtual domain (if any)
2728 * and that the domain needs to be kept virtual if there is a non-affine
2729 * break condition.
2731 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2733 BinaryOperator *ass;
2734 Decl *decl;
2735 Stmt *init;
2736 Expr *lhs, *rhs;
2737 ValueDecl *iv;
2738 isl_space *space;
2739 isl_set *domain;
2740 isl_map *sched;
2741 isl_set *cond = NULL;
2742 isl_set *skip = NULL;
2743 isl_id *id;
2744 struct pet_scop *scop, *scop_cond = NULL;
2745 assigned_value_cache cache(assigned_value);
2746 isl_int inc;
2747 bool is_one;
2748 bool is_unsigned;
2749 bool is_simple;
2750 bool is_virtual;
2751 bool keep_virtual = false;
2752 bool has_affine_break;
2753 bool has_var_break;
2754 isl_map *wrap = NULL;
2755 isl_pw_aff *pa, *pa_inc, *init_val;
2756 isl_set *valid_init;
2757 isl_set *valid_cond;
2758 isl_set *valid_cond_init;
2759 isl_set *valid_cond_next;
2760 isl_set *valid_inc;
2761 isl_map *test_access = NULL, *break_access = NULL;
2762 int stmt_id;
2764 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2765 return extract_infinite_for(stmt);
2767 init = stmt->getInit();
2768 if (!init) {
2769 unsupported(stmt);
2770 return NULL;
2772 if ((ass = initialization_assignment(init)) != NULL) {
2773 iv = extract_induction_variable(ass);
2774 if (!iv)
2775 return NULL;
2776 lhs = ass->getLHS();
2777 rhs = ass->getRHS();
2778 } else if ((decl = initialization_declaration(init)) != NULL) {
2779 VarDecl *var = extract_induction_variable(init, decl);
2780 if (!var)
2781 return NULL;
2782 iv = var;
2783 rhs = var->getInit();
2784 lhs = create_DeclRefExpr(var);
2785 } else {
2786 unsupported(stmt->getInit());
2787 return NULL;
2790 pa_inc = extract_increment(stmt, iv);
2791 if (!pa_inc)
2792 return NULL;
2794 isl_int_init(inc);
2795 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
2796 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
2797 isl_pw_aff_free(pa_inc);
2798 unsupported(stmt->getInc());
2799 isl_int_clear(inc);
2800 return NULL;
2802 valid_inc = isl_pw_aff_domain(pa_inc);
2804 is_unsigned = iv->getType()->isUnsignedIntegerType();
2806 assigned_value.erase(iv);
2807 clear_assignments clear(assigned_value);
2808 clear.TraverseStmt(stmt->getBody());
2810 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2812 pa = try_extract_nested_condition(stmt->getCond());
2813 if (allow_nested && (!pa || has_nested(pa)))
2814 stmt_id = n_stmt++;
2816 scop = extract(stmt->getBody());
2818 has_affine_break = scop &&
2819 pet_scop_has_affine_skip(scop, pet_skip_later);
2820 if (has_affine_break) {
2821 skip = pet_scop_get_skip(scop, pet_skip_later);
2822 skip = isl_set_fix_si(skip, isl_dim_set, 0, 1);
2823 skip = isl_set_params(skip);
2825 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
2826 if (has_var_break) {
2827 break_access = pet_scop_get_skip_map(scop, pet_skip_later);
2828 keep_virtual = true;
2831 if (pa && !is_nested_allowed(pa, scop)) {
2832 isl_pw_aff_free(pa);
2833 pa = NULL;
2836 if (!allow_nested && !pa)
2837 pa = try_extract_affine_condition(stmt->getCond());
2838 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2839 cond = isl_pw_aff_non_zero_set(pa);
2840 if (allow_nested && !cond) {
2841 int save_n_stmt = n_stmt;
2842 test_access = create_test_access(ctx, n_test++);
2843 n_stmt = stmt_id;
2844 scop_cond = extract_non_affine_condition(stmt->getCond(),
2845 isl_map_copy(test_access));
2846 n_stmt = save_n_stmt;
2847 scop_cond = scop_add_array(scop_cond, test_access, ast_context);
2848 scop_cond = pet_scop_prefix(scop_cond, 0);
2849 scop = pet_scop_reset_context(scop);
2850 scop = pet_scop_prefix(scop, 1);
2851 keep_virtual = true;
2852 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2855 cond = embed(cond, isl_id_copy(id));
2856 skip = embed(skip, isl_id_copy(id));
2857 valid_cond = isl_set_coalesce(valid_cond);
2858 valid_cond = embed(valid_cond, isl_id_copy(id));
2859 valid_inc = embed(valid_inc, isl_id_copy(id));
2860 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
2861 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2863 init_val = extract_affine(rhs);
2864 valid_cond_init = enforce_subset(
2865 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
2866 isl_set_copy(valid_cond));
2867 if (is_one && !is_virtual) {
2868 isl_pw_aff_free(init_val);
2869 pa = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
2870 lhs, rhs, init);
2871 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2872 valid_init = set_project_out_by_id(valid_init, id);
2873 domain = isl_pw_aff_non_zero_set(pa);
2874 } else {
2875 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2876 domain = strided_domain(isl_id_copy(id), init_val, inc);
2879 domain = embed(domain, isl_id_copy(id));
2880 if (is_virtual) {
2881 isl_map *rev_wrap;
2882 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2883 rev_wrap = isl_map_reverse(isl_map_copy(wrap));
2884 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2885 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
2886 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2887 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2889 is_simple = is_simple_bound(cond, inc);
2890 if (!is_simple) {
2891 cond = isl_set_gist(cond, isl_set_copy(domain));
2892 is_simple = is_simple_bound(cond, inc);
2894 if (!is_simple)
2895 cond = valid_for_each_iteration(cond,
2896 isl_set_copy(domain), inc);
2897 domain = isl_set_intersect(domain, cond);
2898 if (has_affine_break) {
2899 skip = isl_set_intersect(skip , isl_set_copy(domain));
2900 skip = after(skip, isl_int_sgn(inc));
2901 domain = isl_set_subtract(domain, skip);
2903 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2904 space = isl_space_from_domain(isl_set_get_space(domain));
2905 space = isl_space_add_dims(space, isl_dim_out, 1);
2906 sched = isl_map_universe(space);
2907 if (isl_int_is_pos(inc))
2908 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2909 else
2910 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2912 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain), inc);
2913 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2915 if (is_virtual && !keep_virtual) {
2916 wrap = isl_map_set_dim_id(wrap,
2917 isl_dim_out, 0, isl_id_copy(id));
2918 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
2919 domain = isl_set_apply(domain, isl_map_copy(wrap));
2920 sched = isl_map_apply_domain(sched, wrap);
2922 if (!(is_virtual && keep_virtual)) {
2923 space = isl_set_get_space(domain);
2924 wrap = isl_map_identity(isl_space_map_from_set(space));
2927 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
2928 isl_map_copy(sched), isl_map_copy(wrap), isl_id_copy(id));
2929 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
2930 scop = resolve_nested(scop);
2931 if (has_var_break)
2932 scop = scop_add_break(scop, break_access, isl_set_copy(domain),
2933 isl_int_sgn(inc));
2934 if (test_access) {
2935 scop = scop_add_while(scop_cond, scop, test_access, domain,
2936 isl_int_sgn(inc));
2937 isl_set_free(valid_inc);
2938 } else {
2939 scop = pet_scop_restrict_context(scop, valid_inc);
2940 scop = pet_scop_restrict_context(scop, valid_cond_next);
2941 scop = pet_scop_restrict_context(scop, valid_cond_init);
2942 isl_set_free(domain);
2944 clear_assignment(assigned_value, iv);
2946 isl_int_clear(inc);
2948 scop = pet_scop_restrict_context(scop, valid_init);
2950 return scop;
2953 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
2955 return extract(stmt->children(), true, skip_declarations);
2958 /* Does parameter "pos" of "map" refer to a nested access?
2960 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
2962 bool nested;
2963 isl_id *id;
2965 id = isl_map_get_dim_id(map, isl_dim_param, pos);
2966 nested = is_nested_parameter(id);
2967 isl_id_free(id);
2969 return nested;
2972 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
2974 static int n_nested_parameter(__isl_keep isl_space *space)
2976 int n = 0;
2977 int nparam;
2979 nparam = isl_space_dim(space, isl_dim_param);
2980 for (int i = 0; i < nparam; ++i)
2981 if (is_nested_parameter(space, i))
2982 ++n;
2984 return n;
2987 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
2989 static int n_nested_parameter(__isl_keep isl_map *map)
2991 isl_space *space;
2992 int n;
2994 space = isl_map_get_space(map);
2995 n = n_nested_parameter(space);
2996 isl_space_free(space);
2998 return n;
3001 /* For each nested access parameter in "space",
3002 * construct a corresponding pet_expr, place it in args and
3003 * record its position in "param2pos".
3004 * "n_arg" is the number of elements that are already in args.
3005 * The position recorded in "param2pos" takes this number into account.
3006 * If the pet_expr corresponding to a parameter is identical to
3007 * the pet_expr corresponding to an earlier parameter, then these two
3008 * parameters are made to refer to the same element in args.
3010 * Return the final number of elements in args or -1 if an error has occurred.
3012 int PetScan::extract_nested(__isl_keep isl_space *space,
3013 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
3015 int nparam;
3017 nparam = isl_space_dim(space, isl_dim_param);
3018 for (int i = 0; i < nparam; ++i) {
3019 int j;
3020 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3021 Expr *nested;
3023 if (!is_nested_parameter(id)) {
3024 isl_id_free(id);
3025 continue;
3028 nested = (Expr *) isl_id_get_user(id);
3029 args[n_arg] = extract_expr(nested);
3030 if (!args[n_arg])
3031 return -1;
3033 for (j = 0; j < n_arg; ++j)
3034 if (pet_expr_is_equal(args[j], args[n_arg]))
3035 break;
3037 if (j < n_arg) {
3038 pet_expr_free(args[n_arg]);
3039 args[n_arg] = NULL;
3040 param2pos[i] = j;
3041 } else
3042 param2pos[i] = n_arg++;
3044 isl_id_free(id);
3047 return n_arg;
3050 /* For each nested access parameter in the access relations in "expr",
3051 * construct a corresponding pet_expr, place it in expr->args and
3052 * record its position in "param2pos".
3053 * n is the number of nested access parameters.
3055 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
3056 std::map<int,int> &param2pos)
3058 isl_space *space;
3060 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
3061 expr->n_arg = n;
3062 if (!expr->args)
3063 goto error;
3065 space = isl_map_get_space(expr->acc.access);
3066 n = extract_nested(space, 0, expr->args, param2pos);
3067 isl_space_free(space);
3069 if (n < 0)
3070 goto error;
3072 expr->n_arg = n;
3073 return expr;
3074 error:
3075 pet_expr_free(expr);
3076 return NULL;
3079 /* Look for parameters in any access relation in "expr" that
3080 * refer to nested accesses. In particular, these are
3081 * parameters with no name.
3083 * If there are any such parameters, then the domain of the access
3084 * relation, which is still [] at this point, is replaced by
3085 * [[] -> [t_1,...,t_n]], with n the number of these parameters
3086 * (after identifying identical nested accesses).
3087 * The parameters are then equated to the corresponding t dimensions
3088 * and subsequently projected out.
3089 * param2pos maps the position of the parameter to the position
3090 * of the corresponding t dimension.
3092 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
3094 int n;
3095 int nparam;
3096 int n_in;
3097 isl_space *dim;
3098 isl_map *map;
3099 std::map<int,int> param2pos;
3101 if (!expr)
3102 return expr;
3104 for (int i = 0; i < expr->n_arg; ++i) {
3105 expr->args[i] = resolve_nested(expr->args[i]);
3106 if (!expr->args[i]) {
3107 pet_expr_free(expr);
3108 return NULL;
3112 if (expr->type != pet_expr_access)
3113 return expr;
3115 n = n_nested_parameter(expr->acc.access);
3116 if (n == 0)
3117 return expr;
3119 expr = extract_nested(expr, n, param2pos);
3120 if (!expr)
3121 return NULL;
3123 n = expr->n_arg;
3124 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
3125 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
3126 dim = isl_map_get_space(expr->acc.access);
3127 dim = isl_space_domain(dim);
3128 dim = isl_space_from_domain(dim);
3129 dim = isl_space_add_dims(dim, isl_dim_out, n);
3130 map = isl_map_universe(dim);
3131 map = isl_map_domain_map(map);
3132 map = isl_map_reverse(map);
3133 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
3135 for (int i = nparam - 1; i >= 0; --i) {
3136 isl_id *id = isl_map_get_dim_id(expr->acc.access,
3137 isl_dim_param, i);
3138 if (!is_nested_parameter(id)) {
3139 isl_id_free(id);
3140 continue;
3143 expr->acc.access = isl_map_equate(expr->acc.access,
3144 isl_dim_param, i, isl_dim_in,
3145 n_in + param2pos[i]);
3146 expr->acc.access = isl_map_project_out(expr->acc.access,
3147 isl_dim_param, i, 1);
3149 isl_id_free(id);
3152 return expr;
3153 error:
3154 pet_expr_free(expr);
3155 return NULL;
3158 /* Return the file offset of the expansion location of "Loc".
3160 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3162 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3165 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3167 /* Return a SourceLocation for the location after the first semicolon
3168 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3169 * call it and also skip trailing spaces and newline.
3171 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3172 const LangOptions &LO)
3174 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3177 #else
3179 /* Return a SourceLocation for the location after the first semicolon
3180 * after "loc". If Lexer::findLocationAfterToken is not available,
3181 * we look in the underlying character data for the first semicolon.
3183 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3184 const LangOptions &LO)
3186 const char *semi;
3187 const char *s = SM.getCharacterData(loc);
3189 semi = strchr(s, ';');
3190 if (!semi)
3191 return SourceLocation();
3192 return loc.getFileLocWithOffset(semi + 1 - s);
3195 #endif
3197 /* Convert a top-level pet_expr to a pet_scop with one statement.
3198 * This mainly involves resolving nested expression parameters
3199 * and setting the name of the iteration space.
3200 * The name is given by "label" if it is non-NULL. Otherwise,
3201 * it is of the form S_<n_stmt>.
3202 * start and end of the pet_scop are derived from those of "stmt".
3204 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
3205 __isl_take isl_id *label)
3207 struct pet_stmt *ps;
3208 struct pet_scop *scop;
3209 SourceLocation loc = stmt->getLocStart();
3210 SourceManager &SM = PP.getSourceManager();
3211 const LangOptions &LO = PP.getLangOpts();
3212 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3213 unsigned start, end;
3215 expr = resolve_nested(expr);
3216 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
3217 scop = pet_scop_from_pet_stmt(ctx, ps);
3219 start = getExpansionOffset(SM, loc);
3220 loc = stmt->getLocEnd();
3221 loc = location_after_semi(loc, SM, LO);
3222 end = getExpansionOffset(SM, loc);
3224 scop = pet_scop_update_start_end(scop, start, end);
3225 return scop;
3228 /* Check if we can extract an affine expression from "expr".
3229 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3230 * We turn on autodetection so that we won't generate any warnings
3231 * and turn off nesting, so that we won't accept any non-affine constructs.
3233 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3235 isl_pw_aff *pwaff;
3236 int save_autodetect = options->autodetect;
3237 bool save_nesting = nesting_enabled;
3239 options->autodetect = 1;
3240 nesting_enabled = false;
3242 pwaff = extract_affine(expr);
3244 options->autodetect = save_autodetect;
3245 nesting_enabled = save_nesting;
3247 return pwaff;
3250 /* Check whether "expr" is an affine expression.
3252 bool PetScan::is_affine(Expr *expr)
3254 isl_pw_aff *pwaff;
3256 pwaff = try_extract_affine(expr);
3257 isl_pw_aff_free(pwaff);
3259 return pwaff != NULL;
3262 /* Check if we can extract an affine constraint from "expr".
3263 * Return the constraint as an isl_set if we can and NULL otherwise.
3264 * We turn on autodetection so that we won't generate any warnings
3265 * and turn off nesting, so that we won't accept any non-affine constructs.
3267 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3269 isl_pw_aff *cond;
3270 int save_autodetect = options->autodetect;
3271 bool save_nesting = nesting_enabled;
3273 options->autodetect = 1;
3274 nesting_enabled = false;
3276 cond = extract_condition(expr);
3278 options->autodetect = save_autodetect;
3279 nesting_enabled = save_nesting;
3281 return cond;
3284 /* Check whether "expr" is an affine constraint.
3286 bool PetScan::is_affine_condition(Expr *expr)
3288 isl_pw_aff *cond;
3290 cond = try_extract_affine_condition(expr);
3291 isl_pw_aff_free(cond);
3293 return cond != NULL;
3296 /* Check if we can extract a condition from "expr".
3297 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3298 * If allow_nested is set, then the condition may involve parameters
3299 * corresponding to nested accesses.
3300 * We turn on autodetection so that we won't generate any warnings.
3302 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3304 isl_pw_aff *cond;
3305 int save_autodetect = options->autodetect;
3306 bool save_nesting = nesting_enabled;
3308 options->autodetect = 1;
3309 nesting_enabled = allow_nested;
3310 cond = extract_condition(expr);
3312 options->autodetect = save_autodetect;
3313 nesting_enabled = save_nesting;
3315 return cond;
3318 /* If the top-level expression of "stmt" is an assignment, then
3319 * return that assignment as a BinaryOperator.
3320 * Otherwise return NULL.
3322 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3324 BinaryOperator *ass;
3326 if (!stmt)
3327 return NULL;
3328 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3329 return NULL;
3331 ass = cast<BinaryOperator>(stmt);
3332 if(ass->getOpcode() != BO_Assign)
3333 return NULL;
3335 return ass;
3338 /* Check if the given if statement is a conditional assignement
3339 * with a non-affine condition. If so, construct a pet_scop
3340 * corresponding to this conditional assignment. Otherwise return NULL.
3342 * In particular we check if "stmt" is of the form
3344 * if (condition)
3345 * a = f(...);
3346 * else
3347 * a = g(...);
3349 * where a is some array or scalar access.
3350 * The constructed pet_scop then corresponds to the expression
3352 * a = condition ? f(...) : g(...)
3354 * All access relations in f(...) are intersected with condition
3355 * while all access relation in g(...) are intersected with the complement.
3357 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3359 BinaryOperator *ass_then, *ass_else;
3360 isl_map *write_then, *write_else;
3361 isl_set *cond, *comp;
3362 isl_map *map;
3363 isl_pw_aff *pa;
3364 int equal;
3365 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3366 bool save_nesting = nesting_enabled;
3368 if (!options->detect_conditional_assignment)
3369 return NULL;
3371 ass_then = top_assignment_or_null(stmt->getThen());
3372 ass_else = top_assignment_or_null(stmt->getElse());
3374 if (!ass_then || !ass_else)
3375 return NULL;
3377 if (is_affine_condition(stmt->getCond()))
3378 return NULL;
3380 write_then = extract_access(ass_then->getLHS());
3381 write_else = extract_access(ass_else->getLHS());
3383 equal = isl_map_is_equal(write_then, write_else);
3384 isl_map_free(write_else);
3385 if (equal < 0 || !equal) {
3386 isl_map_free(write_then);
3387 return NULL;
3390 nesting_enabled = allow_nested;
3391 pa = extract_condition(stmt->getCond());
3392 nesting_enabled = save_nesting;
3393 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3394 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3395 map = isl_map_from_range(isl_set_from_pw_aff(pa));
3397 pe_cond = pet_expr_from_access(map);
3399 pe_then = extract_expr(ass_then->getRHS());
3400 pe_then = pet_expr_restrict(pe_then, cond);
3401 pe_else = extract_expr(ass_else->getRHS());
3402 pe_else = pet_expr_restrict(pe_else, comp);
3404 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
3405 pe_write = pet_expr_from_access(write_then);
3406 if (pe_write) {
3407 pe_write->acc.write = 1;
3408 pe_write->acc.read = 0;
3410 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
3411 return extract(stmt, pe);
3414 /* Create a pet_scop with a single statement evaluating "cond"
3415 * and writing the result to a virtual scalar, as expressed by
3416 * "access".
3418 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
3419 __isl_take isl_map *access)
3421 struct pet_expr *expr, *write;
3422 struct pet_stmt *ps;
3423 struct pet_scop *scop;
3424 SourceLocation loc = cond->getLocStart();
3425 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3427 write = pet_expr_from_access(access);
3428 if (write) {
3429 write->acc.write = 1;
3430 write->acc.read = 0;
3432 expr = extract_expr(cond);
3433 expr = resolve_nested(expr);
3434 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
3435 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
3436 scop = pet_scop_from_pet_stmt(ctx, ps);
3437 scop = resolve_nested(scop);
3439 return scop;
3442 extern "C" {
3443 static __isl_give isl_map *embed_access(__isl_take isl_map *access,
3444 void *user);
3447 /* Apply the map pointed to by "user" to the domain of the access
3448 * relation, thereby embedding it in the range of the map.
3449 * The domain of both relations is the zero-dimensional domain.
3451 static __isl_give isl_map *embed_access(__isl_take isl_map *access, void *user)
3453 isl_map *map = (isl_map *) user;
3455 return isl_map_apply_domain(access, isl_map_copy(map));
3458 /* Apply "map" to all access relations in "expr".
3460 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
3462 return pet_expr_foreach_access(expr, &embed_access, map);
3465 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3467 static int n_nested_parameter(__isl_keep isl_set *set)
3469 isl_space *space;
3470 int n;
3472 space = isl_set_get_space(set);
3473 n = n_nested_parameter(space);
3474 isl_space_free(space);
3476 return n;
3479 /* Remove all parameters from "map" that refer to nested accesses.
3481 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
3483 int nparam;
3484 isl_space *space;
3486 space = isl_map_get_space(map);
3487 nparam = isl_space_dim(space, isl_dim_param);
3488 for (int i = nparam - 1; i >= 0; --i)
3489 if (is_nested_parameter(space, i))
3490 map = isl_map_project_out(map, isl_dim_param, i, 1);
3491 isl_space_free(space);
3493 return map;
3496 extern "C" {
3497 static __isl_give isl_map *access_remove_nested_parameters(
3498 __isl_take isl_map *access, void *user);
3501 static __isl_give isl_map *access_remove_nested_parameters(
3502 __isl_take isl_map *access, void *user)
3504 return remove_nested_parameters(access);
3507 /* Remove all nested access parameters from the schedule and all
3508 * accesses of "stmt".
3509 * There is no need to remove them from the domain as these parameters
3510 * have already been removed from the domain when this function is called.
3512 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
3514 if (!stmt)
3515 return NULL;
3516 stmt->schedule = remove_nested_parameters(stmt->schedule);
3517 stmt->body = pet_expr_foreach_access(stmt->body,
3518 &access_remove_nested_parameters, NULL);
3519 if (!stmt->schedule || !stmt->body)
3520 goto error;
3521 for (int i = 0; i < stmt->n_arg; ++i) {
3522 stmt->args[i] = pet_expr_foreach_access(stmt->args[i],
3523 &access_remove_nested_parameters, NULL);
3524 if (!stmt->args[i])
3525 goto error;
3528 return stmt;
3529 error:
3530 pet_stmt_free(stmt);
3531 return NULL;
3534 /* For each nested access parameter in the domain of "stmt",
3535 * construct a corresponding pet_expr, place it before the original
3536 * elements in stmt->args and record its position in "param2pos".
3537 * n is the number of nested access parameters.
3539 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3540 std::map<int,int> &param2pos)
3542 int i;
3543 isl_space *space;
3544 int n_arg;
3545 struct pet_expr **args;
3547 n_arg = stmt->n_arg;
3548 args = isl_calloc_array(ctx, struct pet_expr *, n + n_arg);
3549 if (!args)
3550 goto error;
3552 space = isl_set_get_space(stmt->domain);
3553 n_arg = extract_nested(space, 0, args, param2pos);
3554 isl_space_free(space);
3556 if (n_arg < 0)
3557 goto error;
3559 for (i = 0; i < stmt->n_arg; ++i)
3560 args[n_arg + i] = stmt->args[i];
3561 free(stmt->args);
3562 stmt->args = args;
3563 stmt->n_arg += n_arg;
3565 return stmt;
3566 error:
3567 if (args) {
3568 for (i = 0; i < n; ++i)
3569 pet_expr_free(args[i]);
3570 free(args);
3572 pet_stmt_free(stmt);
3573 return NULL;
3576 /* Check whether any of the arguments i of "stmt" starting at position "n"
3577 * is equal to one of the first "n" arguments j.
3578 * If so, combine the constraints on arguments i and j and remove
3579 * argument i.
3581 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3583 int i, j;
3584 isl_map *map;
3586 if (!stmt)
3587 return NULL;
3588 if (n == 0)
3589 return stmt;
3590 if (n == stmt->n_arg)
3591 return stmt;
3593 map = isl_set_unwrap(stmt->domain);
3595 for (i = stmt->n_arg - 1; i >= n; --i) {
3596 for (j = 0; j < n; ++j)
3597 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3598 break;
3599 if (j >= n)
3600 continue;
3602 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3603 map = isl_map_project_out(map, isl_dim_out, i, 1);
3605 pet_expr_free(stmt->args[i]);
3606 for (j = i; j + 1 < stmt->n_arg; ++j)
3607 stmt->args[j] = stmt->args[j + 1];
3608 stmt->n_arg--;
3611 stmt->domain = isl_map_wrap(map);
3612 if (!stmt->domain)
3613 goto error;
3614 return stmt;
3615 error:
3616 pet_stmt_free(stmt);
3617 return NULL;
3620 /* Look for parameters in the iteration domain of "stmt" that
3621 * refer to nested accesses. In particular, these are
3622 * parameters with no name.
3624 * If there are any such parameters, then as many extra variables
3625 * (after identifying identical nested accesses) are inserted in the
3626 * range of the map wrapped inside the domain, before the original variables.
3627 * If the original domain is not a wrapped map, then a new wrapped
3628 * map is created with zero output dimensions.
3629 * The parameters are then equated to the corresponding output dimensions
3630 * and subsequently projected out, from the iteration domain,
3631 * the schedule and the access relations.
3632 * For each of the output dimensions, a corresponding argument
3633 * expression is inserted. Initially they are created with
3634 * a zero-dimensional domain, so they have to be embedded
3635 * in the current iteration domain.
3636 * param2pos maps the position of the parameter to the position
3637 * of the corresponding output dimension in the wrapped map.
3639 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3641 int n;
3642 int nparam;
3643 unsigned n_arg;
3644 isl_map *map;
3645 std::map<int,int> param2pos;
3647 if (!stmt)
3648 return NULL;
3650 n = n_nested_parameter(stmt->domain);
3651 if (n == 0)
3652 return stmt;
3654 n_arg = stmt->n_arg;
3655 stmt = extract_nested(stmt, n, param2pos);
3656 if (!stmt)
3657 return NULL;
3659 n = stmt->n_arg - n_arg;
3660 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3661 if (isl_set_is_wrapping(stmt->domain))
3662 map = isl_set_unwrap(stmt->domain);
3663 else
3664 map = isl_map_from_domain(stmt->domain);
3665 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3667 for (int i = nparam - 1; i >= 0; --i) {
3668 isl_id *id;
3670 if (!is_nested_parameter(map, i))
3671 continue;
3673 id = isl_map_get_tuple_id(stmt->args[param2pos[i]]->acc.access,
3674 isl_dim_out);
3675 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3676 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3677 param2pos[i]);
3678 map = isl_map_project_out(map, isl_dim_param, i, 1);
3681 stmt->domain = isl_map_wrap(map);
3683 map = isl_set_unwrap(isl_set_copy(stmt->domain));
3684 map = isl_map_from_range(isl_map_domain(map));
3685 for (int pos = 0; pos < n; ++pos)
3686 stmt->args[pos] = embed(stmt->args[pos], map);
3687 isl_map_free(map);
3689 stmt = remove_nested_parameters(stmt);
3690 stmt = remove_duplicate_arguments(stmt, n);
3692 return stmt;
3693 error:
3694 pet_stmt_free(stmt);
3695 return NULL;
3698 /* For each statement in "scop", move the parameters that correspond
3699 * to nested access into the ranges of the domains and create
3700 * corresponding argument expressions.
3702 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3704 if (!scop)
3705 return NULL;
3707 for (int i = 0; i < scop->n_stmt; ++i) {
3708 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3709 if (!scop->stmts[i])
3710 goto error;
3713 return scop;
3714 error:
3715 pet_scop_free(scop);
3716 return NULL;
3719 /* Given an access expression "expr", is the variable accessed by
3720 * "expr" assigned anywhere inside "scop"?
3722 static bool is_assigned(pet_expr *expr, pet_scop *scop)
3724 bool assigned = false;
3725 isl_id *id;
3727 id = isl_map_get_tuple_id(expr->acc.access, isl_dim_out);
3728 assigned = pet_scop_writes(scop, id);
3729 isl_id_free(id);
3731 return assigned;
3734 /* Are all nested access parameters in "pa" allowed given "scop".
3735 * In particular, is none of them written by anywhere inside "scop".
3737 * If "scop" has any skip conditions, then no nested access parameters
3738 * are allowed. In particular, if there is any nested access in a guard
3739 * for a piece of code containing a "continue", then we want to introduce
3740 * a separate statement for evaluating this guard so that we can express
3741 * that the result is false for all previous iterations.
3743 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3745 int nparam;
3747 if (!scop)
3748 return true;
3750 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3751 for (int i = 0; i < nparam; ++i) {
3752 Expr *nested;
3753 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3754 pet_expr *expr;
3755 bool allowed;
3757 if (!is_nested_parameter(id)) {
3758 isl_id_free(id);
3759 continue;
3762 if (pet_scop_has_skip(scop, pet_skip_now)) {
3763 isl_id_free(id);
3764 return false;
3767 nested = (Expr *) isl_id_get_user(id);
3768 expr = extract_expr(nested);
3769 allowed = expr && expr->type == pet_expr_access &&
3770 !is_assigned(expr, scop);
3772 pet_expr_free(expr);
3773 isl_id_free(id);
3775 if (!allowed)
3776 return false;
3779 return true;
3782 /* Do we need to construct a skip condition of the given type
3783 * on an if statement, given that the if condition is non-affine?
3785 * pet_scop_filter_skip can only handle the case where the if condition
3786 * holds (the then branch) and the skip condition is universal.
3787 * In any other case, we need to construct a new skip condition.
3789 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3790 bool have_else, enum pet_skip type)
3792 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
3793 return true;
3794 if (scop_then && pet_scop_has_skip(scop_then, type) &&
3795 !pet_scop_has_universal_skip(scop_then, type))
3796 return true;
3797 return false;
3800 /* Do we need to construct a skip condition of the given type
3801 * on an if statement, given that the if condition is affine?
3803 * There is no need to construct a new skip condition if all
3804 * the skip conditions are affine.
3806 static bool need_skip_aff(struct pet_scop *scop_then,
3807 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
3809 if (scop_then && pet_scop_has_var_skip(scop_then, type))
3810 return true;
3811 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
3812 return true;
3813 return false;
3816 /* Do we need to construct a skip condition of the given type
3817 * on an if statement?
3819 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3820 bool have_else, enum pet_skip type, bool affine)
3822 if (affine)
3823 return need_skip_aff(scop_then, scop_else, have_else, type);
3824 else
3825 return need_skip(scop_then, scop_else, have_else, type);
3828 /* Construct an affine expression pet_expr that is evaluates
3829 * to the constant "val".
3831 static struct pet_expr *universally(isl_ctx *ctx, int val)
3833 isl_space *space;
3834 isl_map *map;
3836 space = isl_space_alloc(ctx, 0, 0, 1);
3837 map = isl_map_universe(space);
3838 map = isl_map_fix_si(map, isl_dim_out, 0, val);
3840 return pet_expr_from_access(map);
3843 /* Construct an affine expression pet_expr that is evaluates
3844 * to the constant 1.
3846 static struct pet_expr *universally_true(isl_ctx *ctx)
3848 return universally(ctx, 1);
3851 /* Construct an affine expression pet_expr that is evaluates
3852 * to the constant 0.
3854 static struct pet_expr *universally_false(isl_ctx *ctx)
3856 return universally(ctx, 0);
3859 /* Given an access relation "test_access" for the if condition,
3860 * an access relation "skip_access" for the skip condition and
3861 * scops for the then and else branches, construct a scop for
3862 * computing "skip_access".
3864 * The computed scop contains a single statement that essentially does
3866 * skip_cond = test_cond ? skip_cond_then : skip_cond_else
3868 * If the skip conditions of the then and/or else branch are not affine,
3869 * then they need to be filtered by test_access.
3870 * If they are missing, then this means the skip condition is false.
3872 * Since we are constructing a skip condition for the if statement,
3873 * the skip conditions on the then and else branches are removed.
3875 static struct pet_scop *extract_skip(PetScan *scan,
3876 __isl_take isl_map *test_access, __isl_take isl_map *skip_access,
3877 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
3878 enum pet_skip type)
3880 struct pet_expr *expr_then, *expr_else, *expr, *expr_skip;
3881 struct pet_stmt *stmt;
3882 struct pet_scop *scop;
3883 isl_ctx *ctx = scan->ctx;
3885 if (!scop_then)
3886 goto error;
3887 if (have_else && !scop_else)
3888 goto error;
3890 if (pet_scop_has_skip(scop_then, type)) {
3891 expr_then = pet_scop_get_skip_expr(scop_then, type);
3892 pet_scop_reset_skip(scop_then, type);
3893 if (!pet_expr_is_affine(expr_then))
3894 expr_then = pet_expr_filter(expr_then,
3895 isl_map_copy(test_access), 1);
3896 } else
3897 expr_then = universally_false(ctx);
3899 if (have_else && pet_scop_has_skip(scop_else, type)) {
3900 expr_else = pet_scop_get_skip_expr(scop_else, type);
3901 pet_scop_reset_skip(scop_else, type);
3902 if (!pet_expr_is_affine(expr_else))
3903 expr_else = pet_expr_filter(expr_else,
3904 isl_map_copy(test_access), 0);
3905 } else
3906 expr_else = universally_false(ctx);
3908 expr = pet_expr_from_access(test_access);
3909 expr = pet_expr_new_ternary(ctx, expr, expr_then, expr_else);
3910 expr_skip = pet_expr_from_access(isl_map_copy(skip_access));
3911 if (expr_skip) {
3912 expr_skip->acc.write = 1;
3913 expr_skip->acc.read = 0;
3915 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
3916 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, scan->n_stmt++, expr);
3918 scop = pet_scop_from_pet_stmt(ctx, stmt);
3919 scop = scop_add_array(scop, skip_access, scan->ast_context);
3920 isl_map_free(skip_access);
3922 return scop;
3923 error:
3924 isl_map_free(test_access);
3925 isl_map_free(skip_access);
3926 return NULL;
3929 /* Is scop's skip_now condition equal to its skip_later condition?
3930 * In particular, this means that it either has no skip_now condition
3931 * or both a skip_now and a skip_later condition (that are equal to each other).
3933 static bool skip_equals_skip_later(struct pet_scop *scop)
3935 int has_skip_now, has_skip_later;
3936 int equal;
3937 isl_set *skip_now, *skip_later;
3939 if (!scop)
3940 return false;
3941 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
3942 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
3943 if (has_skip_now != has_skip_later)
3944 return false;
3945 if (!has_skip_now)
3946 return true;
3948 skip_now = pet_scop_get_skip(scop, pet_skip_now);
3949 skip_later = pet_scop_get_skip(scop, pet_skip_later);
3950 equal = isl_set_is_equal(skip_now, skip_later);
3951 isl_set_free(skip_now);
3952 isl_set_free(skip_later);
3954 return equal;
3957 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
3959 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
3961 pet_scop_reset_skip(scop1, pet_skip_later);
3962 pet_scop_reset_skip(scop2, pet_skip_later);
3965 /* Structure that handles the construction of skip conditions.
3967 * scop_then and scop_else represent the then and else branches
3968 * of the if statement
3970 * skip[type] is true if we need to construct a skip condition of that type
3971 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
3972 * are equal to each other
3973 * access[type] is the virtual array representing the skip condition
3974 * scop[type] is a scop for computing the skip condition
3976 struct pet_skip_info {
3977 isl_ctx *ctx;
3979 bool skip[2];
3980 bool equal;
3981 isl_map *access[2];
3982 struct pet_scop *scop[2];
3984 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
3986 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
3989 /* Structure that handles the construction of skip conditions on if statements.
3991 * scop_then and scop_else represent the then and else branches
3992 * of the if statement
3994 struct pet_skip_info_if : public pet_skip_info {
3995 struct pet_scop *scop_then, *scop_else;
3996 bool have_else;
3998 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
3999 struct pet_scop *scop_else, bool have_else, bool affine);
4000 void extract(PetScan *scan, __isl_keep isl_map *access,
4001 enum pet_skip type);
4002 void extract(PetScan *scan, __isl_keep isl_map *access);
4003 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
4004 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4005 int offset);
4006 struct pet_scop *add(struct pet_scop *scop, int offset);
4009 /* Initialize a pet_skip_info_if structure based on the then and else branches
4010 * and based on whether the if condition is affine or not.
4012 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4013 struct pet_scop *scop_else, bool have_else, bool affine) :
4014 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
4015 have_else(have_else)
4017 skip[pet_skip_now] =
4018 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
4019 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
4020 (!have_else || skip_equals_skip_later(scop_else));
4021 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4022 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
4025 /* If we need to construct a skip condition of the given type,
4026 * then do so now.
4028 * "map" represents the if condition.
4030 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_map *map,
4031 enum pet_skip type)
4033 if (!skip[type])
4034 return;
4036 access[type] = create_test_access(isl_map_get_ctx(map), scan->n_test++);
4037 scop[type] = extract_skip(scan, isl_map_copy(map),
4038 isl_map_copy(access[type]),
4039 scop_then, scop_else, have_else, type);
4042 /* Construct the required skip conditions, given the if condition "map".
4044 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_map *map)
4046 extract(scan, map, pet_skip_now);
4047 extract(scan, map, pet_skip_later);
4048 if (equal)
4049 drop_skip_later(scop_then, scop_else);
4052 /* Construct the required skip conditions, given the if condition "cond".
4054 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
4056 isl_set *test_set;
4057 isl_map *test;
4059 if (!skip[pet_skip_now] && !skip[pet_skip_later])
4060 return;
4062 test_set = isl_set_from_pw_aff(isl_pw_aff_copy(cond));
4063 test = isl_map_from_range(test_set);
4064 extract(scan, test);
4065 isl_map_free(test);
4068 /* Add the computed skip condition of the give type to "main" and
4069 * add the scop for computing the condition at the given offset.
4071 * If equal is set, then we only computed a skip condition for pet_skip_now,
4072 * but we also need to set it as main's pet_skip_later.
4074 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
4075 enum pet_skip type, int offset)
4077 isl_set *skip_set;
4079 if (!skip[type])
4080 return main;
4082 skip_set = isl_map_range(access[type]);
4083 access[type] = NULL;
4084 scop[type] = pet_scop_prefix(scop[type], offset);
4085 main = pet_scop_add_par(ctx, main, scop[type]);
4086 scop[type] = NULL;
4088 if (equal)
4089 main = pet_scop_set_skip(main, pet_skip_later,
4090 isl_set_copy(skip_set));
4092 main = pet_scop_set_skip(main, type, skip_set);
4094 return main;
4097 /* Add the computed skip conditions to "main" and
4098 * add the scops for computing the conditions at the given offset.
4100 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
4102 scop = add(scop, pet_skip_now, offset);
4103 scop = add(scop, pet_skip_later, offset);
4105 return scop;
4108 /* Construct a pet_scop for a non-affine if statement.
4110 * We create a separate statement that writes the result
4111 * of the non-affine condition to a virtual scalar.
4112 * A constraint requiring the value of this virtual scalar to be one
4113 * is added to the iteration domains of the then branch.
4114 * Similarly, a constraint requiring the value of this virtual scalar
4115 * to be zero is added to the iteration domains of the else branch, if any.
4116 * We adjust the schedules to ensure that the virtual scalar is written
4117 * before it is read.
4119 * If there are any breaks or continues in the then and/or else
4120 * branches, then we may have to compute a new skip condition.
4121 * This is handled using a pet_skip_info_if object.
4122 * On initialization, the object checks if skip conditions need
4123 * to be computed. If so, it does so in "extract" and adds them in "add".
4125 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
4126 struct pet_scop *scop_then, struct pet_scop *scop_else,
4127 bool have_else, int stmt_id)
4129 struct pet_scop *scop;
4130 isl_map *test_access;
4131 int save_n_stmt = n_stmt;
4133 test_access = create_test_access(ctx, n_test++);
4134 n_stmt = stmt_id;
4135 scop = extract_non_affine_condition(cond, isl_map_copy(test_access));
4136 n_stmt = save_n_stmt;
4137 scop = scop_add_array(scop, test_access, ast_context);
4139 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
4140 skip.extract(this, test_access);
4142 scop = pet_scop_prefix(scop, 0);
4143 scop_then = pet_scop_prefix(scop_then, 1);
4144 scop_then = pet_scop_filter(scop_then, isl_map_copy(test_access), 1);
4145 if (have_else) {
4146 scop_else = pet_scop_prefix(scop_else, 1);
4147 scop_else = pet_scop_filter(scop_else, test_access, 0);
4148 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
4149 } else
4150 isl_map_free(test_access);
4152 scop = pet_scop_add_seq(ctx, scop, scop_then);
4154 scop = skip.add(scop, 2);
4156 return scop;
4159 /* Construct a pet_scop for an if statement.
4161 * If the condition fits the pattern of a conditional assignment,
4162 * then it is handled by extract_conditional_assignment.
4163 * Otherwise, we do the following.
4165 * If the condition is affine, then the condition is added
4166 * to the iteration domains of the then branch, while the
4167 * opposite of the condition in added to the iteration domains
4168 * of the else branch, if any.
4169 * We allow the condition to be dynamic, i.e., to refer to
4170 * scalars or array elements that may be written to outside
4171 * of the given if statement. These nested accesses are then represented
4172 * as output dimensions in the wrapping iteration domain.
4173 * If it also written _inside_ the then or else branch, then
4174 * we treat the condition as non-affine.
4175 * As explained in extract_non_affine_if, this will introduce
4176 * an extra statement.
4177 * For aesthetic reasons, we want this statement to have a statement
4178 * number that is lower than those of the then and else branches.
4179 * In order to evaluate if will need such a statement, however, we
4180 * first construct scops for the then and else branches.
4181 * We therefore reserve a statement number if we might have to
4182 * introduce such an extra statement.
4184 * If the condition is not affine, then the scop is created in
4185 * extract_non_affine_if.
4187 * If there are any breaks or continues in the then and/or else
4188 * branches, then we may have to compute a new skip condition.
4189 * This is handled using a pet_skip_info_if object.
4190 * On initialization, the object checks if skip conditions need
4191 * to be computed. If so, it does so in "extract" and adds them in "add".
4193 struct pet_scop *PetScan::extract(IfStmt *stmt)
4195 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4196 isl_pw_aff *cond;
4197 int stmt_id;
4198 isl_set *set;
4199 isl_set *valid;
4201 scop = extract_conditional_assignment(stmt);
4202 if (scop)
4203 return scop;
4205 cond = try_extract_nested_condition(stmt->getCond());
4206 if (allow_nested && (!cond || has_nested(cond)))
4207 stmt_id = n_stmt++;
4210 assigned_value_cache cache(assigned_value);
4211 scop_then = extract(stmt->getThen());
4214 if (stmt->getElse()) {
4215 assigned_value_cache cache(assigned_value);
4216 scop_else = extract(stmt->getElse());
4217 if (options->autodetect) {
4218 if (scop_then && !scop_else) {
4219 partial = true;
4220 isl_pw_aff_free(cond);
4221 return scop_then;
4223 if (!scop_then && scop_else) {
4224 partial = true;
4225 isl_pw_aff_free(cond);
4226 return scop_else;
4231 if (cond &&
4232 (!is_nested_allowed(cond, scop_then) ||
4233 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4234 isl_pw_aff_free(cond);
4235 cond = NULL;
4237 if (allow_nested && !cond)
4238 return extract_non_affine_if(stmt->getCond(), scop_then,
4239 scop_else, stmt->getElse(), stmt_id);
4241 if (!cond)
4242 cond = extract_condition(stmt->getCond());
4244 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4245 skip.extract(this, cond);
4247 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4248 set = isl_pw_aff_non_zero_set(cond);
4249 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4251 if (stmt->getElse()) {
4252 set = isl_set_subtract(isl_set_copy(valid), set);
4253 scop_else = pet_scop_restrict(scop_else, set);
4254 scop = pet_scop_add_par(ctx, scop, scop_else);
4255 } else
4256 isl_set_free(set);
4257 scop = resolve_nested(scop);
4258 scop = pet_scop_restrict_context(scop, valid);
4260 if (skip)
4261 scop = pet_scop_prefix(scop, 0);
4262 scop = skip.add(scop, 1);
4264 return scop;
4267 /* Try and construct a pet_scop for a label statement.
4268 * We currently only allow labels on expression statements.
4270 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4272 isl_id *label;
4273 Stmt *sub;
4275 sub = stmt->getSubStmt();
4276 if (!isa<Expr>(sub)) {
4277 unsupported(stmt);
4278 return NULL;
4281 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4283 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4286 /* Construct a pet_scop for a continue statement.
4288 * We simply create an empty scop with a universal pet_skip_now
4289 * skip condition. This skip condition will then be taken into
4290 * account by the enclosing loop construct, possibly after
4291 * being incorporated into outer skip conditions.
4293 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4295 pet_scop *scop;
4296 isl_space *space;
4297 isl_set *set;
4299 scop = pet_scop_empty(ctx);
4300 if (!scop)
4301 return NULL;
4303 space = isl_space_set_alloc(ctx, 0, 1);
4304 set = isl_set_universe(space);
4305 set = isl_set_fix_si(set, isl_dim_set, 0, 1);
4306 scop = pet_scop_set_skip(scop, pet_skip_now, set);
4308 return scop;
4311 /* Construct a pet_scop for a break statement.
4313 * We simply create an empty scop with both a universal pet_skip_now
4314 * skip condition and a universal pet_skip_later skip condition.
4315 * These skip conditions will then be taken into
4316 * account by the enclosing loop construct, possibly after
4317 * being incorporated into outer skip conditions.
4319 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4321 pet_scop *scop;
4322 isl_space *space;
4323 isl_set *set;
4325 scop = pet_scop_empty(ctx);
4326 if (!scop)
4327 return NULL;
4329 space = isl_space_set_alloc(ctx, 0, 1);
4330 set = isl_set_universe(space);
4331 set = isl_set_fix_si(set, isl_dim_set, 0, 1);
4332 scop = pet_scop_set_skip(scop, pet_skip_now, isl_set_copy(set));
4333 scop = pet_scop_set_skip(scop, pet_skip_later, set);
4335 return scop;
4338 /* Try and construct a pet_scop corresponding to "stmt".
4340 * If "stmt" is a compound statement, then "skip_declarations"
4341 * indicates whether we should skip initial declarations in the
4342 * compound statement.
4344 * If the constructed pet_scop is not a (possibly) partial representation
4345 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4346 * In particular, if skip_declarations, then we may have skipped declarations
4347 * inside "stmt" and so the pet_scop may not represent the entire "stmt".
4348 * Note that this function may be called with "stmt" referring to the entire
4349 * body of the function, including the outer braces. In such cases,
4350 * skip_declarations will be set and the braces will not be taken into
4351 * account in scop->start and scop->end.
4353 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
4355 struct pet_scop *scop;
4356 unsigned start, end;
4357 SourceLocation loc;
4358 SourceManager &SM = PP.getSourceManager();
4360 if (isa<Expr>(stmt))
4361 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4363 switch (stmt->getStmtClass()) {
4364 case Stmt::WhileStmtClass:
4365 scop = extract(cast<WhileStmt>(stmt));
4366 break;
4367 case Stmt::ForStmtClass:
4368 scop = extract_for(cast<ForStmt>(stmt));
4369 break;
4370 case Stmt::IfStmtClass:
4371 scop = extract(cast<IfStmt>(stmt));
4372 break;
4373 case Stmt::CompoundStmtClass:
4374 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
4375 break;
4376 case Stmt::LabelStmtClass:
4377 scop = extract(cast<LabelStmt>(stmt));
4378 break;
4379 case Stmt::ContinueStmtClass:
4380 scop = extract(cast<ContinueStmt>(stmt));
4381 break;
4382 case Stmt::BreakStmtClass:
4383 scop = extract(cast<BreakStmt>(stmt));
4384 break;
4385 case Stmt::DeclStmtClass:
4386 scop = extract(cast<DeclStmt>(stmt));
4387 break;
4388 default:
4389 unsupported(stmt);
4390 return NULL;
4393 if (partial || skip_declarations)
4394 return scop;
4396 start = getExpansionOffset(SM, stmt->getLocStart());
4397 loc = PP.getLocForEndOfToken(stmt->getLocEnd());
4398 end = getExpansionOffset(SM, loc);
4399 scop = pet_scop_update_start_end(scop, start, end);
4401 return scop;
4404 /* Do we need to construct a skip condition of the given type
4405 * on a sequence of statements?
4407 * There is no need to construct a new skip condition if only
4408 * only of the two statements has a skip condition or if both
4409 * of their skip conditions are affine.
4411 * In principle we also don't need a new continuation variable if
4412 * the continuation of scop2 is affine, but then we would need
4413 * to allow more complicated forms of continuations.
4415 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4416 enum pet_skip type)
4418 if (!scop1 || !pet_scop_has_skip(scop1, type))
4419 return false;
4420 if (!scop2 || !pet_scop_has_skip(scop2, type))
4421 return false;
4422 if (pet_scop_has_affine_skip(scop1, type) &&
4423 pet_scop_has_affine_skip(scop2, type))
4424 return false;
4425 return true;
4428 /* Construct a scop for computing the skip condition of the given type and
4429 * with access relation "skip_access" for a sequence of two scops "scop1"
4430 * and "scop2".
4432 * The computed scop contains a single statement that essentially does
4434 * skip_cond = skip_cond_1 ? 1 : skip_cond_2
4436 * or, in other words, skip_cond1 || skip_cond2.
4437 * In this expression, skip_cond_2 is filtered to reflect that it is
4438 * only evaluated when skip_cond_1 is false.
4440 * The skip condition on scop1 is not removed because it still needs
4441 * to be applied to scop2 when these two scops are combined.
4443 static struct pet_scop *extract_skip_seq(PetScan *ps,
4444 __isl_take isl_map *skip_access,
4445 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4447 isl_map *access;
4448 struct pet_expr *expr1, *expr2, *expr, *expr_skip;
4449 struct pet_stmt *stmt;
4450 struct pet_scop *scop;
4451 isl_ctx *ctx = ps->ctx;
4453 if (!scop1 || !scop2)
4454 goto error;
4456 expr1 = pet_scop_get_skip_expr(scop1, type);
4457 expr2 = pet_scop_get_skip_expr(scop2, type);
4458 pet_scop_reset_skip(scop2, type);
4460 expr2 = pet_expr_filter(expr2, isl_map_copy(expr1->acc.access), 0);
4462 expr = universally_true(ctx);
4463 expr = pet_expr_new_ternary(ctx, expr1, expr, expr2);
4464 expr_skip = pet_expr_from_access(isl_map_copy(skip_access));
4465 if (expr_skip) {
4466 expr_skip->acc.write = 1;
4467 expr_skip->acc.read = 0;
4469 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4470 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, ps->n_stmt++, expr);
4472 scop = pet_scop_from_pet_stmt(ctx, stmt);
4473 scop = scop_add_array(scop, skip_access, ps->ast_context);
4474 isl_map_free(skip_access);
4476 return scop;
4477 error:
4478 isl_map_free(skip_access);
4479 return NULL;
4482 /* Structure that handles the construction of skip conditions
4483 * on sequences of statements.
4485 * scop1 and scop2 represent the two statements that are combined
4487 struct pet_skip_info_seq : public pet_skip_info {
4488 struct pet_scop *scop1, *scop2;
4490 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4491 struct pet_scop *scop2);
4492 void extract(PetScan *scan, enum pet_skip type);
4493 void extract(PetScan *scan);
4494 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4495 int offset);
4496 struct pet_scop *add(struct pet_scop *scop, int offset);
4499 /* Initialize a pet_skip_info_seq structure based on
4500 * on the two statements that are going to be combined.
4502 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4503 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
4505 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
4506 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
4507 skip_equals_skip_later(scop2);
4508 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4509 need_skip_seq(scop1, scop2, pet_skip_later);
4512 /* If we need to construct a skip condition of the given type,
4513 * then do so now.
4515 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
4517 if (!skip[type])
4518 return;
4520 access[type] = create_test_access(ctx, scan->n_test++);
4521 scop[type] = extract_skip_seq(scan, isl_map_copy(access[type]),
4522 scop1, scop2, type);
4525 /* Construct the required skip conditions.
4527 void pet_skip_info_seq::extract(PetScan *scan)
4529 extract(scan, pet_skip_now);
4530 extract(scan, pet_skip_later);
4531 if (equal)
4532 drop_skip_later(scop1, scop2);
4535 /* Add the computed skip condition of the give type to "main" and
4536 * add the scop for computing the condition at the given offset (the statement
4537 * number). Within this offset, the condition is computed at position 1
4538 * to ensure that it is computed after the corresponding statement.
4540 * If equal is set, then we only computed a skip condition for pet_skip_now,
4541 * but we also need to set it as main's pet_skip_later.
4543 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
4544 enum pet_skip type, int offset)
4546 isl_set *skip_set;
4548 if (!skip[type])
4549 return main;
4551 skip_set = isl_map_range(access[type]);
4552 access[type] = NULL;
4553 scop[type] = pet_scop_prefix(scop[type], 1);
4554 scop[type] = pet_scop_prefix(scop[type], offset);
4555 main = pet_scop_add_par(ctx, main, scop[type]);
4556 scop[type] = NULL;
4558 if (equal)
4559 main = pet_scop_set_skip(main, pet_skip_later,
4560 isl_set_copy(skip_set));
4562 main = pet_scop_set_skip(main, type, skip_set);
4564 return main;
4567 /* Add the computed skip conditions to "main" and
4568 * add the scops for computing the conditions at the given offset.
4570 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
4572 scop = add(scop, pet_skip_now, offset);
4573 scop = add(scop, pet_skip_later, offset);
4575 return scop;
4578 /* Extract a clone of the kill statement in "scop".
4579 * "scop" is expected to have been created from a DeclStmt
4580 * and should have the kill as its first statement.
4582 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
4584 struct pet_expr *kill;
4585 struct pet_stmt *stmt;
4586 isl_map *access;
4588 if (!scop)
4589 return NULL;
4590 if (scop->n_stmt < 1)
4591 isl_die(ctx, isl_error_internal,
4592 "expecting at least one statement", return NULL);
4593 stmt = scop->stmts[0];
4594 if (stmt->body->type != pet_expr_unary ||
4595 stmt->body->op != pet_op_kill)
4596 isl_die(ctx, isl_error_internal,
4597 "expecting kill statement", return NULL);
4599 access = isl_map_copy(stmt->body->args[0]->acc.access);
4600 access = isl_map_reset_tuple_id(access, isl_dim_in);
4601 kill = pet_expr_kill_from_access(access);
4602 return pet_stmt_from_pet_expr(ctx, stmt->line, NULL, n_stmt++, kill);
4605 /* Mark all arrays in "scop" as being exposed.
4607 static struct pet_scop *mark_exposed(struct pet_scop *scop)
4609 if (!scop)
4610 return NULL;
4611 for (int i = 0; i < scop->n_array; ++i)
4612 scop->arrays[i]->exposed = 1;
4613 return scop;
4616 /* Try and construct a pet_scop corresponding to (part of)
4617 * a sequence of statements.
4619 * "block" is set if the sequence respresents the children of
4620 * a compound statement.
4621 * "skip_declarations" is set if we should skip initial declarations
4622 * in the sequence of statements.
4624 * If there are any breaks or continues in the individual statements,
4625 * then we may have to compute a new skip condition.
4626 * This is handled using a pet_skip_info_seq object.
4627 * On initialization, the object checks if skip conditions need
4628 * to be computed. If so, it does so in "extract" and adds them in "add".
4630 * If "block" is set, then we need to insert kill statements at
4631 * the end of the block for any array that has been declared by
4632 * one of the statements in the sequence. Each of these declarations
4633 * results in the construction of a kill statement at the place
4634 * of the declaration, so we simply collect duplicates of
4635 * those kill statements and append these duplicates to the constructed scop.
4637 * If "block" is not set, then any array declared by one of the statements
4638 * in the sequence is marked as being exposed.
4640 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
4641 bool skip_declarations)
4643 pet_scop *scop;
4644 StmtIterator i;
4645 int j;
4646 bool partial_range = false;
4647 set<struct pet_stmt *> kills;
4648 set<struct pet_stmt *>::iterator it;
4650 scop = pet_scop_empty(ctx);
4651 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4652 Stmt *child = *i;
4653 struct pet_scop *scop_i;
4655 if (skip_declarations &&
4656 child->getStmtClass() == Stmt::DeclStmtClass)
4657 continue;
4659 scop_i = extract(child);
4660 if (scop && partial) {
4661 pet_scop_free(scop_i);
4662 break;
4664 pet_skip_info_seq skip(ctx, scop, scop_i);
4665 skip.extract(this);
4666 if (skip)
4667 scop_i = pet_scop_prefix(scop_i, 0);
4668 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4669 if (block)
4670 kills.insert(extract_kill(scop_i));
4671 else
4672 scop_i = mark_exposed(scop_i);
4674 scop_i = pet_scop_prefix(scop_i, j);
4675 if (options->autodetect) {
4676 if (scop_i)
4677 scop = pet_scop_add_seq(ctx, scop, scop_i);
4678 else
4679 partial_range = true;
4680 if (scop->n_stmt != 0 && !scop_i)
4681 partial = true;
4682 } else {
4683 scop = pet_scop_add_seq(ctx, scop, scop_i);
4686 scop = skip.add(scop, j);
4688 if (partial)
4689 break;
4692 for (it = kills.begin(); it != kills.end(); ++it) {
4693 pet_scop *scop_j;
4694 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4695 scop_j = pet_scop_prefix(scop_j, j);
4696 scop = pet_scop_add_seq(ctx, scop, scop_j);
4699 if (scop && partial_range)
4700 partial = true;
4702 return scop;
4705 /* Check if the scop marked by the user is exactly this Stmt
4706 * or part of this Stmt.
4707 * If so, return a pet_scop corresponding to the marked region.
4708 * Otherwise, return NULL.
4710 struct pet_scop *PetScan::scan(Stmt *stmt)
4712 SourceManager &SM = PP.getSourceManager();
4713 unsigned start_off, end_off;
4715 start_off = getExpansionOffset(SM, stmt->getLocStart());
4716 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4718 if (start_off > loc.end)
4719 return NULL;
4720 if (end_off < loc.start)
4721 return NULL;
4722 if (start_off >= loc.start && end_off <= loc.end) {
4723 return extract(stmt);
4726 StmtIterator start;
4727 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4728 Stmt *child = *start;
4729 if (!child)
4730 continue;
4731 start_off = getExpansionOffset(SM, child->getLocStart());
4732 end_off = getExpansionOffset(SM, child->getLocEnd());
4733 if (start_off < loc.start && end_off > loc.end)
4734 return scan(child);
4735 if (start_off >= loc.start)
4736 break;
4739 StmtIterator end;
4740 for (end = start; end != stmt->child_end(); ++end) {
4741 Stmt *child = *end;
4742 start_off = SM.getFileOffset(child->getLocStart());
4743 if (start_off >= loc.end)
4744 break;
4747 return extract(StmtRange(start, end), false, false);
4750 /* Set the size of index "pos" of "array" to "size".
4751 * In particular, add a constraint of the form
4753 * i_pos < size
4755 * to array->extent and a constraint of the form
4757 * size >= 0
4759 * to array->context.
4761 static struct pet_array *update_size(struct pet_array *array, int pos,
4762 __isl_take isl_pw_aff *size)
4764 isl_set *valid;
4765 isl_set *univ;
4766 isl_set *bound;
4767 isl_space *dim;
4768 isl_aff *aff;
4769 isl_pw_aff *index;
4770 isl_id *id;
4772 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
4773 array->context = isl_set_intersect(array->context, valid);
4775 dim = isl_set_get_space(array->extent);
4776 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
4777 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
4778 univ = isl_set_universe(isl_aff_get_domain_space(aff));
4779 index = isl_pw_aff_alloc(univ, aff);
4781 size = isl_pw_aff_add_dims(size, isl_dim_in,
4782 isl_set_dim(array->extent, isl_dim_set));
4783 id = isl_set_get_tuple_id(array->extent);
4784 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
4785 bound = isl_pw_aff_lt_set(index, size);
4787 array->extent = isl_set_intersect(array->extent, bound);
4789 if (!array->context || !array->extent)
4790 goto error;
4792 return array;
4793 error:
4794 pet_array_free(array);
4795 return NULL;
4798 /* Figure out the size of the array at position "pos" and all
4799 * subsequent positions from "type" and update "array" accordingly.
4801 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
4802 const Type *type, int pos)
4804 const ArrayType *atype;
4805 isl_pw_aff *size;
4807 if (!array)
4808 return NULL;
4810 if (type->isPointerType()) {
4811 type = type->getPointeeType().getTypePtr();
4812 return set_upper_bounds(array, type, pos + 1);
4814 if (!type->isArrayType())
4815 return array;
4817 type = type->getCanonicalTypeInternal().getTypePtr();
4818 atype = cast<ArrayType>(type);
4820 if (type->isConstantArrayType()) {
4821 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
4822 size = extract_affine(ca->getSize());
4823 array = update_size(array, pos, size);
4824 } else if (type->isVariableArrayType()) {
4825 const VariableArrayType *vla = cast<VariableArrayType>(atype);
4826 size = extract_affine(vla->getSizeExpr());
4827 array = update_size(array, pos, size);
4830 type = atype->getElementType().getTypePtr();
4832 return set_upper_bounds(array, type, pos + 1);
4835 /* Is "T" the type of a variable length array with static size?
4837 static bool is_vla_with_static_size(QualType T)
4839 const VariableArrayType *vlatype;
4841 if (!T->isVariableArrayType())
4842 return false;
4843 vlatype = cast<VariableArrayType>(T);
4844 return vlatype->getSizeModifier() == VariableArrayType::Static;
4847 /* Return the type of "decl" as an array.
4849 * In particular, if "decl" is a parameter declaration that
4850 * is a variable length array with a static size, then
4851 * return the original type (i.e., the variable length array).
4852 * Otherwise, return the type of decl.
4854 static QualType get_array_type(ValueDecl *decl)
4856 ParmVarDecl *parm;
4857 QualType T;
4859 parm = dyn_cast<ParmVarDecl>(decl);
4860 if (!parm)
4861 return decl->getType();
4863 T = parm->getOriginalType();
4864 if (!is_vla_with_static_size(T))
4865 return decl->getType();
4866 return T;
4869 /* Construct and return a pet_array corresponding to the variable "decl".
4870 * In particular, initialize array->extent to
4872 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4874 * and then call set_upper_bounds to set the upper bounds on the indices
4875 * based on the type of the variable.
4877 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
4879 struct pet_array *array;
4880 QualType qt = get_array_type(decl);
4881 const Type *type = qt.getTypePtr();
4882 int depth = array_depth(type);
4883 QualType base = base_type(qt);
4884 string name;
4885 isl_id *id;
4886 isl_space *dim;
4888 array = isl_calloc_type(ctx, struct pet_array);
4889 if (!array)
4890 return NULL;
4892 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
4893 dim = isl_space_set_alloc(ctx, 0, depth);
4894 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
4896 array->extent = isl_set_nat_universe(dim);
4898 dim = isl_space_params_alloc(ctx, 0);
4899 array->context = isl_set_universe(dim);
4901 array = set_upper_bounds(array, type, 0);
4902 if (!array)
4903 return NULL;
4905 name = base.getAsString();
4906 array->element_type = strdup(name.c_str());
4907 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
4909 return array;
4912 /* Construct a list of pet_arrays, one for each array (or scalar)
4913 * accessed inside "scop", add this list to "scop" and return the result.
4915 * The context of "scop" is updated with the intersection of
4916 * the contexts of all arrays, i.e., constraints on the parameters
4917 * that ensure that the arrays have a valid (non-negative) size.
4919 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
4921 int i;
4922 set<ValueDecl *> arrays;
4923 set<ValueDecl *>::iterator it;
4924 int n_array;
4925 struct pet_array **scop_arrays;
4927 if (!scop)
4928 return NULL;
4930 pet_scop_collect_arrays(scop, arrays);
4931 if (arrays.size() == 0)
4932 return scop;
4934 n_array = scop->n_array;
4936 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
4937 n_array + arrays.size());
4938 if (!scop_arrays)
4939 goto error;
4940 scop->arrays = scop_arrays;
4942 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
4943 struct pet_array *array;
4944 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
4945 if (!scop->arrays[n_array + i])
4946 goto error;
4947 scop->n_array++;
4948 scop->context = isl_set_intersect(scop->context,
4949 isl_set_copy(array->context));
4950 if (!scop->context)
4951 goto error;
4954 return scop;
4955 error:
4956 pet_scop_free(scop);
4957 return NULL;
4960 /* Bound all parameters in scop->context to the possible values
4961 * of the corresponding C variable.
4963 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
4965 int n;
4967 if (!scop)
4968 return NULL;
4970 n = isl_set_dim(scop->context, isl_dim_param);
4971 for (int i = 0; i < n; ++i) {
4972 isl_id *id;
4973 ValueDecl *decl;
4975 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
4976 if (is_nested_parameter(id)) {
4977 isl_id_free(id);
4978 isl_die(isl_set_get_ctx(scop->context),
4979 isl_error_internal,
4980 "unresolved nested parameter", goto error);
4982 decl = (ValueDecl *) isl_id_get_user(id);
4983 isl_id_free(id);
4985 scop->context = set_parameter_bounds(scop->context, i, decl);
4987 if (!scop->context)
4988 goto error;
4991 return scop;
4992 error:
4993 pet_scop_free(scop);
4994 return NULL;
4997 /* Construct a pet_scop from the given function.
4999 * If the scop was delimited by scop and endscop pragmas, then we override
5000 * the file offsets by those derived from the pragmas.
5002 struct pet_scop *PetScan::scan(FunctionDecl *fd)
5004 pet_scop *scop;
5005 Stmt *stmt;
5007 stmt = fd->getBody();
5009 if (options->autodetect)
5010 scop = extract(stmt, true);
5011 else {
5012 scop = scan(stmt);
5013 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
5015 scop = pet_scop_detect_parameter_accesses(scop);
5016 scop = scan_arrays(scop);
5017 scop = add_parameter_bounds(scop);
5018 scop = pet_scop_gist(scop, value_bounds);
5020 return scop;