PetScan::extract_non_affine_condition: take index expression
[pet.git] / scan.cc
blobbf1a8875ccc738b005b39299fe9c4479665ec910
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012 Ecole Normale Superieure. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
32 * Leiden University.
33 */
35 #include <string.h>
36 #include <set>
37 #include <map>
38 #include <iostream>
39 #include <llvm/Support/raw_ostream.h>
40 #include <clang/AST/ASTContext.h>
41 #include <clang/AST/ASTDiagnostic.h>
42 #include <clang/AST/Expr.h>
43 #include <clang/AST/RecursiveASTVisitor.h>
45 #include <isl/id.h>
46 #include <isl/space.h>
47 #include <isl/aff.h>
48 #include <isl/set.h>
50 #include "options.h"
51 #include "scan.h"
52 #include "scop.h"
53 #include "scop_plus.h"
55 #include "config.h"
57 using namespace std;
58 using namespace clang;
60 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
61 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
63 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
64 SourceLocation(), var, false, var->getInnerLocStart(),
65 var->getType(), VK_LValue);
67 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
68 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
70 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
71 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
72 VK_LValue);
74 #else
75 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
77 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
78 var, var->getInnerLocStart(), var->getType(), VK_LValue);
80 #endif
82 /* Check if the element type corresponding to the given array type
83 * has a const qualifier.
85 static bool const_base(QualType qt)
87 const Type *type = qt.getTypePtr();
89 if (type->isPointerType())
90 return const_base(type->getPointeeType());
91 if (type->isArrayType()) {
92 const ArrayType *atype;
93 type = type->getCanonicalTypeInternal().getTypePtr();
94 atype = cast<ArrayType>(type);
95 return const_base(atype->getElementType());
98 return qt.isConstQualified();
101 /* Mark "decl" as having an unknown value in "assigned_value".
103 * If no (known or unknown) value was assigned to "decl" before,
104 * then it may have been treated as a parameter before and may
105 * therefore appear in a value assigned to another variable.
106 * If so, this assignment needs to be turned into an unknown value too.
108 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
109 ValueDecl *decl)
111 map<ValueDecl *, isl_pw_aff *>::iterator it;
113 it = assigned_value.find(decl);
115 assigned_value[decl] = NULL;
117 if (it == assigned_value.end())
118 return;
120 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
121 isl_pw_aff *pa = it->second;
122 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
124 for (int i = 0; i < nparam; ++i) {
125 isl_id *id;
127 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
128 continue;
129 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
130 if (isl_id_get_user(id) == decl)
131 it->second = NULL;
132 isl_id_free(id);
137 /* Look for any assignments to scalar variables in part of the parse
138 * tree and set assigned_value to NULL for each of them.
139 * Also reset assigned_value if the address of a scalar variable
140 * is being taken. As an exception, if the address is passed to a function
141 * that is declared to receive a const pointer, then assigned_value is
142 * not reset.
144 * This ensures that we won't use any previously stored value
145 * in the current subtree and its parents.
147 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
148 map<ValueDecl *, isl_pw_aff *> &assigned_value;
149 set<UnaryOperator *> skip;
151 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
152 assigned_value(assigned_value) {}
154 /* Check for "address of" operators whose value is passed
155 * to a const pointer argument and add them to "skip", so that
156 * we can skip them in VisitUnaryOperator.
158 bool VisitCallExpr(CallExpr *expr) {
159 FunctionDecl *fd;
160 fd = expr->getDirectCallee();
161 if (!fd)
162 return true;
163 for (int i = 0; i < expr->getNumArgs(); ++i) {
164 Expr *arg = expr->getArg(i);
165 UnaryOperator *op;
166 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
167 ImplicitCastExpr *ice;
168 ice = cast<ImplicitCastExpr>(arg);
169 arg = ice->getSubExpr();
171 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
172 continue;
173 op = cast<UnaryOperator>(arg);
174 if (op->getOpcode() != UO_AddrOf)
175 continue;
176 if (const_base(fd->getParamDecl(i)->getType()))
177 skip.insert(op);
179 return true;
182 bool VisitUnaryOperator(UnaryOperator *expr) {
183 Expr *arg;
184 DeclRefExpr *ref;
185 ValueDecl *decl;
187 switch (expr->getOpcode()) {
188 case UO_AddrOf:
189 case UO_PostInc:
190 case UO_PostDec:
191 case UO_PreInc:
192 case UO_PreDec:
193 break;
194 default:
195 return true;
197 if (skip.find(expr) != skip.end())
198 return true;
200 arg = expr->getSubExpr();
201 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
202 return true;
203 ref = cast<DeclRefExpr>(arg);
204 decl = ref->getDecl();
205 clear_assignment(assigned_value, decl);
206 return true;
209 bool VisitBinaryOperator(BinaryOperator *expr) {
210 Expr *lhs;
211 DeclRefExpr *ref;
212 ValueDecl *decl;
214 if (!expr->isAssignmentOp())
215 return true;
216 lhs = expr->getLHS();
217 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
218 return true;
219 ref = cast<DeclRefExpr>(lhs);
220 decl = ref->getDecl();
221 clear_assignment(assigned_value, decl);
222 return true;
226 /* Keep a copy of the currently assigned values.
228 * Any variable that is assigned a value inside the current scope
229 * is removed again when we leave the scope (either because it wasn't
230 * stored in the cache or because it has a different value in the cache).
232 struct assigned_value_cache {
233 map<ValueDecl *, isl_pw_aff *> &assigned_value;
234 map<ValueDecl *, isl_pw_aff *> cache;
236 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
237 assigned_value(assigned_value), cache(assigned_value) {}
238 ~assigned_value_cache() {
239 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
240 for (it = assigned_value.begin(); it != assigned_value.end();
241 ++it) {
242 if (!it->second ||
243 (cache.find(it->first) != cache.end() &&
244 cache[it->first] != it->second))
245 cache[it->first] = NULL;
247 assigned_value = cache;
251 /* Insert an expression into the collection of expressions,
252 * provided it is not already in there.
253 * The isl_pw_affs are freed in the destructor.
255 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
257 std::set<isl_pw_aff *>::iterator it;
259 if (expressions.find(expr) == expressions.end())
260 expressions.insert(expr);
261 else
262 isl_pw_aff_free(expr);
265 PetScan::~PetScan()
267 std::set<isl_pw_aff *>::iterator it;
269 for (it = expressions.begin(); it != expressions.end(); ++it)
270 isl_pw_aff_free(*it);
272 isl_union_map_free(value_bounds);
275 /* Called if we found something we (currently) cannot handle.
276 * We'll provide more informative warnings later.
278 * We only actually complain if autodetect is false.
280 void PetScan::unsupported(Stmt *stmt, const char *msg)
282 if (options->autodetect)
283 return;
285 SourceLocation loc = stmt->getLocStart();
286 DiagnosticsEngine &diag = PP.getDiagnostics();
287 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
288 msg ? msg : "unsupported");
289 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
292 /* Extract an integer from "expr".
294 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
296 const Type *type = expr->getType().getTypePtr();
297 int is_signed = type->hasSignedIntegerRepresentation();
298 llvm::APInt val = expr->getValue();
299 int is_negative = is_signed && val.isNegative();
300 isl_val *v;
302 if (is_negative)
303 val = -val;
305 v = extract_unsigned(ctx, val);
307 if (is_negative)
308 v = isl_val_neg(v);
309 return v;
312 /* Extract an integer from "val", which assumed to be non-negative.
314 __isl_give isl_val *PetScan::extract_unsigned(isl_ctx *ctx,
315 const llvm::APInt &val)
317 unsigned n;
318 const uint64_t *data;
320 data = val.getRawData();
321 n = val.getNumWords();
322 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
325 /* Extract an integer from "expr".
326 * Return NULL if "expr" does not (obviously) represent an integer.
328 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
330 return extract_int(expr->getSubExpr());
333 /* Extract an integer from "expr".
334 * Return NULL if "expr" does not (obviously) represent an integer.
336 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
338 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
339 return extract_int(ctx, cast<IntegerLiteral>(expr));
340 if (expr->getStmtClass() == Stmt::ParenExprClass)
341 return extract_int(cast<ParenExpr>(expr));
343 unsupported(expr);
344 return NULL;
347 /* Extract an affine expression from the IntegerLiteral "expr".
349 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
351 isl_space *dim = isl_space_params_alloc(ctx, 0);
352 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
353 isl_aff *aff = isl_aff_zero_on_domain(ls);
354 isl_set *dom = isl_set_universe(dim);
355 isl_val *v;
357 v = extract_int(expr);
358 aff = isl_aff_add_constant_val(aff, v);
360 return isl_pw_aff_alloc(dom, aff);
363 /* Extract an affine expression from the APInt "val", which is assumed
364 * to be non-negative.
366 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
368 isl_space *dim = isl_space_params_alloc(ctx, 0);
369 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
370 isl_aff *aff = isl_aff_zero_on_domain(ls);
371 isl_set *dom = isl_set_universe(dim);
372 isl_val *v;
374 v = extract_unsigned(ctx, val);
375 aff = isl_aff_add_constant_val(aff, v);
377 return isl_pw_aff_alloc(dom, aff);
380 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
382 return extract_affine(expr->getSubExpr());
385 static unsigned get_type_size(ValueDecl *decl)
387 return decl->getASTContext().getIntWidth(decl->getType());
390 /* Bound parameter "pos" of "set" to the possible values of "decl".
392 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
393 unsigned pos, ValueDecl *decl)
395 unsigned width;
396 isl_ctx *ctx;
397 isl_val *bound;
399 ctx = isl_set_get_ctx(set);
400 width = get_type_size(decl);
401 if (decl->getType()->isUnsignedIntegerType()) {
402 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
403 bound = isl_val_int_from_ui(ctx, width);
404 bound = isl_val_2exp(bound);
405 bound = isl_val_sub_ui(bound, 1);
406 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
407 } else {
408 bound = isl_val_int_from_ui(ctx, width - 1);
409 bound = isl_val_2exp(bound);
410 bound = isl_val_sub_ui(bound, 1);
411 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
412 isl_val_copy(bound));
413 bound = isl_val_neg(bound);
414 bound = isl_val_sub_ui(bound, 1);
415 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
418 return set;
421 /* Extract an affine expression from the DeclRefExpr "expr".
423 * If the variable has been assigned a value, then we check whether
424 * we know what (affine) value was assigned.
425 * If so, we return this value. Otherwise we convert "expr"
426 * to an extra parameter (provided nesting_enabled is set).
428 * Otherwise, we simply return an expression that is equal
429 * to a parameter corresponding to the referenced variable.
431 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
433 ValueDecl *decl = expr->getDecl();
434 const Type *type = decl->getType().getTypePtr();
435 isl_id *id;
436 isl_space *dim;
437 isl_aff *aff;
438 isl_set *dom;
440 if (!type->isIntegerType()) {
441 unsupported(expr);
442 return NULL;
445 if (assigned_value.find(decl) != assigned_value.end()) {
446 if (assigned_value[decl])
447 return isl_pw_aff_copy(assigned_value[decl]);
448 else
449 return nested_access(expr);
452 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
453 dim = isl_space_params_alloc(ctx, 1);
455 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
457 dom = isl_set_universe(isl_space_copy(dim));
458 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
459 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
461 return isl_pw_aff_alloc(dom, aff);
464 /* Extract an affine expression from an integer division operation.
465 * In particular, if "expr" is lhs/rhs, then return
467 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
469 * The second argument (rhs) is required to be a (positive) integer constant.
471 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
473 int is_cst;
474 isl_pw_aff *rhs, *lhs;
476 rhs = extract_affine(expr->getRHS());
477 is_cst = isl_pw_aff_is_cst(rhs);
478 if (is_cst < 0 || !is_cst) {
479 isl_pw_aff_free(rhs);
480 if (!is_cst)
481 unsupported(expr);
482 return NULL;
485 lhs = extract_affine(expr->getLHS());
487 return isl_pw_aff_tdiv_q(lhs, rhs);
490 /* Extract an affine expression from a modulo operation.
491 * In particular, if "expr" is lhs/rhs, then return
493 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
495 * The second argument (rhs) is required to be a (positive) integer constant.
497 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
499 int is_cst;
500 isl_pw_aff *rhs, *lhs;
502 rhs = extract_affine(expr->getRHS());
503 is_cst = isl_pw_aff_is_cst(rhs);
504 if (is_cst < 0 || !is_cst) {
505 isl_pw_aff_free(rhs);
506 if (!is_cst)
507 unsupported(expr);
508 return NULL;
511 lhs = extract_affine(expr->getLHS());
513 return isl_pw_aff_tdiv_r(lhs, rhs);
516 /* Extract an affine expression from a multiplication operation.
517 * This is only allowed if at least one of the two arguments
518 * is a (piecewise) constant.
520 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
522 isl_pw_aff *lhs;
523 isl_pw_aff *rhs;
525 lhs = extract_affine(expr->getLHS());
526 rhs = extract_affine(expr->getRHS());
528 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
529 isl_pw_aff_free(lhs);
530 isl_pw_aff_free(rhs);
531 unsupported(expr);
532 return NULL;
535 return isl_pw_aff_mul(lhs, rhs);
538 /* Extract an affine expression from an addition or subtraction operation.
540 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
542 isl_pw_aff *lhs;
543 isl_pw_aff *rhs;
545 lhs = extract_affine(expr->getLHS());
546 rhs = extract_affine(expr->getRHS());
548 switch (expr->getOpcode()) {
549 case BO_Add:
550 return isl_pw_aff_add(lhs, rhs);
551 case BO_Sub:
552 return isl_pw_aff_sub(lhs, rhs);
553 default:
554 isl_pw_aff_free(lhs);
555 isl_pw_aff_free(rhs);
556 return NULL;
561 /* Compute
563 * pwaff mod 2^width
565 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
566 unsigned width)
568 isl_ctx *ctx;
569 isl_val *mod;
571 ctx = isl_pw_aff_get_ctx(pwaff);
572 mod = isl_val_int_from_ui(ctx, width);
573 mod = isl_val_2exp(mod);
575 pwaff = isl_pw_aff_mod_val(pwaff, mod);
577 return pwaff;
580 /* Limit the domain of "pwaff" to those elements where the function
581 * value satisfies
583 * 2^{width-1} <= pwaff < 2^{width-1}
585 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
586 unsigned width)
588 isl_ctx *ctx;
589 isl_val *v;
590 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
591 isl_local_space *ls = isl_local_space_from_space(space);
592 isl_aff *bound;
593 isl_set *dom;
594 isl_pw_aff *b;
596 ctx = isl_pw_aff_get_ctx(pwaff);
597 v = isl_val_int_from_ui(ctx, width - 1);
598 v = isl_val_2exp(v);
600 bound = isl_aff_zero_on_domain(ls);
601 bound = isl_aff_add_constant_val(bound, v);
602 b = isl_pw_aff_from_aff(bound);
604 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
605 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
607 b = isl_pw_aff_neg(b);
608 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
609 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
611 return pwaff;
614 /* Handle potential overflows on signed computations.
616 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
617 * the we adjust the domain of "pa" to avoid overflows.
619 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
620 unsigned width)
622 if (options->signed_overflow == PET_OVERFLOW_AVOID)
623 pa = avoid_overflow(pa, width);
625 return pa;
628 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
630 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
631 __isl_take isl_set *dom)
633 isl_pw_aff *pa;
634 pa = isl_set_indicator_function(set);
635 pa = isl_pw_aff_intersect_domain(pa, dom);
636 return pa;
639 /* Extract an affine expression from some binary operations.
640 * If the result of the expression is unsigned, then we wrap it
641 * based on the size of the type. Otherwise, we ensure that
642 * no overflow occurs.
644 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
646 isl_pw_aff *res;
647 unsigned width;
649 switch (expr->getOpcode()) {
650 case BO_Add:
651 case BO_Sub:
652 res = extract_affine_add(expr);
653 break;
654 case BO_Div:
655 res = extract_affine_div(expr);
656 break;
657 case BO_Rem:
658 res = extract_affine_mod(expr);
659 break;
660 case BO_Mul:
661 res = extract_affine_mul(expr);
662 break;
663 case BO_LT:
664 case BO_LE:
665 case BO_GT:
666 case BO_GE:
667 case BO_EQ:
668 case BO_NE:
669 case BO_LAnd:
670 case BO_LOr:
671 return extract_condition(expr);
672 default:
673 unsupported(expr);
674 return NULL;
677 width = ast_context.getIntWidth(expr->getType());
678 if (expr->getType()->isUnsignedIntegerType())
679 res = wrap(res, width);
680 else
681 res = signed_overflow(res, width);
683 return res;
686 /* Extract an affine expression from a negation operation.
688 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
690 if (expr->getOpcode() == UO_Minus)
691 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
692 if (expr->getOpcode() == UO_LNot)
693 return extract_condition(expr);
695 unsupported(expr);
696 return NULL;
699 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
701 return extract_affine(expr->getSubExpr());
704 /* Extract an affine expression from some special function calls.
705 * In particular, we handle "min", "max", "ceild" and "floord".
706 * In case of the latter two, the second argument needs to be
707 * a (positive) integer constant.
709 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
711 FunctionDecl *fd;
712 string name;
713 isl_pw_aff *aff1, *aff2;
715 fd = expr->getDirectCallee();
716 if (!fd) {
717 unsupported(expr);
718 return NULL;
721 name = fd->getDeclName().getAsString();
722 if (!(expr->getNumArgs() == 2 && name == "min") &&
723 !(expr->getNumArgs() == 2 && name == "max") &&
724 !(expr->getNumArgs() == 2 && name == "floord") &&
725 !(expr->getNumArgs() == 2 && name == "ceild")) {
726 unsupported(expr);
727 return NULL;
730 if (name == "min" || name == "max") {
731 aff1 = extract_affine(expr->getArg(0));
732 aff2 = extract_affine(expr->getArg(1));
734 if (name == "min")
735 aff1 = isl_pw_aff_min(aff1, aff2);
736 else
737 aff1 = isl_pw_aff_max(aff1, aff2);
738 } else if (name == "floord" || name == "ceild") {
739 isl_val *v;
740 Expr *arg2 = expr->getArg(1);
742 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
743 unsupported(expr);
744 return NULL;
746 aff1 = extract_affine(expr->getArg(0));
747 v = extract_int(cast<IntegerLiteral>(arg2));
748 aff1 = isl_pw_aff_scale_down_val(aff1, v);
749 if (name == "floord")
750 aff1 = isl_pw_aff_floor(aff1);
751 else
752 aff1 = isl_pw_aff_ceil(aff1);
753 } else {
754 unsupported(expr);
755 return NULL;
758 return aff1;
761 /* This method is called when we come across an access that is
762 * nested in what is supposed to be an affine expression.
763 * If nesting is allowed, we return a new parameter that corresponds
764 * to this nested access. Otherwise, we simply complain.
766 * Note that we currently don't allow nested accesses themselves
767 * to contain any nested accesses, so we check if we can extract
768 * the access without any nesting and complain if we can't.
770 * The new parameter is resolved in resolve_nested.
772 isl_pw_aff *PetScan::nested_access(Expr *expr)
774 isl_id *id;
775 isl_space *dim;
776 isl_aff *aff;
777 isl_set *dom;
778 isl_multi_pw_aff *index;
780 if (!nesting_enabled) {
781 unsupported(expr);
782 return NULL;
785 allow_nested = false;
786 index = extract_index(expr);
787 allow_nested = true;
788 if (!index) {
789 unsupported(expr);
790 return NULL;
792 isl_multi_pw_aff_free(index);
794 id = isl_id_alloc(ctx, NULL, expr);
795 dim = isl_space_params_alloc(ctx, 1);
797 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
799 dom = isl_set_universe(isl_space_copy(dim));
800 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
801 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
803 return isl_pw_aff_alloc(dom, aff);
806 /* Affine expressions are not supposed to contain array accesses,
807 * but if nesting is allowed, we return a parameter corresponding
808 * to the array access.
810 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
812 return nested_access(expr);
815 /* Extract an affine expression from a conditional operation.
817 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
819 isl_pw_aff *cond, *lhs, *rhs, *res;
821 cond = extract_condition(expr->getCond());
822 lhs = extract_affine(expr->getTrueExpr());
823 rhs = extract_affine(expr->getFalseExpr());
825 return isl_pw_aff_cond(cond, lhs, rhs);
828 /* Extract an affine expression, if possible, from "expr".
829 * Otherwise return NULL.
831 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
833 switch (expr->getStmtClass()) {
834 case Stmt::ImplicitCastExprClass:
835 return extract_affine(cast<ImplicitCastExpr>(expr));
836 case Stmt::IntegerLiteralClass:
837 return extract_affine(cast<IntegerLiteral>(expr));
838 case Stmt::DeclRefExprClass:
839 return extract_affine(cast<DeclRefExpr>(expr));
840 case Stmt::BinaryOperatorClass:
841 return extract_affine(cast<BinaryOperator>(expr));
842 case Stmt::UnaryOperatorClass:
843 return extract_affine(cast<UnaryOperator>(expr));
844 case Stmt::ParenExprClass:
845 return extract_affine(cast<ParenExpr>(expr));
846 case Stmt::CallExprClass:
847 return extract_affine(cast<CallExpr>(expr));
848 case Stmt::ArraySubscriptExprClass:
849 return extract_affine(cast<ArraySubscriptExpr>(expr));
850 case Stmt::ConditionalOperatorClass:
851 return extract_affine(cast<ConditionalOperator>(expr));
852 default:
853 unsupported(expr);
855 return NULL;
858 __isl_give isl_multi_pw_aff *PetScan::extract_index(ImplicitCastExpr *expr)
860 return extract_index(expr->getSubExpr());
863 /* Return the depth of an array of the given type.
865 static int array_depth(const Type *type)
867 if (type->isPointerType())
868 return 1 + array_depth(type->getPointeeType().getTypePtr());
869 if (type->isArrayType()) {
870 const ArrayType *atype;
871 type = type->getCanonicalTypeInternal().getTypePtr();
872 atype = cast<ArrayType>(type);
873 return 1 + array_depth(atype->getElementType().getTypePtr());
875 return 0;
878 /* Return the depth of the array accessed by the index expression "index".
879 * If "index" is an affine expression, i.e., if it does not access
880 * any array, then return 1.
882 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
884 isl_id *id;
885 ValueDecl *decl;
887 if (!index)
888 return -1;
890 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_set))
891 return 1;
893 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_set);
894 if (!id)
895 return -1;
896 decl = (ValueDecl *) isl_id_get_user(id);
897 isl_id_free(id);
899 return array_depth(decl->getType().getTypePtr());
902 /* Return the element type of the given array type.
904 static QualType base_type(QualType qt)
906 const Type *type = qt.getTypePtr();
908 if (type->isPointerType())
909 return base_type(type->getPointeeType());
910 if (type->isArrayType()) {
911 const ArrayType *atype;
912 type = type->getCanonicalTypeInternal().getTypePtr();
913 atype = cast<ArrayType>(type);
914 return base_type(atype->getElementType());
916 return qt;
919 /* Extract an index expression from a reference to a variable.
920 * If the variable has name "A", then the returned index expression
921 * is of the form
923 * { [] -> A[] }
925 __isl_give isl_multi_pw_aff *PetScan::extract_index(DeclRefExpr *expr)
927 return extract_index(expr->getDecl());
930 /* Extract an index expression from a variable.
931 * If the variable has name "A", then the returned index expression
932 * is of the form
934 * { [] -> A[] }
936 __isl_give isl_multi_pw_aff *PetScan::extract_index(ValueDecl *decl)
938 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
939 isl_space *space = isl_space_alloc(ctx, 0, 0, 0);
941 space = isl_space_set_tuple_id(space, isl_dim_out, id);
943 return isl_multi_pw_aff_zero(space);
946 /* Extract an index expression from an integer contant.
947 * If the value of the constant is "v", then the returned access relation
948 * is
950 * { [] -> [v] }
952 __isl_give isl_multi_pw_aff *PetScan::extract_index(IntegerLiteral *expr)
954 isl_multi_pw_aff *mpa;
956 mpa = isl_multi_pw_aff_from_pw_aff(extract_affine(expr));
957 mpa = isl_multi_pw_aff_from_range(mpa);
958 return mpa;
961 /* Try and extract an index expression from the given Expr.
962 * Return NULL if it doesn't work out.
964 __isl_give isl_multi_pw_aff *PetScan::extract_index(Expr *expr)
966 switch (expr->getStmtClass()) {
967 case Stmt::ImplicitCastExprClass:
968 return extract_index(cast<ImplicitCastExpr>(expr));
969 case Stmt::DeclRefExprClass:
970 return extract_index(cast<DeclRefExpr>(expr));
971 case Stmt::ArraySubscriptExprClass:
972 return extract_index(cast<ArraySubscriptExpr>(expr));
973 case Stmt::IntegerLiteralClass:
974 return extract_index(cast<IntegerLiteral>(expr));
975 default:
976 unsupported(expr);
978 return NULL;
981 /* Extract an index expression from the given array subscript expression.
982 * If nesting is allowed in general, then we turn it on while
983 * examining the index expression.
985 * We first extract an index expression from the base.
986 * This will result in an index expression with a range that corresponds
987 * to the earlier indices.
988 * We then extract the current index, restrict its domain
989 * to those values that result in a non-negative index and
990 * append the index to the base index expression.
992 __isl_give isl_multi_pw_aff *PetScan::extract_index(ArraySubscriptExpr *expr)
994 Expr *base = expr->getBase();
995 Expr *idx = expr->getIdx();
996 isl_pw_aff *index;
997 isl_set *domain;
998 isl_multi_pw_aff *base_access;
999 isl_multi_pw_aff *access;
1000 isl_id *id;
1001 bool save_nesting = nesting_enabled;
1003 nesting_enabled = allow_nested;
1005 base_access = extract_index(base);
1006 index = extract_affine(idx);
1008 nesting_enabled = save_nesting;
1010 id = isl_multi_pw_aff_get_tuple_id(base_access, isl_dim_set);
1011 index = isl_pw_aff_from_range(index);
1012 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
1013 index = isl_pw_aff_intersect_domain(index, domain);
1014 access = isl_multi_pw_aff_from_pw_aff(index);
1015 access = isl_multi_pw_aff_flat_range_product(base_access, access);
1016 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_set, id);
1018 return access;
1021 /* Check if "expr" calls function "minmax" with two arguments and if so
1022 * make lhs and rhs refer to these two arguments.
1024 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1026 CallExpr *call;
1027 FunctionDecl *fd;
1028 string name;
1030 if (expr->getStmtClass() != Stmt::CallExprClass)
1031 return false;
1033 call = cast<CallExpr>(expr);
1034 fd = call->getDirectCallee();
1035 if (!fd)
1036 return false;
1038 if (call->getNumArgs() != 2)
1039 return false;
1041 name = fd->getDeclName().getAsString();
1042 if (name != minmax)
1043 return false;
1045 lhs = call->getArg(0);
1046 rhs = call->getArg(1);
1048 return true;
1051 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1052 * lhs and rhs refer to the two arguments.
1054 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1056 return is_minmax(expr, "min", lhs, rhs);
1059 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1060 * lhs and rhs refer to the two arguments.
1062 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1064 return is_minmax(expr, "max", lhs, rhs);
1067 /* Return "lhs && rhs", defined on the shared definition domain.
1069 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1070 __isl_take isl_pw_aff *rhs)
1072 isl_set *cond;
1073 isl_set *dom;
1075 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1076 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1077 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1078 isl_pw_aff_non_zero_set(rhs));
1079 return indicator_function(cond, dom);
1082 /* Return "lhs && rhs", with shortcut semantics.
1083 * That is, if lhs is false, then the result is defined even if rhs is not.
1084 * In practice, we compute lhs ? rhs : lhs.
1086 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1087 __isl_take isl_pw_aff *rhs)
1089 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1092 /* Return "lhs || rhs", with shortcut semantics.
1093 * That is, if lhs is true, then the result is defined even if rhs is not.
1094 * In practice, we compute lhs ? lhs : rhs.
1096 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1097 __isl_take isl_pw_aff *rhs)
1099 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1102 /* Extract an affine expressions representing the comparison "LHS op RHS"
1103 * "comp" is the original statement that "LHS op RHS" is derived from
1104 * and is used for diagnostics.
1106 * If the comparison is of the form
1108 * a <= min(b,c)
1110 * then the expression is constructed as the conjunction of
1111 * the comparisons
1113 * a <= b and a <= c
1115 * A similar optimization is performed for max(a,b) <= c.
1116 * We do this because that will lead to simpler representations
1117 * of the expression.
1118 * If isl is ever enhanced to explicitly deal with min and max expressions,
1119 * this optimization can be removed.
1121 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1122 Expr *LHS, Expr *RHS, Stmt *comp)
1124 isl_pw_aff *lhs;
1125 isl_pw_aff *rhs;
1126 isl_pw_aff *res;
1127 isl_set *cond;
1128 isl_set *dom;
1130 if (op == BO_GT)
1131 return extract_comparison(BO_LT, RHS, LHS, comp);
1132 if (op == BO_GE)
1133 return extract_comparison(BO_LE, RHS, LHS, comp);
1135 if (op == BO_LT || op == BO_LE) {
1136 Expr *expr1, *expr2;
1137 if (is_min(RHS, expr1, expr2)) {
1138 lhs = extract_comparison(op, LHS, expr1, comp);
1139 rhs = extract_comparison(op, LHS, expr2, comp);
1140 return pw_aff_and(lhs, rhs);
1142 if (is_max(LHS, expr1, expr2)) {
1143 lhs = extract_comparison(op, expr1, RHS, comp);
1144 rhs = extract_comparison(op, expr2, RHS, comp);
1145 return pw_aff_and(lhs, rhs);
1149 lhs = extract_affine(LHS);
1150 rhs = extract_affine(RHS);
1152 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1153 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1155 switch (op) {
1156 case BO_LT:
1157 cond = isl_pw_aff_lt_set(lhs, rhs);
1158 break;
1159 case BO_LE:
1160 cond = isl_pw_aff_le_set(lhs, rhs);
1161 break;
1162 case BO_EQ:
1163 cond = isl_pw_aff_eq_set(lhs, rhs);
1164 break;
1165 case BO_NE:
1166 cond = isl_pw_aff_ne_set(lhs, rhs);
1167 break;
1168 default:
1169 isl_pw_aff_free(lhs);
1170 isl_pw_aff_free(rhs);
1171 isl_set_free(dom);
1172 unsupported(comp);
1173 return NULL;
1176 cond = isl_set_coalesce(cond);
1177 res = indicator_function(cond, dom);
1179 return res;
1182 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1184 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1185 comp->getRHS(), comp);
1188 /* Extract an affine expression representing the negation (logical not)
1189 * of a subexpression.
1191 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1193 isl_set *set_cond, *dom;
1194 isl_pw_aff *cond, *res;
1196 cond = extract_condition(op->getSubExpr());
1198 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1200 set_cond = isl_pw_aff_zero_set(cond);
1202 res = indicator_function(set_cond, dom);
1204 return res;
1207 /* Extract an affine expression representing the disjunction (logical or)
1208 * or conjunction (logical and) of two subexpressions.
1210 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1212 isl_pw_aff *lhs, *rhs;
1214 lhs = extract_condition(comp->getLHS());
1215 rhs = extract_condition(comp->getRHS());
1217 switch (comp->getOpcode()) {
1218 case BO_LAnd:
1219 return pw_aff_and_then(lhs, rhs);
1220 case BO_LOr:
1221 return pw_aff_or_else(lhs, rhs);
1222 default:
1223 isl_pw_aff_free(lhs);
1224 isl_pw_aff_free(rhs);
1227 unsupported(comp);
1228 return NULL;
1231 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1233 switch (expr->getOpcode()) {
1234 case UO_LNot:
1235 return extract_boolean(expr);
1236 default:
1237 unsupported(expr);
1238 return NULL;
1242 /* Extract the affine expression "expr != 0 ? 1 : 0".
1244 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1246 isl_pw_aff *res;
1247 isl_set *set, *dom;
1249 res = extract_affine(expr);
1251 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1252 set = isl_pw_aff_non_zero_set(res);
1254 res = indicator_function(set, dom);
1256 return res;
1259 /* Extract an affine expression from a boolean expression.
1260 * In particular, return the expression "expr ? 1 : 0".
1262 * If the expression doesn't look like a condition, we assume it
1263 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1265 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1267 BinaryOperator *comp;
1269 if (!expr) {
1270 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1271 return indicator_function(u, isl_set_copy(u));
1274 if (expr->getStmtClass() == Stmt::ParenExprClass)
1275 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1277 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1278 return extract_condition(cast<UnaryOperator>(expr));
1280 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1281 return extract_implicit_condition(expr);
1283 comp = cast<BinaryOperator>(expr);
1284 switch (comp->getOpcode()) {
1285 case BO_LT:
1286 case BO_LE:
1287 case BO_GT:
1288 case BO_GE:
1289 case BO_EQ:
1290 case BO_NE:
1291 return extract_comparison(comp);
1292 case BO_LAnd:
1293 case BO_LOr:
1294 return extract_boolean(comp);
1295 default:
1296 return extract_implicit_condition(expr);
1300 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
1302 switch (kind) {
1303 case UO_Minus:
1304 return pet_op_minus;
1305 case UO_PostInc:
1306 return pet_op_post_inc;
1307 case UO_PostDec:
1308 return pet_op_post_dec;
1309 case UO_PreInc:
1310 return pet_op_pre_inc;
1311 case UO_PreDec:
1312 return pet_op_pre_dec;
1313 default:
1314 return pet_op_last;
1318 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
1320 switch (kind) {
1321 case BO_AddAssign:
1322 return pet_op_add_assign;
1323 case BO_SubAssign:
1324 return pet_op_sub_assign;
1325 case BO_MulAssign:
1326 return pet_op_mul_assign;
1327 case BO_DivAssign:
1328 return pet_op_div_assign;
1329 case BO_Assign:
1330 return pet_op_assign;
1331 case BO_Add:
1332 return pet_op_add;
1333 case BO_Sub:
1334 return pet_op_sub;
1335 case BO_Mul:
1336 return pet_op_mul;
1337 case BO_Div:
1338 return pet_op_div;
1339 case BO_Rem:
1340 return pet_op_mod;
1341 case BO_EQ:
1342 return pet_op_eq;
1343 case BO_LE:
1344 return pet_op_le;
1345 case BO_LT:
1346 return pet_op_lt;
1347 case BO_GT:
1348 return pet_op_gt;
1349 default:
1350 return pet_op_last;
1354 /* Construct a pet_expr representing a unary operator expression.
1356 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1358 struct pet_expr *arg;
1359 enum pet_op_type op;
1361 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1362 if (op == pet_op_last) {
1363 unsupported(expr);
1364 return NULL;
1367 arg = extract_expr(expr->getSubExpr());
1369 if (expr->isIncrementDecrementOp() &&
1370 arg && arg->type == pet_expr_access) {
1371 mark_write(arg);
1372 arg->acc.read = 1;
1375 return pet_expr_new_unary(ctx, op, arg);
1378 /* Mark the given access pet_expr as a write.
1379 * If a scalar is being accessed, then mark its value
1380 * as unknown in assigned_value.
1382 void PetScan::mark_write(struct pet_expr *access)
1384 isl_id *id;
1385 ValueDecl *decl;
1387 if (!access)
1388 return;
1390 access->acc.write = 1;
1391 access->acc.read = 0;
1393 if (!pet_expr_is_scalar_access(access))
1394 return;
1396 id = pet_expr_access_get_id(access);
1397 decl = (ValueDecl *) isl_id_get_user(id);
1398 clear_assignment(assigned_value, decl);
1399 isl_id_free(id);
1402 /* Assign "rhs" to "lhs".
1404 * In particular, if "lhs" is a scalar variable, then mark
1405 * the variable as having been assigned. If, furthermore, "rhs"
1406 * is an affine expression, then keep track of this value in assigned_value
1407 * so that we can plug it in when we later come across the same variable.
1409 void PetScan::assign(struct pet_expr *lhs, Expr *rhs)
1411 isl_id *id;
1412 ValueDecl *decl;
1413 isl_pw_aff *pa;
1415 if (!lhs)
1416 return;
1417 if (!pet_expr_is_scalar_access(lhs))
1418 return;
1420 id = pet_expr_access_get_id(lhs);
1421 decl = (ValueDecl *) isl_id_get_user(id);
1422 isl_id_free(id);
1424 pa = try_extract_affine(rhs);
1425 clear_assignment(assigned_value, decl);
1426 if (!pa)
1427 return;
1428 assigned_value[decl] = pa;
1429 insert_expression(pa);
1432 /* Construct a pet_expr representing a binary operator expression.
1434 * If the top level operator is an assignment and the LHS is an access,
1435 * then we mark that access as a write. If the operator is a compound
1436 * assignment, the access is marked as both a read and a write.
1438 * If "expr" assigns something to a scalar variable, then we mark
1439 * the variable as having been assigned. If, furthermore, the expression
1440 * is affine, then keep track of this value in assigned_value
1441 * so that we can plug it in when we later come across the same variable.
1443 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1445 struct pet_expr *lhs, *rhs;
1446 enum pet_op_type op;
1448 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1449 if (op == pet_op_last) {
1450 unsupported(expr);
1451 return NULL;
1454 lhs = extract_expr(expr->getLHS());
1455 rhs = extract_expr(expr->getRHS());
1457 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1458 mark_write(lhs);
1459 if (expr->isCompoundAssignmentOp())
1460 lhs->acc.read = 1;
1463 if (expr->getOpcode() == BO_Assign)
1464 assign(lhs, expr->getRHS());
1466 return pet_expr_new_binary(ctx, op, lhs, rhs);
1469 /* Construct a pet_scop with a single statement killing the entire
1470 * array "array".
1472 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1474 isl_map *access;
1475 struct pet_expr *expr;
1477 if (!array)
1478 return NULL;
1479 access = isl_map_from_range(isl_set_copy(array->extent));
1480 expr = pet_expr_kill_from_access(access);
1481 return extract(stmt, expr);
1484 /* Construct a pet_scop for a (single) variable declaration.
1486 * The scop contains the variable being declared (as an array)
1487 * and a statement killing the array.
1489 * If the variable is initialized in the AST, then the scop
1490 * also contains an assignment to the variable.
1492 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1494 Decl *decl;
1495 VarDecl *vd;
1496 struct pet_expr *lhs, *rhs, *pe;
1497 struct pet_scop *scop_decl, *scop;
1498 struct pet_array *array;
1500 if (!stmt->isSingleDecl()) {
1501 unsupported(stmt);
1502 return NULL;
1505 decl = stmt->getSingleDecl();
1506 vd = cast<VarDecl>(decl);
1508 array = extract_array(ctx, vd);
1509 if (array)
1510 array->declared = 1;
1511 scop_decl = kill(stmt, array);
1512 scop_decl = pet_scop_add_array(scop_decl, array);
1514 if (!vd->getInit())
1515 return scop_decl;
1517 lhs = extract_access_expr(vd);
1518 rhs = extract_expr(vd->getInit());
1520 mark_write(lhs);
1521 assign(lhs, vd->getInit());
1523 pe = pet_expr_new_binary(ctx, pet_op_assign, lhs, rhs);
1524 scop = extract(stmt, pe);
1526 scop_decl = pet_scop_prefix(scop_decl, 0);
1527 scop = pet_scop_prefix(scop, 1);
1529 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1531 return scop;
1534 /* Construct a pet_expr representing a conditional operation.
1536 * We first try to extract the condition as an affine expression.
1537 * If that fails, we construct a pet_expr tree representing the condition.
1539 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1541 struct pet_expr *cond, *lhs, *rhs;
1542 isl_pw_aff *pa;
1544 pa = try_extract_affine(expr->getCond());
1545 if (pa) {
1546 isl_multi_pw_aff *test = isl_multi_pw_aff_from_pw_aff(pa);
1547 test = isl_multi_pw_aff_from_range(test);
1548 cond = pet_expr_from_index(test);
1549 } else
1550 cond = extract_expr(expr->getCond());
1551 lhs = extract_expr(expr->getTrueExpr());
1552 rhs = extract_expr(expr->getFalseExpr());
1554 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1557 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1559 return extract_expr(expr->getSubExpr());
1562 /* Construct a pet_expr representing a floating point value.
1564 * If the floating point literal does not appear in a macro,
1565 * then we use the original representation in the source code
1566 * as the string representation. Otherwise, we use the pretty
1567 * printer to produce a string representation.
1569 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1571 double d;
1572 string s;
1573 const LangOptions &LO = PP.getLangOpts();
1574 SourceLocation loc = expr->getLocation();
1576 if (!loc.isMacroID()) {
1577 SourceManager &SM = PP.getSourceManager();
1578 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1579 s = string(SM.getCharacterData(loc), len);
1580 } else {
1581 llvm::raw_string_ostream S(s);
1582 expr->printPretty(S, 0, PrintingPolicy(LO));
1583 S.str();
1585 d = expr->getValueAsApproximateDouble();
1586 return pet_expr_new_double(ctx, d, s.c_str());
1589 /* Extract an index expression from "expr" and then convert it into
1590 * an access pet_expr.
1592 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1594 isl_multi_pw_aff *index;
1595 struct pet_expr *pe;
1596 int depth;
1598 index = extract_index(expr);
1599 depth = extract_depth(index);
1601 pe = pet_expr_from_index_and_depth(index, depth);
1603 return pe;
1606 /* Extract an index expression from "decl" and then convert it into
1607 * an access pet_expr.
1609 struct pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1611 isl_multi_pw_aff *index;
1612 struct pet_expr *pe;
1613 int depth;
1615 index = extract_index(decl);
1616 depth = extract_depth(index);
1618 pe = pet_expr_from_index_and_depth(index, depth);
1620 return pe;
1623 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1625 return extract_expr(expr->getSubExpr());
1628 /* Construct a pet_expr representing a function call.
1630 * If we are passing along a pointer to an array element
1631 * or an entire row or even higher dimensional slice of an array,
1632 * then the function being called may write into the array.
1634 * We assume here that if the function is declared to take a pointer
1635 * to a const type, then the function will perform a read
1636 * and that otherwise, it will perform a write.
1638 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1640 struct pet_expr *res = NULL;
1641 FunctionDecl *fd;
1642 string name;
1644 fd = expr->getDirectCallee();
1645 if (!fd) {
1646 unsupported(expr);
1647 return NULL;
1650 name = fd->getDeclName().getAsString();
1651 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1652 if (!res)
1653 return NULL;
1655 for (int i = 0; i < expr->getNumArgs(); ++i) {
1656 Expr *arg = expr->getArg(i);
1657 int is_addr = 0;
1658 pet_expr *main_arg;
1660 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1661 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1662 arg = ice->getSubExpr();
1664 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1665 UnaryOperator *op = cast<UnaryOperator>(arg);
1666 if (op->getOpcode() == UO_AddrOf) {
1667 is_addr = 1;
1668 arg = op->getSubExpr();
1671 res->args[i] = PetScan::extract_expr(arg);
1672 main_arg = res->args[i];
1673 if (is_addr)
1674 res->args[i] = pet_expr_new_unary(ctx,
1675 pet_op_address_of, res->args[i]);
1676 if (!res->args[i])
1677 goto error;
1678 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1679 array_depth(arg->getType().getTypePtr()) > 0)
1680 is_addr = 1;
1681 if (is_addr && main_arg->type == pet_expr_access) {
1682 ParmVarDecl *parm;
1683 if (!fd->hasPrototype()) {
1684 unsupported(expr, "prototype required");
1685 goto error;
1687 parm = fd->getParamDecl(i);
1688 if (!const_base(parm->getType()))
1689 mark_write(main_arg);
1693 return res;
1694 error:
1695 pet_expr_free(res);
1696 return NULL;
1699 /* Construct a pet_expr representing a (C style) cast.
1701 struct pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1703 struct pet_expr *arg;
1704 QualType type;
1706 arg = extract_expr(expr->getSubExpr());
1707 if (!arg)
1708 return NULL;
1710 type = expr->getTypeAsWritten();
1711 return pet_expr_new_cast(ctx, type.getAsString().c_str(), arg);
1714 /* Try and onstruct a pet_expr representing "expr".
1716 struct pet_expr *PetScan::extract_expr(Expr *expr)
1718 switch (expr->getStmtClass()) {
1719 case Stmt::UnaryOperatorClass:
1720 return extract_expr(cast<UnaryOperator>(expr));
1721 case Stmt::CompoundAssignOperatorClass:
1722 case Stmt::BinaryOperatorClass:
1723 return extract_expr(cast<BinaryOperator>(expr));
1724 case Stmt::ImplicitCastExprClass:
1725 return extract_expr(cast<ImplicitCastExpr>(expr));
1726 case Stmt::ArraySubscriptExprClass:
1727 case Stmt::DeclRefExprClass:
1728 case Stmt::IntegerLiteralClass:
1729 return extract_access_expr(expr);
1730 case Stmt::FloatingLiteralClass:
1731 return extract_expr(cast<FloatingLiteral>(expr));
1732 case Stmt::ParenExprClass:
1733 return extract_expr(cast<ParenExpr>(expr));
1734 case Stmt::ConditionalOperatorClass:
1735 return extract_expr(cast<ConditionalOperator>(expr));
1736 case Stmt::CallExprClass:
1737 return extract_expr(cast<CallExpr>(expr));
1738 case Stmt::CStyleCastExprClass:
1739 return extract_expr(cast<CStyleCastExpr>(expr));
1740 default:
1741 unsupported(expr);
1743 return NULL;
1746 /* Check if the given initialization statement is an assignment.
1747 * If so, return that assignment. Otherwise return NULL.
1749 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1751 BinaryOperator *ass;
1753 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1754 return NULL;
1756 ass = cast<BinaryOperator>(init);
1757 if (ass->getOpcode() != BO_Assign)
1758 return NULL;
1760 return ass;
1763 /* Check if the given initialization statement is a declaration
1764 * of a single variable.
1765 * If so, return that declaration. Otherwise return NULL.
1767 Decl *PetScan::initialization_declaration(Stmt *init)
1769 DeclStmt *decl;
1771 if (init->getStmtClass() != Stmt::DeclStmtClass)
1772 return NULL;
1774 decl = cast<DeclStmt>(init);
1776 if (!decl->isSingleDecl())
1777 return NULL;
1779 return decl->getSingleDecl();
1782 /* Given the assignment operator in the initialization of a for loop,
1783 * extract the induction variable, i.e., the (integer)variable being
1784 * assigned.
1786 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1788 Expr *lhs;
1789 DeclRefExpr *ref;
1790 ValueDecl *decl;
1791 const Type *type;
1793 lhs = init->getLHS();
1794 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1795 unsupported(init);
1796 return NULL;
1799 ref = cast<DeclRefExpr>(lhs);
1800 decl = ref->getDecl();
1801 type = decl->getType().getTypePtr();
1803 if (!type->isIntegerType()) {
1804 unsupported(lhs);
1805 return NULL;
1808 return decl;
1811 /* Given the initialization statement of a for loop and the single
1812 * declaration in this initialization statement,
1813 * extract the induction variable, i.e., the (integer) variable being
1814 * declared.
1816 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1818 VarDecl *vd;
1820 vd = cast<VarDecl>(decl);
1822 const QualType type = vd->getType();
1823 if (!type->isIntegerType()) {
1824 unsupported(init);
1825 return NULL;
1828 if (!vd->getInit()) {
1829 unsupported(init);
1830 return NULL;
1833 return vd;
1836 /* Check that op is of the form iv++ or iv--.
1837 * Return an affine expression "1" or "-1" accordingly.
1839 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
1840 clang::UnaryOperator *op, clang::ValueDecl *iv)
1842 Expr *sub;
1843 DeclRefExpr *ref;
1844 isl_space *space;
1845 isl_aff *aff;
1847 if (!op->isIncrementDecrementOp()) {
1848 unsupported(op);
1849 return NULL;
1852 sub = op->getSubExpr();
1853 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1854 unsupported(op);
1855 return NULL;
1858 ref = cast<DeclRefExpr>(sub);
1859 if (ref->getDecl() != iv) {
1860 unsupported(op);
1861 return NULL;
1864 space = isl_space_params_alloc(ctx, 0);
1865 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1867 if (op->isIncrementOp())
1868 aff = isl_aff_add_constant_si(aff, 1);
1869 else
1870 aff = isl_aff_add_constant_si(aff, -1);
1872 return isl_pw_aff_from_aff(aff);
1875 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1876 * has a single constant expression, then put this constant in *user.
1877 * The caller is assumed to have checked that this function will
1878 * be called exactly once.
1880 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1881 void *user)
1883 isl_val **inc = (isl_val **)user;
1884 int res = 0;
1886 if (isl_aff_is_cst(aff))
1887 *inc = isl_aff_get_constant_val(aff);
1888 else
1889 res = -1;
1891 isl_set_free(set);
1892 isl_aff_free(aff);
1894 return res;
1897 /* Check if op is of the form
1899 * iv = iv + inc
1901 * and return inc as an affine expression.
1903 * We extract an affine expression from the RHS, subtract iv and return
1904 * the result.
1906 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
1907 clang::ValueDecl *iv)
1909 Expr *lhs;
1910 DeclRefExpr *ref;
1911 isl_id *id;
1912 isl_space *dim;
1913 isl_aff *aff;
1914 isl_pw_aff *val;
1916 if (op->getOpcode() != BO_Assign) {
1917 unsupported(op);
1918 return NULL;
1921 lhs = op->getLHS();
1922 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1923 unsupported(op);
1924 return NULL;
1927 ref = cast<DeclRefExpr>(lhs);
1928 if (ref->getDecl() != iv) {
1929 unsupported(op);
1930 return NULL;
1933 val = extract_affine(op->getRHS());
1935 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1937 dim = isl_space_params_alloc(ctx, 1);
1938 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1939 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1940 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1942 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1944 return val;
1947 /* Check that op is of the form iv += cst or iv -= cst
1948 * and return an affine expression corresponding oto cst or -cst accordingly.
1950 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
1951 CompoundAssignOperator *op, clang::ValueDecl *iv)
1953 Expr *lhs;
1954 DeclRefExpr *ref;
1955 bool neg = false;
1956 isl_pw_aff *val;
1957 BinaryOperatorKind opcode;
1959 opcode = op->getOpcode();
1960 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1961 unsupported(op);
1962 return NULL;
1964 if (opcode == BO_SubAssign)
1965 neg = true;
1967 lhs = op->getLHS();
1968 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1969 unsupported(op);
1970 return NULL;
1973 ref = cast<DeclRefExpr>(lhs);
1974 if (ref->getDecl() != iv) {
1975 unsupported(op);
1976 return NULL;
1979 val = extract_affine(op->getRHS());
1980 if (neg)
1981 val = isl_pw_aff_neg(val);
1983 return val;
1986 /* Check that the increment of the given for loop increments
1987 * (or decrements) the induction variable "iv" and return
1988 * the increment as an affine expression if successful.
1990 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
1991 ValueDecl *iv)
1993 Stmt *inc = stmt->getInc();
1995 if (!inc) {
1996 unsupported(stmt);
1997 return NULL;
2000 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
2001 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
2002 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
2003 return extract_compound_increment(
2004 cast<CompoundAssignOperator>(inc), iv);
2005 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
2006 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
2008 unsupported(inc);
2009 return NULL;
2012 /* Embed the given iteration domain in an extra outer loop
2013 * with induction variable "var".
2014 * If this variable appeared as a parameter in the constraints,
2015 * it is replaced by the new outermost dimension.
2017 static __isl_give isl_set *embed(__isl_take isl_set *set,
2018 __isl_take isl_id *var)
2020 int pos;
2022 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
2023 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
2024 if (pos >= 0) {
2025 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
2026 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2029 isl_id_free(var);
2030 return set;
2033 /* Return those elements in the space of "cond" that come after
2034 * (based on "sign") an element in "cond".
2036 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
2038 isl_map *previous_to_this;
2040 if (sign > 0)
2041 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
2042 else
2043 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
2045 cond = isl_set_apply(cond, previous_to_this);
2047 return cond;
2050 /* Create the infinite iteration domain
2052 * { [id] : id >= 0 }
2054 * If "scop" has an affine skip of type pet_skip_later,
2055 * then remove those iterations i that have an earlier iteration
2056 * where the skip condition is satisfied, meaning that iteration i
2057 * is not executed.
2058 * Since we are dealing with a loop without loop iterator,
2059 * the skip condition cannot refer to the current loop iterator and
2060 * so effectively, the returned set is of the form
2062 * { [0]; [id] : id >= 1 and not skip }
2064 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
2065 struct pet_scop *scop)
2067 isl_ctx *ctx = isl_id_get_ctx(id);
2068 isl_set *domain;
2069 isl_set *skip;
2071 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
2072 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
2074 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
2075 return domain;
2077 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2078 skip = embed(skip, isl_id_copy(id));
2079 skip = isl_set_intersect(skip , isl_set_copy(domain));
2080 domain = isl_set_subtract(domain, after(skip, 1));
2082 return domain;
2085 /* Create an identity affine expression on the space containing "domain",
2086 * which is assumed to be one-dimensional.
2088 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
2090 isl_local_space *ls;
2092 ls = isl_local_space_from_space(isl_set_get_space(domain));
2093 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
2096 /* Create a map that maps elements of a single-dimensional array "id_test"
2097 * to the previous element (according to "inc"), provided this element
2098 * belongs to "domain". That is, create the map
2100 * { id[x] -> id[x - inc] : x - inc in domain }
2102 static __isl_give isl_map *map_to_previous(__isl_take isl_id *id_test,
2103 __isl_take isl_set *domain, __isl_take isl_val *inc)
2105 isl_space *space;
2106 isl_local_space *ls;
2107 isl_aff *aff;
2108 isl_map *prev;
2110 space = isl_set_get_space(domain);
2111 ls = isl_local_space_from_space(space);
2112 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2113 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
2114 prev = isl_map_from_aff(aff);
2115 prev = isl_map_intersect_range(prev, domain);
2116 prev = isl_map_set_tuple_id(prev, isl_dim_out, id_test);
2118 return prev;
2121 /* Add an implication to "scop" expressing that if an element of
2122 * virtual array "id_test" has value "satisfied" then all previous elements
2123 * of this array also have that value. The set of previous elements
2124 * is bounded by "domain". If "sign" is negative then iterator
2125 * is decreasing and we express that all subsequent array elements
2126 * (but still defined previously) have the same value.
2128 static struct pet_scop *add_implication(struct pet_scop *scop,
2129 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
2130 int satisfied)
2132 isl_space *space;
2133 isl_map *map;
2135 domain = isl_set_set_tuple_id(domain, id_test);
2136 space = isl_set_get_space(domain);
2137 if (sign > 0)
2138 map = isl_map_lex_ge(space);
2139 else
2140 map = isl_map_lex_le(space);
2141 map = isl_map_intersect_range(map, domain);
2142 scop = pet_scop_add_implication(scop, map, satisfied);
2144 return scop;
2147 /* Add a filter to "scop" that imposes that it is only executed
2148 * when the variable identified by "id_test" has a zero value
2149 * for all previous iterations of "domain".
2151 * In particular, add a filter that imposes that the array
2152 * has a zero value at the previous iteration of domain and
2153 * add an implication that implies that it then has that
2154 * value for all previous iterations.
2156 static struct pet_scop *scop_add_break(struct pet_scop *scop,
2157 __isl_take isl_id *id_test, __isl_take isl_set *domain,
2158 __isl_take isl_val *inc)
2160 isl_map *prev;
2161 int sign = isl_val_sgn(inc);
2163 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2164 scop = add_implication(scop, id_test, domain, sign, 0);
2165 scop = pet_scop_filter(scop, prev, 0);
2167 return scop;
2170 /* Construct a pet_scop for an infinite loop around the given body.
2172 * We extract a pet_scop for the body and then embed it in a loop with
2173 * iteration domain
2175 * { [t] : t >= 0 }
2177 * and schedule
2179 * { [t] -> [t] }
2181 * If the body contains any break, then it is taken into
2182 * account in infinite_domain (if the skip condition is affine)
2183 * or in scop_add_break (if the skip condition is not affine).
2185 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2187 isl_id *id, *id_test;
2188 isl_set *domain;
2189 isl_aff *ident;
2190 struct pet_scop *scop;
2191 bool has_var_break;
2193 scop = extract(body);
2194 if (!scop)
2195 return NULL;
2197 id = isl_id_alloc(ctx, "t", NULL);
2198 domain = infinite_domain(isl_id_copy(id), scop);
2199 ident = identity_aff(domain);
2201 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2202 if (has_var_break)
2203 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
2205 scop = pet_scop_embed(scop, isl_set_copy(domain),
2206 isl_map_from_aff(isl_aff_copy(ident)), ident, id);
2207 if (has_var_break)
2208 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
2209 else
2210 isl_set_free(domain);
2212 return scop;
2215 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2217 * for (;;)
2218 * body
2221 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2223 return extract_infinite_loop(stmt->getBody());
2226 /* Create an index expression for an access to a virtual array
2227 * representing the result of a condition.
2228 * Unlike other accessed data, the id of the array is NULL as
2229 * there is no ValueDecl in the program corresponding to the virtual
2230 * array.
2231 * The array starts out as a scalar, but grows along with the
2232 * statement writing to the array in pet_scop_embed.
2234 static __isl_give isl_multi_pw_aff *create_test_index(isl_ctx *ctx, int test_nr)
2236 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2237 isl_id *id;
2238 char name[50];
2240 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2241 id = isl_id_alloc(ctx, name, NULL);
2242 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2243 return isl_multi_pw_aff_zero(dim);
2246 /* Create an access to a virtual array representing the result
2247 * of a condition.
2249 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2251 return isl_map_from_multi_pw_aff(create_test_index(ctx, test_nr));
2254 /* Add an array with the given extent ("access") to the list
2255 * of arrays in "scop" and return the extended pet_scop.
2256 * The array is marked as attaining values 0 and 1 only and
2257 * as each element being assigned at most once.
2259 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2260 __isl_keep isl_map *access, clang::ASTContext &ast_ctx)
2262 isl_ctx *ctx = isl_map_get_ctx(access);
2263 isl_space *dim;
2264 struct pet_array *array;
2266 if (!scop)
2267 return NULL;
2268 if (!ctx)
2269 goto error;
2271 array = isl_calloc_type(ctx, struct pet_array);
2272 if (!array)
2273 goto error;
2275 array->extent = isl_map_range(isl_map_copy(access));
2276 dim = isl_space_params_alloc(ctx, 0);
2277 array->context = isl_set_universe(dim);
2278 dim = isl_space_set_alloc(ctx, 0, 1);
2279 array->value_bounds = isl_set_universe(dim);
2280 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2281 isl_dim_set, 0, 0);
2282 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2283 isl_dim_set, 0, 1);
2284 array->element_type = strdup("int");
2285 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2286 array->uniquely_defined = 1;
2288 if (!array->extent || !array->context)
2289 array = pet_array_free(array);
2291 scop = pet_scop_add_array(scop, array);
2293 return scop;
2294 error:
2295 pet_scop_free(scop);
2296 return NULL;
2299 /* Construct a pet_scop for a while loop of the form
2301 * while (pa)
2302 * body
2304 * In particular, construct a scop for an infinite loop around body and
2305 * intersect the domain with the affine expression.
2306 * Note that this intersection may result in an empty loop.
2308 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2309 Stmt *body)
2311 struct pet_scop *scop;
2312 isl_set *dom;
2313 isl_set *valid;
2315 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2316 dom = isl_pw_aff_non_zero_set(pa);
2317 scop = extract_infinite_loop(body);
2318 scop = pet_scop_restrict(scop, dom);
2319 scop = pet_scop_restrict_context(scop, valid);
2321 return scop;
2324 /* Construct a scop for a while, given the scops for the condition
2325 * and the body, the filter identifier and the iteration domain of
2326 * the while loop.
2328 * In particular, the scop for the condition is filtered to depend
2329 * on "id_test" evaluating to true for all previous iterations
2330 * of the loop, while the scop for the body is filtered to depend
2331 * on "id_test" evaluating to true for all iterations up to the
2332 * current iteration.
2333 * The actual filter only imposes that this virtual array has
2334 * value one on the previous or the current iteration.
2335 * The fact that this condition also applies to the previous
2336 * iterations is enforced by an implication.
2338 * These filtered scops are then combined into a single scop.
2340 * "sign" is positive if the iterator increases and negative
2341 * if it decreases.
2343 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2344 struct pet_scop *scop_body, __isl_take isl_id *id_test,
2345 __isl_take isl_set *domain, __isl_take isl_val *inc)
2347 isl_ctx *ctx = isl_set_get_ctx(domain);
2348 isl_space *space;
2349 isl_map *test_access;
2350 isl_map *prev;
2351 int sign = isl_val_sgn(inc);
2352 struct pet_scop *scop;
2354 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2355 scop_cond = pet_scop_filter(scop_cond, prev, 1);
2357 space = isl_space_map_from_set(isl_set_get_space(domain));
2358 test_access = isl_map_identity(space);
2359 test_access = isl_map_set_tuple_id(test_access, isl_dim_out,
2360 isl_id_copy(id_test));
2361 scop_body = pet_scop_filter(scop_body, test_access, 1);
2363 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
2364 scop = add_implication(scop, id_test, domain, sign, 1);
2366 return scop;
2369 /* Check if the while loop is of the form
2371 * while (affine expression)
2372 * body
2374 * If so, call extract_affine_while to construct a scop.
2376 * Otherwise, construct a generic while scop, with iteration domain
2377 * { [t] : t >= 0 }. The scop consists of two parts, one for
2378 * evaluating the condition and one for the body.
2379 * The schedule is adjusted to reflect that the condition is evaluated
2380 * before the body is executed and the body is filtered to depend
2381 * on the result of the condition evaluating to true on all iterations
2382 * up to the current iteration, while the evaluation the condition itself
2383 * is filtered to depend on the result of the condition evaluating to true
2384 * on all previous iterations.
2385 * The context of the scop representing the body is dropped
2386 * because we don't know how many times the body will be executed,
2387 * if at all.
2389 * If the body contains any break, then it is taken into
2390 * account in infinite_domain (if the skip condition is affine)
2391 * or in scop_add_break (if the skip condition is not affine).
2393 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2395 Expr *cond;
2396 isl_id *id, *id_test, *id_break_test;
2397 isl_multi_pw_aff *test_index;
2398 isl_map *test_access;
2399 isl_set *domain;
2400 isl_aff *ident;
2401 isl_pw_aff *pa;
2402 struct pet_scop *scop, *scop_body;
2403 bool has_var_break;
2405 cond = stmt->getCond();
2406 if (!cond) {
2407 unsupported(stmt);
2408 return NULL;
2411 clear_assignments clear(assigned_value);
2412 clear.TraverseStmt(stmt->getBody());
2414 pa = try_extract_affine_condition(cond);
2415 if (pa)
2416 return extract_affine_while(pa, stmt->getBody());
2418 if (!allow_nested) {
2419 unsupported(stmt);
2420 return NULL;
2423 test_index = create_test_index(ctx, n_test++);
2424 scop = extract_non_affine_condition(cond,
2425 isl_multi_pw_aff_copy(test_index));
2426 test_access = isl_map_from_multi_pw_aff(test_index);
2427 scop = scop_add_array(scop, test_access, ast_context);
2428 id_test = isl_map_get_tuple_id(test_access, isl_dim_out);
2429 isl_map_free(test_access);
2430 scop_body = extract(stmt->getBody());
2432 id = isl_id_alloc(ctx, "t", NULL);
2433 domain = infinite_domain(isl_id_copy(id), scop_body);
2434 ident = identity_aff(domain);
2436 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2437 if (has_var_break)
2438 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2440 scop = pet_scop_prefix(scop, 0);
2441 scop = pet_scop_embed(scop, isl_set_copy(domain),
2442 isl_map_from_aff(isl_aff_copy(ident)),
2443 isl_aff_copy(ident), isl_id_copy(id));
2444 scop_body = pet_scop_reset_context(scop_body);
2445 scop_body = pet_scop_prefix(scop_body, 1);
2446 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2447 isl_map_from_aff(isl_aff_copy(ident)), ident, id);
2449 if (has_var_break) {
2450 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2451 isl_set_copy(domain), isl_val_one(ctx));
2452 scop_body = scop_add_break(scop_body, id_break_test,
2453 isl_set_copy(domain), isl_val_one(ctx));
2455 scop = scop_add_while(scop, scop_body, id_test, domain,
2456 isl_val_one(ctx));
2458 return scop;
2461 /* Check whether "cond" expresses a simple loop bound
2462 * on the only set dimension.
2463 * In particular, if "up" is set then "cond" should contain only
2464 * upper bounds on the set dimension.
2465 * Otherwise, it should contain only lower bounds.
2467 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2469 if (isl_val_is_pos(inc))
2470 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2471 else
2472 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2475 /* Extend a condition on a given iteration of a loop to one that
2476 * imposes the same condition on all previous iterations.
2477 * "domain" expresses the lower [upper] bound on the iterations
2478 * when inc is positive [negative].
2480 * In particular, we construct the condition (when inc is positive)
2482 * forall i' : (domain(i') and i' <= i) => cond(i')
2484 * which is equivalent to
2486 * not exists i' : domain(i') and i' <= i and not cond(i')
2488 * We construct this set by negating cond, applying a map
2490 * { [i'] -> [i] : domain(i') and i' <= i }
2492 * and then negating the result again.
2494 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2495 __isl_take isl_set *domain, __isl_take isl_val *inc)
2497 isl_map *previous_to_this;
2499 if (isl_val_is_pos(inc))
2500 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2501 else
2502 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2504 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2506 cond = isl_set_complement(cond);
2507 cond = isl_set_apply(cond, previous_to_this);
2508 cond = isl_set_complement(cond);
2510 isl_val_free(inc);
2512 return cond;
2515 /* Construct a domain of the form
2517 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2519 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2520 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2522 isl_aff *aff;
2523 isl_space *dim;
2524 isl_set *set;
2526 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2527 dim = isl_pw_aff_get_domain_space(init);
2528 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2529 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2530 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2532 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2533 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2534 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2535 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2537 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2539 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2541 return isl_set_params(set);
2544 /* Assuming "cond" represents a bound on a loop where the loop
2545 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2546 * is possible.
2548 * Under the given assumptions, wrapping is only possible if "cond" allows
2549 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2550 * increasing iterator and 0 in case of a decreasing iterator.
2552 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2553 __isl_keep isl_val *inc)
2555 bool cw;
2556 isl_ctx *ctx;
2557 isl_val *limit;
2558 isl_set *test;
2560 test = isl_set_copy(cond);
2562 ctx = isl_set_get_ctx(test);
2563 if (isl_val_is_neg(inc))
2564 limit = isl_val_zero(ctx);
2565 else {
2566 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2567 limit = isl_val_2exp(limit);
2568 limit = isl_val_sub_ui(limit, 1);
2571 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2572 cw = !isl_set_is_empty(test);
2573 isl_set_free(test);
2575 return cw;
2578 /* Given a one-dimensional space, construct the following affine expression
2579 * on this space
2581 * { [v] -> [v mod 2^width] }
2583 * where width is the number of bits used to represent the values
2584 * of the unsigned variable "iv".
2586 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2587 ValueDecl *iv)
2589 isl_ctx *ctx;
2590 isl_val *mod;
2591 isl_aff *aff;
2592 isl_map *map;
2594 ctx = isl_space_get_ctx(dim);
2595 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2596 mod = isl_val_2exp(mod);
2598 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2599 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2600 aff = isl_aff_mod_val(aff, mod);
2602 return aff;
2605 /* Project out the parameter "id" from "set".
2607 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2608 __isl_keep isl_id *id)
2610 int pos;
2612 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2613 if (pos >= 0)
2614 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2616 return set;
2619 /* Compute the set of parameters for which "set1" is a subset of "set2".
2621 * set1 is a subset of set2 if
2623 * forall i in set1 : i in set2
2625 * or
2627 * not exists i in set1 and i not in set2
2629 * i.e.,
2631 * not exists i in set1 \ set2
2633 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2634 __isl_take isl_set *set2)
2636 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2639 /* Compute the set of parameter values for which "cond" holds
2640 * on the next iteration for each element of "dom".
2642 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2643 * and then compute the set of parameters for which the result is a subset
2644 * of "cond".
2646 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2647 __isl_take isl_set *dom, __isl_take isl_val *inc)
2649 isl_space *space;
2650 isl_aff *aff;
2651 isl_map *next;
2653 space = isl_set_get_space(dom);
2654 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2655 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2656 aff = isl_aff_add_constant_val(aff, inc);
2657 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2659 dom = isl_set_apply(dom, next);
2661 return enforce_subset(dom, cond);
2664 /* Does "id" refer to a nested access?
2666 static bool is_nested_parameter(__isl_keep isl_id *id)
2668 return id && isl_id_get_user(id) && !isl_id_get_name(id);
2671 /* Does parameter "pos" of "space" refer to a nested access?
2673 static bool is_nested_parameter(__isl_keep isl_space *space, int pos)
2675 bool nested;
2676 isl_id *id;
2678 id = isl_space_get_dim_id(space, isl_dim_param, pos);
2679 nested = is_nested_parameter(id);
2680 isl_id_free(id);
2682 return nested;
2685 /* Does "space" involve any parameters that refer to nested
2686 * accesses, i.e., parameters with no name?
2688 static bool has_nested(__isl_keep isl_space *space)
2690 int nparam;
2692 nparam = isl_space_dim(space, isl_dim_param);
2693 for (int i = 0; i < nparam; ++i)
2694 if (is_nested_parameter(space, i))
2695 return true;
2697 return false;
2700 /* Does "pa" involve any parameters that refer to nested
2701 * accesses, i.e., parameters with no name?
2703 static bool has_nested(__isl_keep isl_pw_aff *pa)
2705 isl_space *space;
2706 bool nested;
2708 space = isl_pw_aff_get_space(pa);
2709 nested = has_nested(space);
2710 isl_space_free(space);
2712 return nested;
2715 /* Construct a pet_scop for a for statement.
2716 * The for loop is required to be of the form
2718 * for (i = init; condition; ++i)
2720 * or
2722 * for (i = init; condition; --i)
2724 * The initialization of the for loop should either be an assignment
2725 * to an integer variable, or a declaration of such a variable with
2726 * initialization.
2728 * The condition is allowed to contain nested accesses, provided
2729 * they are not being written to inside the body of the loop.
2730 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2731 * essentially treated as a while loop, with iteration domain
2732 * { [i] : i >= init }.
2734 * We extract a pet_scop for the body and then embed it in a loop with
2735 * iteration domain and schedule
2737 * { [i] : i >= init and condition' }
2738 * { [i] -> [i] }
2740 * or
2742 * { [i] : i <= init and condition' }
2743 * { [i] -> [-i] }
2745 * Where condition' is equal to condition if the latter is
2746 * a simple upper [lower] bound and a condition that is extended
2747 * to apply to all previous iterations otherwise.
2749 * If the condition is non-affine, then we drop the condition from the
2750 * iteration domain and instead create a separate statement
2751 * for evaluating the condition. The body is then filtered to depend
2752 * on the result of the condition evaluating to true on all iterations
2753 * up to the current iteration, while the evaluation the condition itself
2754 * is filtered to depend on the result of the condition evaluating to true
2755 * on all previous iterations.
2756 * The context of the scop representing the body is dropped
2757 * because we don't know how many times the body will be executed,
2758 * if at all.
2760 * If the stride of the loop is not 1, then "i >= init" is replaced by
2762 * (exists a: i = init + stride * a and a >= 0)
2764 * If the loop iterator i is unsigned, then wrapping may occur.
2765 * During the computation, we work with a virtual iterator that
2766 * does not wrap. However, the condition in the code applies
2767 * to the wrapped value, so we need to change condition(i)
2768 * into condition([i % 2^width]).
2769 * After computing the virtual domain and schedule, we apply
2770 * the function { [v] -> [v % 2^width] } to the domain and the domain
2771 * of the schedule. In order not to lose any information, we also
2772 * need to intersect the domain of the schedule with the virtual domain
2773 * first, since some iterations in the wrapped domain may be scheduled
2774 * several times, typically an infinite number of times.
2775 * Note that there may be no need to perform this final wrapping
2776 * if the loop condition (after wrapping) satisfies certain conditions.
2777 * However, the is_simple_bound condition is not enough since it doesn't
2778 * check if there even is an upper bound.
2780 * If the loop condition is non-affine, then we keep the virtual
2781 * iterator in the iteration domain and instead replace all accesses
2782 * to the original iterator by the wrapping of the virtual iterator.
2784 * Wrapping on unsigned iterators can be avoided entirely if
2785 * loop condition is simple, the loop iterator is incremented
2786 * [decremented] by one and the last value before wrapping cannot
2787 * possibly satisfy the loop condition.
2789 * Before extracting a pet_scop from the body we remove all
2790 * assignments in assigned_value to variables that are assigned
2791 * somewhere in the body of the loop.
2793 * Valid parameters for a for loop are those for which the initial
2794 * value itself, the increment on each domain iteration and
2795 * the condition on both the initial value and
2796 * the result of incrementing the iterator for each iteration of the domain
2797 * can be evaluated.
2798 * If the loop condition is non-affine, then we only consider validity
2799 * of the initial value.
2801 * If the body contains any break, then we keep track of it in "skip"
2802 * (if the skip condition is affine) or it is handled in scop_add_break
2803 * (if the skip condition is not affine).
2804 * Note that the affine break condition needs to be considered with
2805 * respect to previous iterations in the virtual domain (if any)
2806 * and that the domain needs to be kept virtual if there is a non-affine
2807 * break condition.
2809 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2811 BinaryOperator *ass;
2812 Decl *decl;
2813 Stmt *init;
2814 Expr *lhs, *rhs;
2815 ValueDecl *iv;
2816 isl_space *space;
2817 isl_set *domain;
2818 isl_map *sched;
2819 isl_set *cond = NULL;
2820 isl_set *skip = NULL;
2821 isl_id *id, *id_test = NULL, *id_break_test;
2822 struct pet_scop *scop, *scop_cond = NULL;
2823 assigned_value_cache cache(assigned_value);
2824 isl_val *inc;
2825 bool is_one;
2826 bool is_unsigned;
2827 bool is_simple;
2828 bool is_virtual;
2829 bool keep_virtual = false;
2830 bool has_affine_break;
2831 bool has_var_break;
2832 isl_aff *wrap = NULL;
2833 isl_pw_aff *pa, *pa_inc, *init_val;
2834 isl_set *valid_init;
2835 isl_set *valid_cond;
2836 isl_set *valid_cond_init;
2837 isl_set *valid_cond_next;
2838 isl_set *valid_inc;
2839 int stmt_id;
2841 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2842 return extract_infinite_for(stmt);
2844 init = stmt->getInit();
2845 if (!init) {
2846 unsupported(stmt);
2847 return NULL;
2849 if ((ass = initialization_assignment(init)) != NULL) {
2850 iv = extract_induction_variable(ass);
2851 if (!iv)
2852 return NULL;
2853 lhs = ass->getLHS();
2854 rhs = ass->getRHS();
2855 } else if ((decl = initialization_declaration(init)) != NULL) {
2856 VarDecl *var = extract_induction_variable(init, decl);
2857 if (!var)
2858 return NULL;
2859 iv = var;
2860 rhs = var->getInit();
2861 lhs = create_DeclRefExpr(var);
2862 } else {
2863 unsupported(stmt->getInit());
2864 return NULL;
2867 pa_inc = extract_increment(stmt, iv);
2868 if (!pa_inc)
2869 return NULL;
2871 inc = NULL;
2872 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
2873 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
2874 isl_pw_aff_free(pa_inc);
2875 unsupported(stmt->getInc());
2876 isl_val_free(inc);
2877 return NULL;
2879 valid_inc = isl_pw_aff_domain(pa_inc);
2881 is_unsigned = iv->getType()->isUnsignedIntegerType();
2883 assigned_value.erase(iv);
2884 clear_assignments clear(assigned_value);
2885 clear.TraverseStmt(stmt->getBody());
2887 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2889 pa = try_extract_nested_condition(stmt->getCond());
2890 if (allow_nested && (!pa || has_nested(pa)))
2891 stmt_id = n_stmt++;
2893 scop = extract(stmt->getBody());
2895 has_affine_break = scop &&
2896 pet_scop_has_affine_skip(scop, pet_skip_later);
2897 if (has_affine_break)
2898 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2899 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
2900 if (has_var_break) {
2901 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
2902 keep_virtual = true;
2905 if (pa && !is_nested_allowed(pa, scop)) {
2906 isl_pw_aff_free(pa);
2907 pa = NULL;
2910 if (!allow_nested && !pa)
2911 pa = try_extract_affine_condition(stmt->getCond());
2912 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2913 cond = isl_pw_aff_non_zero_set(pa);
2914 if (allow_nested && !cond) {
2915 isl_multi_pw_aff *test_index;
2916 isl_map *test_access;
2917 int save_n_stmt = n_stmt;
2918 test_index = create_test_index(ctx, n_test++);
2919 n_stmt = stmt_id;
2920 scop_cond = extract_non_affine_condition(stmt->getCond(),
2921 isl_multi_pw_aff_copy(test_index));
2922 n_stmt = save_n_stmt;
2923 test_access = isl_map_from_multi_pw_aff(test_index);
2924 scop_cond = scop_add_array(scop_cond, test_access, ast_context);
2925 id_test = isl_map_get_tuple_id(test_access, isl_dim_out);
2926 isl_map_free(test_access);
2927 scop_cond = pet_scop_prefix(scop_cond, 0);
2928 scop = pet_scop_reset_context(scop);
2929 scop = pet_scop_prefix(scop, 1);
2930 keep_virtual = true;
2931 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
2934 cond = embed(cond, isl_id_copy(id));
2935 skip = embed(skip, isl_id_copy(id));
2936 valid_cond = isl_set_coalesce(valid_cond);
2937 valid_cond = embed(valid_cond, isl_id_copy(id));
2938 valid_inc = embed(valid_inc, isl_id_copy(id));
2939 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
2940 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
2942 init_val = extract_affine(rhs);
2943 valid_cond_init = enforce_subset(
2944 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
2945 isl_set_copy(valid_cond));
2946 if (is_one && !is_virtual) {
2947 isl_pw_aff_free(init_val);
2948 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
2949 lhs, rhs, init);
2950 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2951 valid_init = set_project_out_by_id(valid_init, id);
2952 domain = isl_pw_aff_non_zero_set(pa);
2953 } else {
2954 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
2955 domain = strided_domain(isl_id_copy(id), init_val,
2956 isl_val_copy(inc));
2959 domain = embed(domain, isl_id_copy(id));
2960 if (is_virtual) {
2961 isl_map *rev_wrap;
2962 wrap = compute_wrapping(isl_set_get_space(cond), iv);
2963 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
2964 rev_wrap = isl_map_reverse(rev_wrap);
2965 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
2966 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
2967 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
2968 valid_inc = isl_set_apply(valid_inc, rev_wrap);
2970 is_simple = is_simple_bound(cond, inc);
2971 if (!is_simple) {
2972 cond = isl_set_gist(cond, isl_set_copy(domain));
2973 is_simple = is_simple_bound(cond, inc);
2975 if (!is_simple)
2976 cond = valid_for_each_iteration(cond,
2977 isl_set_copy(domain), isl_val_copy(inc));
2978 domain = isl_set_intersect(domain, cond);
2979 if (has_affine_break) {
2980 skip = isl_set_intersect(skip , isl_set_copy(domain));
2981 skip = after(skip, isl_val_sgn(inc));
2982 domain = isl_set_subtract(domain, skip);
2984 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
2985 space = isl_space_from_domain(isl_set_get_space(domain));
2986 space = isl_space_add_dims(space, isl_dim_out, 1);
2987 sched = isl_map_universe(space);
2988 if (isl_val_is_pos(inc))
2989 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
2990 else
2991 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
2993 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
2994 isl_val_copy(inc));
2995 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
2997 if (is_virtual && !keep_virtual) {
2998 isl_map *wrap_map = isl_map_from_aff(wrap);
2999 wrap_map = isl_map_set_dim_id(wrap_map,
3000 isl_dim_out, 0, isl_id_copy(id));
3001 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
3002 domain = isl_set_apply(domain, isl_map_copy(wrap_map));
3003 sched = isl_map_apply_domain(sched, wrap_map);
3005 if (!(is_virtual && keep_virtual))
3006 wrap = identity_aff(domain);
3008 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
3009 isl_map_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
3010 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
3011 scop = resolve_nested(scop);
3012 if (has_var_break)
3013 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
3014 isl_val_copy(inc));
3015 if (id_test) {
3016 scop = scop_add_while(scop_cond, scop, id_test, domain,
3017 isl_val_copy(inc));
3018 isl_set_free(valid_inc);
3019 } else {
3020 scop = pet_scop_restrict_context(scop, valid_inc);
3021 scop = pet_scop_restrict_context(scop, valid_cond_next);
3022 scop = pet_scop_restrict_context(scop, valid_cond_init);
3023 isl_set_free(domain);
3025 clear_assignment(assigned_value, iv);
3027 isl_val_free(inc);
3029 scop = pet_scop_restrict_context(scop, valid_init);
3031 return scop;
3034 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
3036 return extract(stmt->children(), true, skip_declarations);
3039 /* Does parameter "pos" of "map" refer to a nested access?
3041 static bool is_nested_parameter(__isl_keep isl_map *map, int pos)
3043 bool nested;
3044 isl_id *id;
3046 id = isl_map_get_dim_id(map, isl_dim_param, pos);
3047 nested = is_nested_parameter(id);
3048 isl_id_free(id);
3050 return nested;
3053 /* How many parameters of "space" refer to nested accesses, i.e., have no name?
3055 static int n_nested_parameter(__isl_keep isl_space *space)
3057 int n = 0;
3058 int nparam;
3060 nparam = isl_space_dim(space, isl_dim_param);
3061 for (int i = 0; i < nparam; ++i)
3062 if (is_nested_parameter(space, i))
3063 ++n;
3065 return n;
3068 /* How many parameters of "map" refer to nested accesses, i.e., have no name?
3070 static int n_nested_parameter(__isl_keep isl_map *map)
3072 isl_space *space;
3073 int n;
3075 space = isl_map_get_space(map);
3076 n = n_nested_parameter(space);
3077 isl_space_free(space);
3079 return n;
3082 /* For each nested access parameter in "space",
3083 * construct a corresponding pet_expr, place it in args and
3084 * record its position in "param2pos".
3085 * "n_arg" is the number of elements that are already in args.
3086 * The position recorded in "param2pos" takes this number into account.
3087 * If the pet_expr corresponding to a parameter is identical to
3088 * the pet_expr corresponding to an earlier parameter, then these two
3089 * parameters are made to refer to the same element in args.
3091 * Return the final number of elements in args or -1 if an error has occurred.
3093 int PetScan::extract_nested(__isl_keep isl_space *space,
3094 int n_arg, struct pet_expr **args, std::map<int,int> &param2pos)
3096 int nparam;
3098 nparam = isl_space_dim(space, isl_dim_param);
3099 for (int i = 0; i < nparam; ++i) {
3100 int j;
3101 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3102 Expr *nested;
3104 if (!is_nested_parameter(id)) {
3105 isl_id_free(id);
3106 continue;
3109 nested = (Expr *) isl_id_get_user(id);
3110 args[n_arg] = extract_expr(nested);
3111 if (!args[n_arg])
3112 return -1;
3114 for (j = 0; j < n_arg; ++j)
3115 if (pet_expr_is_equal(args[j], args[n_arg]))
3116 break;
3118 if (j < n_arg) {
3119 pet_expr_free(args[n_arg]);
3120 args[n_arg] = NULL;
3121 param2pos[i] = j;
3122 } else
3123 param2pos[i] = n_arg++;
3125 isl_id_free(id);
3128 return n_arg;
3131 /* For each nested access parameter in the access relations in "expr",
3132 * construct a corresponding pet_expr, place it in expr->args and
3133 * record its position in "param2pos".
3134 * n is the number of nested access parameters.
3136 struct pet_expr *PetScan::extract_nested(struct pet_expr *expr, int n,
3137 std::map<int,int> &param2pos)
3139 isl_space *space;
3141 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
3142 expr->n_arg = n;
3143 if (!expr->args)
3144 goto error;
3146 space = isl_map_get_space(expr->acc.access);
3147 n = extract_nested(space, 0, expr->args, param2pos);
3148 isl_space_free(space);
3150 if (n < 0)
3151 goto error;
3153 expr->n_arg = n;
3154 return expr;
3155 error:
3156 pet_expr_free(expr);
3157 return NULL;
3160 /* Look for parameters in any access relation in "expr" that
3161 * refer to nested accesses. In particular, these are
3162 * parameters with no name.
3164 * If there are any such parameters, then the domain of the access
3165 * relation, which is still [] at this point, is replaced by
3166 * [[] -> [t_1,...,t_n]], with n the number of these parameters
3167 * (after identifying identical nested accesses).
3168 * The parameters are then equated to the corresponding t dimensions
3169 * and subsequently projected out.
3170 * param2pos maps the position of the parameter to the position
3171 * of the corresponding t dimension.
3173 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
3175 int n;
3176 int nparam;
3177 int n_in;
3178 isl_space *dim;
3179 isl_map *map;
3180 std::map<int,int> param2pos;
3182 if (!expr)
3183 return expr;
3185 for (int i = 0; i < expr->n_arg; ++i) {
3186 expr->args[i] = resolve_nested(expr->args[i]);
3187 if (!expr->args[i]) {
3188 pet_expr_free(expr);
3189 return NULL;
3193 if (expr->type != pet_expr_access)
3194 return expr;
3196 n = n_nested_parameter(expr->acc.access);
3197 if (n == 0)
3198 return expr;
3200 expr = extract_nested(expr, n, param2pos);
3201 if (!expr)
3202 return NULL;
3204 n = expr->n_arg;
3205 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
3206 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
3207 dim = isl_map_get_space(expr->acc.access);
3208 dim = isl_space_domain(dim);
3209 dim = isl_space_from_domain(dim);
3210 dim = isl_space_add_dims(dim, isl_dim_out, n);
3211 map = isl_map_universe(dim);
3212 map = isl_map_domain_map(map);
3213 map = isl_map_reverse(map);
3214 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
3216 for (int i = nparam - 1; i >= 0; --i) {
3217 isl_id *id = isl_map_get_dim_id(expr->acc.access,
3218 isl_dim_param, i);
3219 if (!is_nested_parameter(id)) {
3220 isl_id_free(id);
3221 continue;
3224 expr->acc.access = isl_map_equate(expr->acc.access,
3225 isl_dim_param, i, isl_dim_in,
3226 n_in + param2pos[i]);
3227 expr->acc.access = isl_map_project_out(expr->acc.access,
3228 isl_dim_param, i, 1);
3230 isl_id_free(id);
3233 return expr;
3234 error:
3235 pet_expr_free(expr);
3236 return NULL;
3239 /* Return the file offset of the expansion location of "Loc".
3241 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3243 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3246 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3248 /* Return a SourceLocation for the location after the first semicolon
3249 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3250 * call it and also skip trailing spaces and newline.
3252 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3253 const LangOptions &LO)
3255 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3258 #else
3260 /* Return a SourceLocation for the location after the first semicolon
3261 * after "loc". If Lexer::findLocationAfterToken is not available,
3262 * we look in the underlying character data for the first semicolon.
3264 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3265 const LangOptions &LO)
3267 const char *semi;
3268 const char *s = SM.getCharacterData(loc);
3270 semi = strchr(s, ';');
3271 if (!semi)
3272 return SourceLocation();
3273 return loc.getFileLocWithOffset(semi + 1 - s);
3276 #endif
3278 /* If the token at "loc" is the first token on the line, then return
3279 * a location referring to the start of the line.
3280 * Otherwise, return "loc".
3282 * This function is used to extend a scop to the start of the line
3283 * if the first token of the scop is also the first token on the line.
3285 * We look for the first token on the line. If its location is equal to "loc",
3286 * then the latter is the location of the first token on the line.
3288 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3289 SourceManager &SM, const LangOptions &LO)
3291 std::pair<FileID, unsigned> file_offset_pair;
3292 llvm::StringRef file;
3293 const char *pos;
3294 Token tok;
3295 SourceLocation token_loc, line_loc;
3296 int col;
3298 loc = SM.getExpansionLoc(loc);
3299 col = SM.getExpansionColumnNumber(loc);
3300 line_loc = loc.getLocWithOffset(1 - col);
3301 file_offset_pair = SM.getDecomposedLoc(line_loc);
3302 file = SM.getBufferData(file_offset_pair.first, NULL);
3303 pos = file.data() + file_offset_pair.second;
3305 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3306 file.begin(), pos, file.end());
3307 lexer.LexFromRawLexer(tok);
3308 token_loc = tok.getLocation();
3310 if (token_loc == loc)
3311 return line_loc;
3312 else
3313 return loc;
3316 /* Convert a top-level pet_expr to a pet_scop with one statement.
3317 * This mainly involves resolving nested expression parameters
3318 * and setting the name of the iteration space.
3319 * The name is given by "label" if it is non-NULL. Otherwise,
3320 * it is of the form S_<n_stmt>.
3321 * start and end of the pet_scop are derived from those of "stmt".
3323 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr,
3324 __isl_take isl_id *label)
3326 struct pet_stmt *ps;
3327 struct pet_scop *scop;
3328 SourceLocation loc = stmt->getLocStart();
3329 SourceManager &SM = PP.getSourceManager();
3330 const LangOptions &LO = PP.getLangOpts();
3331 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3332 unsigned start, end;
3334 expr = resolve_nested(expr);
3335 ps = pet_stmt_from_pet_expr(ctx, line, label, n_stmt++, expr);
3336 scop = pet_scop_from_pet_stmt(ctx, ps);
3338 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3339 start = getExpansionOffset(SM, loc);
3340 loc = stmt->getLocEnd();
3341 loc = location_after_semi(loc, SM, LO);
3342 end = getExpansionOffset(SM, loc);
3344 scop = pet_scop_update_start_end(scop, start, end);
3345 return scop;
3348 /* Check if we can extract an affine expression from "expr".
3349 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3350 * We turn on autodetection so that we won't generate any warnings
3351 * and turn off nesting, so that we won't accept any non-affine constructs.
3353 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3355 isl_pw_aff *pwaff;
3356 int save_autodetect = options->autodetect;
3357 bool save_nesting = nesting_enabled;
3359 options->autodetect = 1;
3360 nesting_enabled = false;
3362 pwaff = extract_affine(expr);
3364 options->autodetect = save_autodetect;
3365 nesting_enabled = save_nesting;
3367 return pwaff;
3370 /* Check whether "expr" is an affine expression.
3372 bool PetScan::is_affine(Expr *expr)
3374 isl_pw_aff *pwaff;
3376 pwaff = try_extract_affine(expr);
3377 isl_pw_aff_free(pwaff);
3379 return pwaff != NULL;
3382 /* Check if we can extract an affine constraint from "expr".
3383 * Return the constraint as an isl_set if we can and NULL otherwise.
3384 * We turn on autodetection so that we won't generate any warnings
3385 * and turn off nesting, so that we won't accept any non-affine constructs.
3387 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3389 isl_pw_aff *cond;
3390 int save_autodetect = options->autodetect;
3391 bool save_nesting = nesting_enabled;
3393 options->autodetect = 1;
3394 nesting_enabled = false;
3396 cond = extract_condition(expr);
3398 options->autodetect = save_autodetect;
3399 nesting_enabled = save_nesting;
3401 return cond;
3404 /* Check whether "expr" is an affine constraint.
3406 bool PetScan::is_affine_condition(Expr *expr)
3408 isl_pw_aff *cond;
3410 cond = try_extract_affine_condition(expr);
3411 isl_pw_aff_free(cond);
3413 return cond != NULL;
3416 /* Check if we can extract a condition from "expr".
3417 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3418 * If allow_nested is set, then the condition may involve parameters
3419 * corresponding to nested accesses.
3420 * We turn on autodetection so that we won't generate any warnings.
3422 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3424 isl_pw_aff *cond;
3425 int save_autodetect = options->autodetect;
3426 bool save_nesting = nesting_enabled;
3428 options->autodetect = 1;
3429 nesting_enabled = allow_nested;
3430 cond = extract_condition(expr);
3432 options->autodetect = save_autodetect;
3433 nesting_enabled = save_nesting;
3435 return cond;
3438 /* If the top-level expression of "stmt" is an assignment, then
3439 * return that assignment as a BinaryOperator.
3440 * Otherwise return NULL.
3442 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3444 BinaryOperator *ass;
3446 if (!stmt)
3447 return NULL;
3448 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3449 return NULL;
3451 ass = cast<BinaryOperator>(stmt);
3452 if(ass->getOpcode() != BO_Assign)
3453 return NULL;
3455 return ass;
3458 /* Check if the given if statement is a conditional assignement
3459 * with a non-affine condition. If so, construct a pet_scop
3460 * corresponding to this conditional assignment. Otherwise return NULL.
3462 * In particular we check if "stmt" is of the form
3464 * if (condition)
3465 * a = f(...);
3466 * else
3467 * a = g(...);
3469 * where a is some array or scalar access.
3470 * The constructed pet_scop then corresponds to the expression
3472 * a = condition ? f(...) : g(...)
3474 * All access relations in f(...) are intersected with condition
3475 * while all access relation in g(...) are intersected with the complement.
3477 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3479 BinaryOperator *ass_then, *ass_else;
3480 isl_multi_pw_aff *write_then, *write_else;
3481 isl_set *cond, *comp;
3482 isl_multi_pw_aff *index;
3483 isl_pw_aff *pa;
3484 int equal;
3485 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3486 bool save_nesting = nesting_enabled;
3488 if (!options->detect_conditional_assignment)
3489 return NULL;
3491 ass_then = top_assignment_or_null(stmt->getThen());
3492 ass_else = top_assignment_or_null(stmt->getElse());
3494 if (!ass_then || !ass_else)
3495 return NULL;
3497 if (is_affine_condition(stmt->getCond()))
3498 return NULL;
3500 write_then = extract_index(ass_then->getLHS());
3501 write_else = extract_index(ass_else->getLHS());
3503 equal = isl_multi_pw_aff_plain_is_equal(write_then, write_else);
3504 isl_multi_pw_aff_free(write_else);
3505 if (equal < 0 || !equal) {
3506 isl_multi_pw_aff_free(write_then);
3507 return NULL;
3510 nesting_enabled = allow_nested;
3511 pa = extract_condition(stmt->getCond());
3512 nesting_enabled = save_nesting;
3513 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3514 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3515 index = isl_multi_pw_aff_from_range(isl_multi_pw_aff_from_pw_aff(pa));
3517 pe_cond = pet_expr_from_index(index);
3519 pe_then = extract_expr(ass_then->getRHS());
3520 pe_then = pet_expr_restrict(pe_then, cond);
3521 pe_else = extract_expr(ass_else->getRHS());
3522 pe_else = pet_expr_restrict(pe_else, comp);
3524 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
3525 pe_write = pet_expr_from_index_and_depth(write_then,
3526 extract_depth(write_then));
3527 if (pe_write) {
3528 pe_write->acc.write = 1;
3529 pe_write->acc.read = 0;
3531 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
3532 return extract(stmt, pe);
3535 /* Create a pet_scop with a single statement evaluating "cond"
3536 * and writing the result to a virtual scalar, as expressed by
3537 * "index".
3539 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
3540 __isl_take isl_multi_pw_aff *index)
3542 struct pet_expr *expr, *write;
3543 struct pet_stmt *ps;
3544 struct pet_scop *scop;
3545 SourceLocation loc = cond->getLocStart();
3546 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3548 write = pet_expr_from_index(index);
3549 if (write) {
3550 write->acc.write = 1;
3551 write->acc.read = 0;
3553 expr = extract_expr(cond);
3554 expr = resolve_nested(expr);
3555 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
3556 ps = pet_stmt_from_pet_expr(ctx, line, NULL, n_stmt++, expr);
3557 scop = pet_scop_from_pet_stmt(ctx, ps);
3558 scop = resolve_nested(scop);
3560 return scop;
3563 extern "C" {
3564 static struct pet_expr *embed_access(struct pet_expr *expr, void *user);
3567 /* Apply the map pointed to by "user" to the domain of the access
3568 * relation associated to "expr", thereby embedding it in the range of the map.
3569 * The domain of both relations is the zero-dimensional domain.
3571 static struct pet_expr *embed_access(struct pet_expr *expr, void *user)
3573 isl_map *map = (isl_map *) user;
3575 expr->acc.access = isl_map_apply_domain(expr->acc.access,
3576 isl_map_copy(map));
3577 if (!expr->acc.access)
3578 goto error;
3580 return expr;
3581 error:
3582 pet_expr_free(expr);
3583 return NULL;
3586 /* Apply "map" to all access relations in "expr".
3588 static struct pet_expr *embed(struct pet_expr *expr, __isl_keep isl_map *map)
3590 return pet_expr_map_access(expr, &embed_access, map);
3593 /* How many parameters of "set" refer to nested accesses, i.e., have no name?
3595 static int n_nested_parameter(__isl_keep isl_set *set)
3597 isl_space *space;
3598 int n;
3600 space = isl_set_get_space(set);
3601 n = n_nested_parameter(space);
3602 isl_space_free(space);
3604 return n;
3607 /* Remove all parameters from "map" that refer to nested accesses.
3609 static __isl_give isl_map *remove_nested_parameters(__isl_take isl_map *map)
3611 int nparam;
3612 isl_space *space;
3614 space = isl_map_get_space(map);
3615 nparam = isl_space_dim(space, isl_dim_param);
3616 for (int i = nparam - 1; i >= 0; --i)
3617 if (is_nested_parameter(space, i))
3618 map = isl_map_project_out(map, isl_dim_param, i, 1);
3619 isl_space_free(space);
3621 return map;
3624 /* Remove all parameters from the access relation of "expr"
3625 * that refer to nested accesses.
3627 static struct pet_expr *remove_nested_parameters(struct pet_expr *expr)
3629 expr->acc.access = remove_nested_parameters(expr->acc.access);
3630 if (!expr->acc.access)
3631 goto error;
3633 return expr;
3634 error:
3635 pet_expr_free(expr);
3636 return NULL;
3639 extern "C" {
3640 static struct pet_expr *expr_remove_nested_parameters(
3641 struct pet_expr *expr, void *user);
3644 static struct pet_expr *expr_remove_nested_parameters(
3645 struct pet_expr *expr, void *user)
3647 return remove_nested_parameters(expr);
3650 /* Remove all nested access parameters from the schedule and all
3651 * accesses of "stmt".
3652 * There is no need to remove them from the domain as these parameters
3653 * have already been removed from the domain when this function is called.
3655 static struct pet_stmt *remove_nested_parameters(struct pet_stmt *stmt)
3657 if (!stmt)
3658 return NULL;
3659 stmt->schedule = remove_nested_parameters(stmt->schedule);
3660 stmt->body = pet_expr_map_access(stmt->body,
3661 &expr_remove_nested_parameters, NULL);
3662 if (!stmt->schedule || !stmt->body)
3663 goto error;
3664 for (int i = 0; i < stmt->n_arg; ++i) {
3665 stmt->args[i] = pet_expr_map_access(stmt->args[i],
3666 &expr_remove_nested_parameters, NULL);
3667 if (!stmt->args[i])
3668 goto error;
3671 return stmt;
3672 error:
3673 pet_stmt_free(stmt);
3674 return NULL;
3677 /* For each nested access parameter in the domain of "stmt",
3678 * construct a corresponding pet_expr, place it before the original
3679 * elements in stmt->args and record its position in "param2pos".
3680 * n is the number of nested access parameters.
3682 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3683 std::map<int,int> &param2pos)
3685 int i;
3686 isl_space *space;
3687 int n_arg;
3688 struct pet_expr **args;
3690 n_arg = stmt->n_arg;
3691 args = isl_calloc_array(ctx, struct pet_expr *, n + n_arg);
3692 if (!args)
3693 goto error;
3695 space = isl_set_get_space(stmt->domain);
3696 n_arg = extract_nested(space, 0, args, param2pos);
3697 isl_space_free(space);
3699 if (n_arg < 0)
3700 goto error;
3702 for (i = 0; i < stmt->n_arg; ++i)
3703 args[n_arg + i] = stmt->args[i];
3704 free(stmt->args);
3705 stmt->args = args;
3706 stmt->n_arg += n_arg;
3708 return stmt;
3709 error:
3710 if (args) {
3711 for (i = 0; i < n; ++i)
3712 pet_expr_free(args[i]);
3713 free(args);
3715 pet_stmt_free(stmt);
3716 return NULL;
3719 /* Check whether any of the arguments i of "stmt" starting at position "n"
3720 * is equal to one of the first "n" arguments j.
3721 * If so, combine the constraints on arguments i and j and remove
3722 * argument i.
3724 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3726 int i, j;
3727 isl_map *map;
3729 if (!stmt)
3730 return NULL;
3731 if (n == 0)
3732 return stmt;
3733 if (n == stmt->n_arg)
3734 return stmt;
3736 map = isl_set_unwrap(stmt->domain);
3738 for (i = stmt->n_arg - 1; i >= n; --i) {
3739 for (j = 0; j < n; ++j)
3740 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3741 break;
3742 if (j >= n)
3743 continue;
3745 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3746 map = isl_map_project_out(map, isl_dim_out, i, 1);
3748 pet_expr_free(stmt->args[i]);
3749 for (j = i; j + 1 < stmt->n_arg; ++j)
3750 stmt->args[j] = stmt->args[j + 1];
3751 stmt->n_arg--;
3754 stmt->domain = isl_map_wrap(map);
3755 if (!stmt->domain)
3756 goto error;
3757 return stmt;
3758 error:
3759 pet_stmt_free(stmt);
3760 return NULL;
3763 /* Look for parameters in the iteration domain of "stmt" that
3764 * refer to nested accesses. In particular, these are
3765 * parameters with no name.
3767 * If there are any such parameters, then as many extra variables
3768 * (after identifying identical nested accesses) are inserted in the
3769 * range of the map wrapped inside the domain, before the original variables.
3770 * If the original domain is not a wrapped map, then a new wrapped
3771 * map is created with zero output dimensions.
3772 * The parameters are then equated to the corresponding output dimensions
3773 * and subsequently projected out, from the iteration domain,
3774 * the schedule and the access relations.
3775 * For each of the output dimensions, a corresponding argument
3776 * expression is inserted. Initially they are created with
3777 * a zero-dimensional domain, so they have to be embedded
3778 * in the current iteration domain.
3779 * param2pos maps the position of the parameter to the position
3780 * of the corresponding output dimension in the wrapped map.
3782 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3784 int n;
3785 int nparam;
3786 unsigned n_arg;
3787 isl_map *map;
3788 std::map<int,int> param2pos;
3790 if (!stmt)
3791 return NULL;
3793 n = n_nested_parameter(stmt->domain);
3794 if (n == 0)
3795 return stmt;
3797 n_arg = stmt->n_arg;
3798 stmt = extract_nested(stmt, n, param2pos);
3799 if (!stmt)
3800 return NULL;
3802 n = stmt->n_arg - n_arg;
3803 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3804 if (isl_set_is_wrapping(stmt->domain))
3805 map = isl_set_unwrap(stmt->domain);
3806 else
3807 map = isl_map_from_domain(stmt->domain);
3808 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3810 for (int i = nparam - 1; i >= 0; --i) {
3811 isl_id *id;
3813 if (!is_nested_parameter(map, i))
3814 continue;
3816 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
3817 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3818 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3819 param2pos[i]);
3820 map = isl_map_project_out(map, isl_dim_param, i, 1);
3823 stmt->domain = isl_map_wrap(map);
3825 map = isl_set_unwrap(isl_set_copy(stmt->domain));
3826 map = isl_map_from_range(isl_map_domain(map));
3827 for (int pos = 0; pos < n; ++pos)
3828 stmt->args[pos] = embed(stmt->args[pos], map);
3829 isl_map_free(map);
3831 stmt = remove_nested_parameters(stmt);
3832 stmt = remove_duplicate_arguments(stmt, n);
3834 return stmt;
3835 error:
3836 pet_stmt_free(stmt);
3837 return NULL;
3840 /* For each statement in "scop", move the parameters that correspond
3841 * to nested access into the ranges of the domains and create
3842 * corresponding argument expressions.
3844 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3846 if (!scop)
3847 return NULL;
3849 for (int i = 0; i < scop->n_stmt; ++i) {
3850 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3851 if (!scop->stmts[i])
3852 goto error;
3855 return scop;
3856 error:
3857 pet_scop_free(scop);
3858 return NULL;
3861 /* Given an access expression "expr", is the variable accessed by
3862 * "expr" assigned anywhere inside "scop"?
3864 static bool is_assigned(pet_expr *expr, pet_scop *scop)
3866 bool assigned = false;
3867 isl_id *id;
3869 id = pet_expr_access_get_id(expr);
3870 assigned = pet_scop_writes(scop, id);
3871 isl_id_free(id);
3873 return assigned;
3876 /* Are all nested access parameters in "pa" allowed given "scop".
3877 * In particular, is none of them written by anywhere inside "scop".
3879 * If "scop" has any skip conditions, then no nested access parameters
3880 * are allowed. In particular, if there is any nested access in a guard
3881 * for a piece of code containing a "continue", then we want to introduce
3882 * a separate statement for evaluating this guard so that we can express
3883 * that the result is false for all previous iterations.
3885 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3887 int nparam;
3889 if (!scop)
3890 return true;
3892 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3893 for (int i = 0; i < nparam; ++i) {
3894 Expr *nested;
3895 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3896 pet_expr *expr;
3897 bool allowed;
3899 if (!is_nested_parameter(id)) {
3900 isl_id_free(id);
3901 continue;
3904 if (pet_scop_has_skip(scop, pet_skip_now)) {
3905 isl_id_free(id);
3906 return false;
3909 nested = (Expr *) isl_id_get_user(id);
3910 expr = extract_expr(nested);
3911 allowed = expr && expr->type == pet_expr_access &&
3912 !is_assigned(expr, scop);
3914 pet_expr_free(expr);
3915 isl_id_free(id);
3917 if (!allowed)
3918 return false;
3921 return true;
3924 /* Do we need to construct a skip condition of the given type
3925 * on an if statement, given that the if condition is non-affine?
3927 * pet_scop_filter_skip can only handle the case where the if condition
3928 * holds (the then branch) and the skip condition is universal.
3929 * In any other case, we need to construct a new skip condition.
3931 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3932 bool have_else, enum pet_skip type)
3934 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
3935 return true;
3936 if (scop_then && pet_scop_has_skip(scop_then, type) &&
3937 !pet_scop_has_universal_skip(scop_then, type))
3938 return true;
3939 return false;
3942 /* Do we need to construct a skip condition of the given type
3943 * on an if statement, given that the if condition is affine?
3945 * There is no need to construct a new skip condition if all
3946 * the skip conditions are affine.
3948 static bool need_skip_aff(struct pet_scop *scop_then,
3949 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
3951 if (scop_then && pet_scop_has_var_skip(scop_then, type))
3952 return true;
3953 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
3954 return true;
3955 return false;
3958 /* Do we need to construct a skip condition of the given type
3959 * on an if statement?
3961 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
3962 bool have_else, enum pet_skip type, bool affine)
3964 if (affine)
3965 return need_skip_aff(scop_then, scop_else, have_else, type);
3966 else
3967 return need_skip(scop_then, scop_else, have_else, type);
3970 /* Construct an affine expression pet_expr that evaluates
3971 * to the constant "val".
3973 static struct pet_expr *universally(isl_ctx *ctx, int val)
3975 isl_local_space *ls;
3976 isl_val *v;
3977 isl_aff *aff;
3978 isl_multi_pw_aff *mpa;
3980 ls = isl_local_space_from_space(isl_space_set_alloc(ctx, 0, 0));
3981 aff = isl_aff_val_on_domain(ls, isl_val_int_from_si(ctx, val));
3982 mpa = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
3984 return pet_expr_from_index(mpa);
3987 /* Construct an affine expression pet_expr that evaluates
3988 * to the constant 1.
3990 static struct pet_expr *universally_true(isl_ctx *ctx)
3992 return universally(ctx, 1);
3995 /* Construct an affine expression pet_expr that evaluates
3996 * to the constant 0.
3998 static struct pet_expr *universally_false(isl_ctx *ctx)
4000 return universally(ctx, 0);
4003 /* Given an index expression "test_index" for the if condition,
4004 * an access relation "skip_access" for the skip condition and
4005 * scops for the then and else branches, construct a scop for
4006 * computing "skip_access".
4008 * The computed scop contains a single statement that essentially does
4010 * skip_cond = test_cond ? skip_cond_then : skip_cond_else
4012 * If the skip conditions of the then and/or else branch are not affine,
4013 * then they need to be filtered by test_index.
4014 * If they are missing, then this means the skip condition is false.
4016 * Since we are constructing a skip condition for the if statement,
4017 * the skip conditions on the then and else branches are removed.
4019 static struct pet_scop *extract_skip(PetScan *scan,
4020 __isl_take isl_multi_pw_aff *test_index,
4021 __isl_take isl_map *skip_access,
4022 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
4023 enum pet_skip type)
4025 struct pet_expr *expr_then, *expr_else, *expr, *expr_skip;
4026 struct pet_stmt *stmt;
4027 struct pet_scop *scop;
4028 isl_ctx *ctx = scan->ctx;
4029 isl_map *test_access;
4031 if (!scop_then)
4032 goto error;
4033 if (have_else && !scop_else)
4034 goto error;
4036 test_access = isl_map_from_multi_pw_aff(
4037 isl_multi_pw_aff_copy(test_index));
4038 if (pet_scop_has_skip(scop_then, type)) {
4039 expr_then = pet_scop_get_skip_expr(scop_then, type);
4040 pet_scop_reset_skip(scop_then, type);
4041 if (!pet_expr_is_affine(expr_then))
4042 expr_then = pet_expr_filter(expr_then,
4043 isl_map_copy(test_access), 1);
4044 } else
4045 expr_then = universally_false(ctx);
4047 if (have_else && pet_scop_has_skip(scop_else, type)) {
4048 expr_else = pet_scop_get_skip_expr(scop_else, type);
4049 pet_scop_reset_skip(scop_else, type);
4050 if (!pet_expr_is_affine(expr_else))
4051 expr_else = pet_expr_filter(expr_else,
4052 isl_map_copy(test_access), 0);
4053 } else
4054 expr_else = universally_false(ctx);
4055 isl_map_free(test_access);
4057 expr = pet_expr_from_index(test_index);
4058 expr = pet_expr_new_ternary(ctx, expr, expr_then, expr_else);
4059 expr_skip = pet_expr_from_access(isl_map_copy(skip_access));
4060 if (expr_skip) {
4061 expr_skip->acc.write = 1;
4062 expr_skip->acc.read = 0;
4064 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4065 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, scan->n_stmt++, expr);
4067 scop = pet_scop_from_pet_stmt(ctx, stmt);
4068 scop = scop_add_array(scop, skip_access, scan->ast_context);
4069 isl_map_free(skip_access);
4071 return scop;
4072 error:
4073 isl_multi_pw_aff_free(test_index);
4074 isl_map_free(skip_access);
4075 return NULL;
4078 /* Is scop's skip_now condition equal to its skip_later condition?
4079 * In particular, this means that it either has no skip_now condition
4080 * or both a skip_now and a skip_later condition (that are equal to each other).
4082 static bool skip_equals_skip_later(struct pet_scop *scop)
4084 int has_skip_now, has_skip_later;
4085 int equal;
4086 isl_set *skip_now, *skip_later;
4088 if (!scop)
4089 return false;
4090 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
4091 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
4092 if (has_skip_now != has_skip_later)
4093 return false;
4094 if (!has_skip_now)
4095 return true;
4097 skip_now = pet_scop_get_skip(scop, pet_skip_now);
4098 skip_later = pet_scop_get_skip(scop, pet_skip_later);
4099 equal = isl_set_is_equal(skip_now, skip_later);
4100 isl_set_free(skip_now);
4101 isl_set_free(skip_later);
4103 return equal;
4106 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
4108 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
4110 pet_scop_reset_skip(scop1, pet_skip_later);
4111 pet_scop_reset_skip(scop2, pet_skip_later);
4114 /* Structure that handles the construction of skip conditions.
4116 * scop_then and scop_else represent the then and else branches
4117 * of the if statement
4119 * skip[type] is true if we need to construct a skip condition of that type
4120 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
4121 * are equal to each other
4122 * access[type] is the virtual array representing the skip condition
4123 * scop[type] is a scop for computing the skip condition
4125 struct pet_skip_info {
4126 isl_ctx *ctx;
4128 bool skip[2];
4129 bool equal;
4130 isl_map *access[2];
4131 struct pet_scop *scop[2];
4133 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
4135 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
4138 /* Structure that handles the construction of skip conditions on if statements.
4140 * scop_then and scop_else represent the then and else branches
4141 * of the if statement
4143 struct pet_skip_info_if : public pet_skip_info {
4144 struct pet_scop *scop_then, *scop_else;
4145 bool have_else;
4147 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4148 struct pet_scop *scop_else, bool have_else, bool affine);
4149 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index,
4150 enum pet_skip type);
4151 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index);
4152 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
4153 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4154 int offset);
4155 struct pet_scop *add(struct pet_scop *scop, int offset);
4158 /* Initialize a pet_skip_info_if structure based on the then and else branches
4159 * and based on whether the if condition is affine or not.
4161 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4162 struct pet_scop *scop_else, bool have_else, bool affine) :
4163 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
4164 have_else(have_else)
4166 skip[pet_skip_now] =
4167 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
4168 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
4169 (!have_else || skip_equals_skip_later(scop_else));
4170 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4171 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
4174 /* If we need to construct a skip condition of the given type,
4175 * then do so now.
4177 * "index" represents the if condition.
4179 void pet_skip_info_if::extract(PetScan *scan,
4180 __isl_keep isl_multi_pw_aff *index, enum pet_skip type)
4182 isl_ctx *ctx;
4184 if (!skip[type])
4185 return;
4187 ctx = isl_multi_pw_aff_get_ctx(index);
4188 access[type] = create_test_access(ctx, scan->n_test++);
4189 scop[type] = extract_skip(scan, isl_multi_pw_aff_copy(index),
4190 isl_map_copy(access[type]),
4191 scop_then, scop_else, have_else, type);
4194 /* Construct the required skip conditions, given the if condition "index".
4196 void pet_skip_info_if::extract(PetScan *scan,
4197 __isl_keep isl_multi_pw_aff *index)
4199 extract(scan, index, pet_skip_now);
4200 extract(scan, index, pet_skip_later);
4201 if (equal)
4202 drop_skip_later(scop_then, scop_else);
4205 /* Construct the required skip conditions, given the if condition "cond".
4207 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
4209 isl_multi_pw_aff *test;
4211 if (!skip[pet_skip_now] && !skip[pet_skip_later])
4212 return;
4214 test = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_copy(cond));
4215 test = isl_multi_pw_aff_from_range(test);
4216 extract(scan, test);
4217 isl_multi_pw_aff_free(test);
4220 /* Add the computed skip condition of the give type to "main" and
4221 * add the scop for computing the condition at the given offset.
4223 * If equal is set, then we only computed a skip condition for pet_skip_now,
4224 * but we also need to set it as main's pet_skip_later.
4226 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
4227 enum pet_skip type, int offset)
4229 isl_set *skip_set;
4231 if (!skip[type])
4232 return main;
4234 skip_set = isl_map_range(access[type]);
4235 access[type] = NULL;
4236 scop[type] = pet_scop_prefix(scop[type], offset);
4237 main = pet_scop_add_par(ctx, main, scop[type]);
4238 scop[type] = NULL;
4240 if (equal)
4241 main = pet_scop_set_skip(main, pet_skip_later,
4242 isl_set_copy(skip_set));
4244 main = pet_scop_set_skip(main, type, skip_set);
4246 return main;
4249 /* Add the computed skip conditions to "main" and
4250 * add the scops for computing the conditions at the given offset.
4252 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
4254 scop = add(scop, pet_skip_now, offset);
4255 scop = add(scop, pet_skip_later, offset);
4257 return scop;
4260 /* Construct a pet_scop for a non-affine if statement.
4262 * We create a separate statement that writes the result
4263 * of the non-affine condition to a virtual scalar.
4264 * A constraint requiring the value of this virtual scalar to be one
4265 * is added to the iteration domains of the then branch.
4266 * Similarly, a constraint requiring the value of this virtual scalar
4267 * to be zero is added to the iteration domains of the else branch, if any.
4268 * We adjust the schedules to ensure that the virtual scalar is written
4269 * before it is read.
4271 * If there are any breaks or continues in the then and/or else
4272 * branches, then we may have to compute a new skip condition.
4273 * This is handled using a pet_skip_info_if object.
4274 * On initialization, the object checks if skip conditions need
4275 * to be computed. If so, it does so in "extract" and adds them in "add".
4277 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
4278 struct pet_scop *scop_then, struct pet_scop *scop_else,
4279 bool have_else, int stmt_id)
4281 struct pet_scop *scop;
4282 isl_multi_pw_aff *test_index;
4283 isl_map *test_access;
4284 int save_n_stmt = n_stmt;
4286 test_index = create_test_index(ctx, n_test++);
4287 test_access = isl_map_from_multi_pw_aff(
4288 isl_multi_pw_aff_copy(test_index));
4289 n_stmt = stmt_id;
4290 scop = extract_non_affine_condition(cond,
4291 isl_multi_pw_aff_copy(test_index));
4292 n_stmt = save_n_stmt;
4293 scop = scop_add_array(scop, test_access, ast_context);
4295 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
4296 skip.extract(this, test_index);
4297 isl_multi_pw_aff_free(test_index);
4299 scop = pet_scop_prefix(scop, 0);
4300 scop_then = pet_scop_prefix(scop_then, 1);
4301 scop_then = pet_scop_filter(scop_then, isl_map_copy(test_access), 1);
4302 if (have_else) {
4303 scop_else = pet_scop_prefix(scop_else, 1);
4304 scop_else = pet_scop_filter(scop_else, test_access, 0);
4305 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
4306 } else
4307 isl_map_free(test_access);
4309 scop = pet_scop_add_seq(ctx, scop, scop_then);
4311 scop = skip.add(scop, 2);
4313 return scop;
4316 /* Construct a pet_scop for an if statement.
4318 * If the condition fits the pattern of a conditional assignment,
4319 * then it is handled by extract_conditional_assignment.
4320 * Otherwise, we do the following.
4322 * If the condition is affine, then the condition is added
4323 * to the iteration domains of the then branch, while the
4324 * opposite of the condition in added to the iteration domains
4325 * of the else branch, if any.
4326 * We allow the condition to be dynamic, i.e., to refer to
4327 * scalars or array elements that may be written to outside
4328 * of the given if statement. These nested accesses are then represented
4329 * as output dimensions in the wrapping iteration domain.
4330 * If it also written _inside_ the then or else branch, then
4331 * we treat the condition as non-affine.
4332 * As explained in extract_non_affine_if, this will introduce
4333 * an extra statement.
4334 * For aesthetic reasons, we want this statement to have a statement
4335 * number that is lower than those of the then and else branches.
4336 * In order to evaluate if will need such a statement, however, we
4337 * first construct scops for the then and else branches.
4338 * We therefore reserve a statement number if we might have to
4339 * introduce such an extra statement.
4341 * If the condition is not affine, then the scop is created in
4342 * extract_non_affine_if.
4344 * If there are any breaks or continues in the then and/or else
4345 * branches, then we may have to compute a new skip condition.
4346 * This is handled using a pet_skip_info_if object.
4347 * On initialization, the object checks if skip conditions need
4348 * to be computed. If so, it does so in "extract" and adds them in "add".
4350 struct pet_scop *PetScan::extract(IfStmt *stmt)
4352 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4353 isl_pw_aff *cond;
4354 int stmt_id;
4355 isl_set *set;
4356 isl_set *valid;
4358 scop = extract_conditional_assignment(stmt);
4359 if (scop)
4360 return scop;
4362 cond = try_extract_nested_condition(stmt->getCond());
4363 if (allow_nested && (!cond || has_nested(cond)))
4364 stmt_id = n_stmt++;
4367 assigned_value_cache cache(assigned_value);
4368 scop_then = extract(stmt->getThen());
4371 if (stmt->getElse()) {
4372 assigned_value_cache cache(assigned_value);
4373 scop_else = extract(stmt->getElse());
4374 if (options->autodetect) {
4375 if (scop_then && !scop_else) {
4376 partial = true;
4377 isl_pw_aff_free(cond);
4378 return scop_then;
4380 if (!scop_then && scop_else) {
4381 partial = true;
4382 isl_pw_aff_free(cond);
4383 return scop_else;
4388 if (cond &&
4389 (!is_nested_allowed(cond, scop_then) ||
4390 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4391 isl_pw_aff_free(cond);
4392 cond = NULL;
4394 if (allow_nested && !cond)
4395 return extract_non_affine_if(stmt->getCond(), scop_then,
4396 scop_else, stmt->getElse(), stmt_id);
4398 if (!cond)
4399 cond = extract_condition(stmt->getCond());
4401 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4402 skip.extract(this, cond);
4404 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4405 set = isl_pw_aff_non_zero_set(cond);
4406 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4408 if (stmt->getElse()) {
4409 set = isl_set_subtract(isl_set_copy(valid), set);
4410 scop_else = pet_scop_restrict(scop_else, set);
4411 scop = pet_scop_add_par(ctx, scop, scop_else);
4412 } else
4413 isl_set_free(set);
4414 scop = resolve_nested(scop);
4415 scop = pet_scop_restrict_context(scop, valid);
4417 if (skip)
4418 scop = pet_scop_prefix(scop, 0);
4419 scop = skip.add(scop, 1);
4421 return scop;
4424 /* Try and construct a pet_scop for a label statement.
4425 * We currently only allow labels on expression statements.
4427 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4429 isl_id *label;
4430 Stmt *sub;
4432 sub = stmt->getSubStmt();
4433 if (!isa<Expr>(sub)) {
4434 unsupported(stmt);
4435 return NULL;
4438 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4440 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4443 /* Construct a pet_scop for a continue statement.
4445 * We simply create an empty scop with a universal pet_skip_now
4446 * skip condition. This skip condition will then be taken into
4447 * account by the enclosing loop construct, possibly after
4448 * being incorporated into outer skip conditions.
4450 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4452 pet_scop *scop;
4453 isl_space *space;
4454 isl_set *set;
4456 scop = pet_scop_empty(ctx);
4457 if (!scop)
4458 return NULL;
4460 space = isl_space_set_alloc(ctx, 0, 1);
4461 set = isl_set_universe(space);
4462 set = isl_set_fix_si(set, isl_dim_set, 0, 1);
4463 scop = pet_scop_set_skip(scop, pet_skip_now, set);
4465 return scop;
4468 /* Construct a pet_scop for a break statement.
4470 * We simply create an empty scop with both a universal pet_skip_now
4471 * skip condition and a universal pet_skip_later skip condition.
4472 * These skip conditions will then be taken into
4473 * account by the enclosing loop construct, possibly after
4474 * being incorporated into outer skip conditions.
4476 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4478 pet_scop *scop;
4479 isl_space *space;
4480 isl_set *set;
4482 scop = pet_scop_empty(ctx);
4483 if (!scop)
4484 return NULL;
4486 space = isl_space_set_alloc(ctx, 0, 1);
4487 set = isl_set_universe(space);
4488 set = isl_set_fix_si(set, isl_dim_set, 0, 1);
4489 scop = pet_scop_set_skip(scop, pet_skip_now, isl_set_copy(set));
4490 scop = pet_scop_set_skip(scop, pet_skip_later, set);
4492 return scop;
4495 /* Try and construct a pet_scop corresponding to "stmt".
4497 * If "stmt" is a compound statement, then "skip_declarations"
4498 * indicates whether we should skip initial declarations in the
4499 * compound statement.
4501 * If the constructed pet_scop is not a (possibly) partial representation
4502 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4503 * In particular, if skip_declarations, then we may have skipped declarations
4504 * inside "stmt" and so the pet_scop may not represent the entire "stmt".
4505 * Note that this function may be called with "stmt" referring to the entire
4506 * body of the function, including the outer braces. In such cases,
4507 * skip_declarations will be set and the braces will not be taken into
4508 * account in scop->start and scop->end.
4510 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
4512 struct pet_scop *scop;
4513 unsigned start, end;
4514 SourceLocation loc;
4515 SourceManager &SM = PP.getSourceManager();
4516 const LangOptions &LO = PP.getLangOpts();
4518 if (isa<Expr>(stmt))
4519 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4521 switch (stmt->getStmtClass()) {
4522 case Stmt::WhileStmtClass:
4523 scop = extract(cast<WhileStmt>(stmt));
4524 break;
4525 case Stmt::ForStmtClass:
4526 scop = extract_for(cast<ForStmt>(stmt));
4527 break;
4528 case Stmt::IfStmtClass:
4529 scop = extract(cast<IfStmt>(stmt));
4530 break;
4531 case Stmt::CompoundStmtClass:
4532 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
4533 break;
4534 case Stmt::LabelStmtClass:
4535 scop = extract(cast<LabelStmt>(stmt));
4536 break;
4537 case Stmt::ContinueStmtClass:
4538 scop = extract(cast<ContinueStmt>(stmt));
4539 break;
4540 case Stmt::BreakStmtClass:
4541 scop = extract(cast<BreakStmt>(stmt));
4542 break;
4543 case Stmt::DeclStmtClass:
4544 scop = extract(cast<DeclStmt>(stmt));
4545 break;
4546 default:
4547 unsupported(stmt);
4548 return NULL;
4551 if (partial || skip_declarations)
4552 return scop;
4554 loc = stmt->getLocStart();
4555 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
4556 start = getExpansionOffset(SM, loc);
4557 loc = PP.getLocForEndOfToken(stmt->getLocEnd());
4558 end = getExpansionOffset(SM, loc);
4559 scop = pet_scop_update_start_end(scop, start, end);
4561 return scop;
4564 /* Do we need to construct a skip condition of the given type
4565 * on a sequence of statements?
4567 * There is no need to construct a new skip condition if only
4568 * only of the two statements has a skip condition or if both
4569 * of their skip conditions are affine.
4571 * In principle we also don't need a new continuation variable if
4572 * the continuation of scop2 is affine, but then we would need
4573 * to allow more complicated forms of continuations.
4575 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4576 enum pet_skip type)
4578 if (!scop1 || !pet_scop_has_skip(scop1, type))
4579 return false;
4580 if (!scop2 || !pet_scop_has_skip(scop2, type))
4581 return false;
4582 if (pet_scop_has_affine_skip(scop1, type) &&
4583 pet_scop_has_affine_skip(scop2, type))
4584 return false;
4585 return true;
4588 /* Construct a scop for computing the skip condition of the given type and
4589 * with access relation "skip_access" for a sequence of two scops "scop1"
4590 * and "scop2".
4592 * The computed scop contains a single statement that essentially does
4594 * skip_cond = skip_cond_1 ? 1 : skip_cond_2
4596 * or, in other words, skip_cond1 || skip_cond2.
4597 * In this expression, skip_cond_2 is filtered to reflect that it is
4598 * only evaluated when skip_cond_1 is false.
4600 * The skip condition on scop1 is not removed because it still needs
4601 * to be applied to scop2 when these two scops are combined.
4603 static struct pet_scop *extract_skip_seq(PetScan *ps,
4604 __isl_take isl_map *skip_access,
4605 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4607 isl_map *access;
4608 struct pet_expr *expr1, *expr2, *expr, *expr_skip;
4609 struct pet_stmt *stmt;
4610 struct pet_scop *scop;
4611 isl_ctx *ctx = ps->ctx;
4613 if (!scop1 || !scop2)
4614 goto error;
4616 expr1 = pet_scop_get_skip_expr(scop1, type);
4617 expr2 = pet_scop_get_skip_expr(scop2, type);
4618 pet_scop_reset_skip(scop2, type);
4620 expr2 = pet_expr_filter(expr2, isl_map_copy(expr1->acc.access), 0);
4622 expr = universally_true(ctx);
4623 expr = pet_expr_new_ternary(ctx, expr1, expr, expr2);
4624 expr_skip = pet_expr_from_access(isl_map_copy(skip_access));
4625 if (expr_skip) {
4626 expr_skip->acc.write = 1;
4627 expr_skip->acc.read = 0;
4629 expr = pet_expr_new_binary(ctx, pet_op_assign, expr_skip, expr);
4630 stmt = pet_stmt_from_pet_expr(ctx, -1, NULL, ps->n_stmt++, expr);
4632 scop = pet_scop_from_pet_stmt(ctx, stmt);
4633 scop = scop_add_array(scop, skip_access, ps->ast_context);
4634 isl_map_free(skip_access);
4636 return scop;
4637 error:
4638 isl_map_free(skip_access);
4639 return NULL;
4642 /* Structure that handles the construction of skip conditions
4643 * on sequences of statements.
4645 * scop1 and scop2 represent the two statements that are combined
4647 struct pet_skip_info_seq : public pet_skip_info {
4648 struct pet_scop *scop1, *scop2;
4650 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4651 struct pet_scop *scop2);
4652 void extract(PetScan *scan, enum pet_skip type);
4653 void extract(PetScan *scan);
4654 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4655 int offset);
4656 struct pet_scop *add(struct pet_scop *scop, int offset);
4659 /* Initialize a pet_skip_info_seq structure based on
4660 * on the two statements that are going to be combined.
4662 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4663 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
4665 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
4666 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
4667 skip_equals_skip_later(scop2);
4668 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4669 need_skip_seq(scop1, scop2, pet_skip_later);
4672 /* If we need to construct a skip condition of the given type,
4673 * then do so now.
4675 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
4677 if (!skip[type])
4678 return;
4680 access[type] = create_test_access(ctx, scan->n_test++);
4681 scop[type] = extract_skip_seq(scan, isl_map_copy(access[type]),
4682 scop1, scop2, type);
4685 /* Construct the required skip conditions.
4687 void pet_skip_info_seq::extract(PetScan *scan)
4689 extract(scan, pet_skip_now);
4690 extract(scan, pet_skip_later);
4691 if (equal)
4692 drop_skip_later(scop1, scop2);
4695 /* Add the computed skip condition of the given type to "main" and
4696 * add the scop for computing the condition at the given offset (the statement
4697 * number). Within this offset, the condition is computed at position 1
4698 * to ensure that it is computed after the corresponding statement.
4700 * If equal is set, then we only computed a skip condition for pet_skip_now,
4701 * but we also need to set it as main's pet_skip_later.
4703 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
4704 enum pet_skip type, int offset)
4706 isl_set *skip_set;
4708 if (!skip[type])
4709 return main;
4711 skip_set = isl_map_range(access[type]);
4712 access[type] = NULL;
4713 scop[type] = pet_scop_prefix(scop[type], 1);
4714 scop[type] = pet_scop_prefix(scop[type], offset);
4715 main = pet_scop_add_par(ctx, main, scop[type]);
4716 scop[type] = NULL;
4718 if (equal)
4719 main = pet_scop_set_skip(main, pet_skip_later,
4720 isl_set_copy(skip_set));
4722 main = pet_scop_set_skip(main, type, skip_set);
4724 return main;
4727 /* Add the computed skip conditions to "main" and
4728 * add the scops for computing the conditions at the given offset.
4730 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
4732 scop = add(scop, pet_skip_now, offset);
4733 scop = add(scop, pet_skip_later, offset);
4735 return scop;
4738 /* Extract a clone of the kill statement in "scop".
4739 * "scop" is expected to have been created from a DeclStmt
4740 * and should have the kill as its first statement.
4742 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
4744 struct pet_expr *kill;
4745 struct pet_stmt *stmt;
4746 isl_map *access;
4748 if (!scop)
4749 return NULL;
4750 if (scop->n_stmt < 1)
4751 isl_die(ctx, isl_error_internal,
4752 "expecting at least one statement", return NULL);
4753 stmt = scop->stmts[0];
4754 if (stmt->body->type != pet_expr_unary ||
4755 stmt->body->op != pet_op_kill)
4756 isl_die(ctx, isl_error_internal,
4757 "expecting kill statement", return NULL);
4759 access = isl_map_copy(stmt->body->args[0]->acc.access);
4760 access = isl_map_reset_tuple_id(access, isl_dim_in);
4761 kill = pet_expr_kill_from_access(access);
4762 return pet_stmt_from_pet_expr(ctx, stmt->line, NULL, n_stmt++, kill);
4765 /* Mark all arrays in "scop" as being exposed.
4767 static struct pet_scop *mark_exposed(struct pet_scop *scop)
4769 if (!scop)
4770 return NULL;
4771 for (int i = 0; i < scop->n_array; ++i)
4772 scop->arrays[i]->exposed = 1;
4773 return scop;
4776 /* Try and construct a pet_scop corresponding to (part of)
4777 * a sequence of statements.
4779 * "block" is set if the sequence respresents the children of
4780 * a compound statement.
4781 * "skip_declarations" is set if we should skip initial declarations
4782 * in the sequence of statements.
4784 * If there are any breaks or continues in the individual statements,
4785 * then we may have to compute a new skip condition.
4786 * This is handled using a pet_skip_info_seq object.
4787 * On initialization, the object checks if skip conditions need
4788 * to be computed. If so, it does so in "extract" and adds them in "add".
4790 * If "block" is set, then we need to insert kill statements at
4791 * the end of the block for any array that has been declared by
4792 * one of the statements in the sequence. Each of these declarations
4793 * results in the construction of a kill statement at the place
4794 * of the declaration, so we simply collect duplicates of
4795 * those kill statements and append these duplicates to the constructed scop.
4797 * If "block" is not set, then any array declared by one of the statements
4798 * in the sequence is marked as being exposed.
4800 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
4801 bool skip_declarations)
4803 pet_scop *scop;
4804 StmtIterator i;
4805 int j;
4806 bool partial_range = false;
4807 set<struct pet_stmt *> kills;
4808 set<struct pet_stmt *>::iterator it;
4810 scop = pet_scop_empty(ctx);
4811 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4812 Stmt *child = *i;
4813 struct pet_scop *scop_i;
4815 if (skip_declarations &&
4816 child->getStmtClass() == Stmt::DeclStmtClass)
4817 continue;
4819 scop_i = extract(child);
4820 if (scop && partial) {
4821 pet_scop_free(scop_i);
4822 break;
4824 pet_skip_info_seq skip(ctx, scop, scop_i);
4825 skip.extract(this);
4826 if (skip)
4827 scop_i = pet_scop_prefix(scop_i, 0);
4828 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4829 if (block)
4830 kills.insert(extract_kill(scop_i));
4831 else
4832 scop_i = mark_exposed(scop_i);
4834 scop_i = pet_scop_prefix(scop_i, j);
4835 if (options->autodetect) {
4836 if (scop_i)
4837 scop = pet_scop_add_seq(ctx, scop, scop_i);
4838 else
4839 partial_range = true;
4840 if (scop->n_stmt != 0 && !scop_i)
4841 partial = true;
4842 } else {
4843 scop = pet_scop_add_seq(ctx, scop, scop_i);
4846 scop = skip.add(scop, j);
4848 if (partial)
4849 break;
4852 for (it = kills.begin(); it != kills.end(); ++it) {
4853 pet_scop *scop_j;
4854 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4855 scop_j = pet_scop_prefix(scop_j, j);
4856 scop = pet_scop_add_seq(ctx, scop, scop_j);
4859 if (scop && partial_range) {
4860 if (scop->n_stmt == 0) {
4861 pet_scop_free(scop);
4862 return NULL;
4864 partial = true;
4867 return scop;
4870 /* Check if the scop marked by the user is exactly this Stmt
4871 * or part of this Stmt.
4872 * If so, return a pet_scop corresponding to the marked region.
4873 * Otherwise, return NULL.
4875 struct pet_scop *PetScan::scan(Stmt *stmt)
4877 SourceManager &SM = PP.getSourceManager();
4878 unsigned start_off, end_off;
4880 start_off = getExpansionOffset(SM, stmt->getLocStart());
4881 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4883 if (start_off > loc.end)
4884 return NULL;
4885 if (end_off < loc.start)
4886 return NULL;
4887 if (start_off >= loc.start && end_off <= loc.end) {
4888 return extract(stmt);
4891 StmtIterator start;
4892 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4893 Stmt *child = *start;
4894 if (!child)
4895 continue;
4896 start_off = getExpansionOffset(SM, child->getLocStart());
4897 end_off = getExpansionOffset(SM, child->getLocEnd());
4898 if (start_off < loc.start && end_off >= loc.end)
4899 return scan(child);
4900 if (start_off >= loc.start)
4901 break;
4904 StmtIterator end;
4905 for (end = start; end != stmt->child_end(); ++end) {
4906 Stmt *child = *end;
4907 start_off = SM.getFileOffset(child->getLocStart());
4908 if (start_off >= loc.end)
4909 break;
4912 return extract(StmtRange(start, end), false, false);
4915 /* Set the size of index "pos" of "array" to "size".
4916 * In particular, add a constraint of the form
4918 * i_pos < size
4920 * to array->extent and a constraint of the form
4922 * size >= 0
4924 * to array->context.
4926 static struct pet_array *update_size(struct pet_array *array, int pos,
4927 __isl_take isl_pw_aff *size)
4929 isl_set *valid;
4930 isl_set *univ;
4931 isl_set *bound;
4932 isl_space *dim;
4933 isl_aff *aff;
4934 isl_pw_aff *index;
4935 isl_id *id;
4937 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
4938 array->context = isl_set_intersect(array->context, valid);
4940 dim = isl_set_get_space(array->extent);
4941 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
4942 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
4943 univ = isl_set_universe(isl_aff_get_domain_space(aff));
4944 index = isl_pw_aff_alloc(univ, aff);
4946 size = isl_pw_aff_add_dims(size, isl_dim_in,
4947 isl_set_dim(array->extent, isl_dim_set));
4948 id = isl_set_get_tuple_id(array->extent);
4949 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
4950 bound = isl_pw_aff_lt_set(index, size);
4952 array->extent = isl_set_intersect(array->extent, bound);
4954 if (!array->context || !array->extent)
4955 goto error;
4957 return array;
4958 error:
4959 pet_array_free(array);
4960 return NULL;
4963 /* Figure out the size of the array at position "pos" and all
4964 * subsequent positions from "type" and update "array" accordingly.
4966 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
4967 const Type *type, int pos)
4969 const ArrayType *atype;
4970 isl_pw_aff *size;
4972 if (!array)
4973 return NULL;
4975 if (type->isPointerType()) {
4976 type = type->getPointeeType().getTypePtr();
4977 return set_upper_bounds(array, type, pos + 1);
4979 if (!type->isArrayType())
4980 return array;
4982 type = type->getCanonicalTypeInternal().getTypePtr();
4983 atype = cast<ArrayType>(type);
4985 if (type->isConstantArrayType()) {
4986 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
4987 size = extract_affine(ca->getSize());
4988 array = update_size(array, pos, size);
4989 } else if (type->isVariableArrayType()) {
4990 const VariableArrayType *vla = cast<VariableArrayType>(atype);
4991 size = extract_affine(vla->getSizeExpr());
4992 array = update_size(array, pos, size);
4995 type = atype->getElementType().getTypePtr();
4997 return set_upper_bounds(array, type, pos + 1);
5000 /* Is "T" the type of a variable length array with static size?
5002 static bool is_vla_with_static_size(QualType T)
5004 const VariableArrayType *vlatype;
5006 if (!T->isVariableArrayType())
5007 return false;
5008 vlatype = cast<VariableArrayType>(T);
5009 return vlatype->getSizeModifier() == VariableArrayType::Static;
5012 /* Return the type of "decl" as an array.
5014 * In particular, if "decl" is a parameter declaration that
5015 * is a variable length array with a static size, then
5016 * return the original type (i.e., the variable length array).
5017 * Otherwise, return the type of decl.
5019 static QualType get_array_type(ValueDecl *decl)
5021 ParmVarDecl *parm;
5022 QualType T;
5024 parm = dyn_cast<ParmVarDecl>(decl);
5025 if (!parm)
5026 return decl->getType();
5028 T = parm->getOriginalType();
5029 if (!is_vla_with_static_size(T))
5030 return decl->getType();
5031 return T;
5034 /* Construct and return a pet_array corresponding to the variable "decl".
5035 * In particular, initialize array->extent to
5037 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
5039 * and then call set_upper_bounds to set the upper bounds on the indices
5040 * based on the type of the variable.
5042 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
5044 struct pet_array *array;
5045 QualType qt = get_array_type(decl);
5046 const Type *type = qt.getTypePtr();
5047 int depth = array_depth(type);
5048 QualType base = base_type(qt);
5049 string name;
5050 isl_id *id;
5051 isl_space *dim;
5053 array = isl_calloc_type(ctx, struct pet_array);
5054 if (!array)
5055 return NULL;
5057 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
5058 dim = isl_space_set_alloc(ctx, 0, depth);
5059 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
5061 array->extent = isl_set_nat_universe(dim);
5063 dim = isl_space_params_alloc(ctx, 0);
5064 array->context = isl_set_universe(dim);
5066 array = set_upper_bounds(array, type, 0);
5067 if (!array)
5068 return NULL;
5070 name = base.getAsString();
5071 array->element_type = strdup(name.c_str());
5072 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
5074 return array;
5077 /* Construct a list of pet_arrays, one for each array (or scalar)
5078 * accessed inside "scop", add this list to "scop" and return the result.
5080 * The context of "scop" is updated with the intersection of
5081 * the contexts of all arrays, i.e., constraints on the parameters
5082 * that ensure that the arrays have a valid (non-negative) size.
5084 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
5086 int i;
5087 set<ValueDecl *> arrays;
5088 set<ValueDecl *>::iterator it;
5089 int n_array;
5090 struct pet_array **scop_arrays;
5092 if (!scop)
5093 return NULL;
5095 pet_scop_collect_arrays(scop, arrays);
5096 if (arrays.size() == 0)
5097 return scop;
5099 n_array = scop->n_array;
5101 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
5102 n_array + arrays.size());
5103 if (!scop_arrays)
5104 goto error;
5105 scop->arrays = scop_arrays;
5107 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
5108 struct pet_array *array;
5109 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
5110 if (!scop->arrays[n_array + i])
5111 goto error;
5112 scop->n_array++;
5113 scop->context = isl_set_intersect(scop->context,
5114 isl_set_copy(array->context));
5115 if (!scop->context)
5116 goto error;
5119 return scop;
5120 error:
5121 pet_scop_free(scop);
5122 return NULL;
5125 /* Bound all parameters in scop->context to the possible values
5126 * of the corresponding C variable.
5128 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
5130 int n;
5132 if (!scop)
5133 return NULL;
5135 n = isl_set_dim(scop->context, isl_dim_param);
5136 for (int i = 0; i < n; ++i) {
5137 isl_id *id;
5138 ValueDecl *decl;
5140 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
5141 if (is_nested_parameter(id)) {
5142 isl_id_free(id);
5143 isl_die(isl_set_get_ctx(scop->context),
5144 isl_error_internal,
5145 "unresolved nested parameter", goto error);
5147 decl = (ValueDecl *) isl_id_get_user(id);
5148 isl_id_free(id);
5150 scop->context = set_parameter_bounds(scop->context, i, decl);
5152 if (!scop->context)
5153 goto error;
5156 return scop;
5157 error:
5158 pet_scop_free(scop);
5159 return NULL;
5162 /* Construct a pet_scop from the given function.
5164 * If the scop was delimited by scop and endscop pragmas, then we override
5165 * the file offsets by those derived from the pragmas.
5167 struct pet_scop *PetScan::scan(FunctionDecl *fd)
5169 pet_scop *scop;
5170 Stmt *stmt;
5172 stmt = fd->getBody();
5174 if (options->autodetect)
5175 scop = extract(stmt, true);
5176 else {
5177 scop = scan(stmt);
5178 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
5180 scop = pet_scop_detect_parameter_accesses(scop);
5181 scop = scan_arrays(scop);
5182 scop = add_parameter_bounds(scop);
5183 scop = pet_scop_gist(scop, value_bounds);
5185 return scop;