extract shared PetScan::extract_access_expr(isl_multi_pw_aff *)
[pet.git] / scan.cc
blob837b2c7b6bc7f5eb7a6a5374e4c6085d1be16b5c
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2014 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 "aff.h"
51 #include "clang.h"
52 #include "expr.h"
53 #include "nest.h"
54 #include "options.h"
55 #include "scan.h"
56 #include "scop.h"
57 #include "scop_plus.h"
59 #include "config.h"
61 using namespace std;
62 using namespace clang;
64 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
66 switch (kind) {
67 case UO_Minus:
68 return pet_op_minus;
69 case UO_Not:
70 return pet_op_not;
71 case UO_LNot:
72 return pet_op_lnot;
73 case UO_PostInc:
74 return pet_op_post_inc;
75 case UO_PostDec:
76 return pet_op_post_dec;
77 case UO_PreInc:
78 return pet_op_pre_inc;
79 case UO_PreDec:
80 return pet_op_pre_dec;
81 default:
82 return pet_op_last;
86 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
88 switch (kind) {
89 case BO_AddAssign:
90 return pet_op_add_assign;
91 case BO_SubAssign:
92 return pet_op_sub_assign;
93 case BO_MulAssign:
94 return pet_op_mul_assign;
95 case BO_DivAssign:
96 return pet_op_div_assign;
97 case BO_Assign:
98 return pet_op_assign;
99 case BO_Add:
100 return pet_op_add;
101 case BO_Sub:
102 return pet_op_sub;
103 case BO_Mul:
104 return pet_op_mul;
105 case BO_Div:
106 return pet_op_div;
107 case BO_Rem:
108 return pet_op_mod;
109 case BO_Shl:
110 return pet_op_shl;
111 case BO_Shr:
112 return pet_op_shr;
113 case BO_EQ:
114 return pet_op_eq;
115 case BO_NE:
116 return pet_op_ne;
117 case BO_LE:
118 return pet_op_le;
119 case BO_GE:
120 return pet_op_ge;
121 case BO_LT:
122 return pet_op_lt;
123 case BO_GT:
124 return pet_op_gt;
125 case BO_And:
126 return pet_op_and;
127 case BO_Xor:
128 return pet_op_xor;
129 case BO_Or:
130 return pet_op_or;
131 case BO_LAnd:
132 return pet_op_land;
133 case BO_LOr:
134 return pet_op_lor;
135 default:
136 return pet_op_last;
140 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
141 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
143 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
144 SourceLocation(), var, false, var->getInnerLocStart(),
145 var->getType(), VK_LValue);
147 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
148 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
150 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
151 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
152 VK_LValue);
154 #else
155 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
157 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
158 var, var->getInnerLocStart(), var->getType(), VK_LValue);
160 #endif
162 /* Check if the element type corresponding to the given array type
163 * has a const qualifier.
165 static bool const_base(QualType qt)
167 const Type *type = qt.getTypePtr();
169 if (type->isPointerType())
170 return const_base(type->getPointeeType());
171 if (type->isArrayType()) {
172 const ArrayType *atype;
173 type = type->getCanonicalTypeInternal().getTypePtr();
174 atype = cast<ArrayType>(type);
175 return const_base(atype->getElementType());
178 return qt.isConstQualified();
181 /* Mark "decl" as having an unknown value in "assigned_value".
183 * If no (known or unknown) value was assigned to "decl" before,
184 * then it may have been treated as a parameter before and may
185 * therefore appear in a value assigned to another variable.
186 * If so, this assignment needs to be turned into an unknown value too.
188 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
189 ValueDecl *decl)
191 map<ValueDecl *, isl_pw_aff *>::iterator it;
193 it = assigned_value.find(decl);
195 assigned_value[decl] = NULL;
197 if (it != assigned_value.end())
198 return;
200 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
201 isl_pw_aff *pa = it->second;
202 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
204 for (int i = 0; i < nparam; ++i) {
205 isl_id *id;
207 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
208 continue;
209 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
210 if (isl_id_get_user(id) == decl)
211 it->second = NULL;
212 isl_id_free(id);
217 /* Look for any assignments to scalar variables in part of the parse
218 * tree and set assigned_value to NULL for each of them.
219 * Also reset assigned_value if the address of a scalar variable
220 * is being taken. As an exception, if the address is passed to a function
221 * that is declared to receive a const pointer, then assigned_value is
222 * not reset.
224 * This ensures that we won't use any previously stored value
225 * in the current subtree and its parents.
227 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
228 map<ValueDecl *, isl_pw_aff *> &assigned_value;
229 set<UnaryOperator *> skip;
231 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
232 assigned_value(assigned_value) {}
234 /* Check for "address of" operators whose value is passed
235 * to a const pointer argument and add them to "skip", so that
236 * we can skip them in VisitUnaryOperator.
238 bool VisitCallExpr(CallExpr *expr) {
239 FunctionDecl *fd;
240 fd = expr->getDirectCallee();
241 if (!fd)
242 return true;
243 for (int i = 0; i < expr->getNumArgs(); ++i) {
244 Expr *arg = expr->getArg(i);
245 UnaryOperator *op;
246 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
247 ImplicitCastExpr *ice;
248 ice = cast<ImplicitCastExpr>(arg);
249 arg = ice->getSubExpr();
251 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
252 continue;
253 op = cast<UnaryOperator>(arg);
254 if (op->getOpcode() != UO_AddrOf)
255 continue;
256 if (const_base(fd->getParamDecl(i)->getType()))
257 skip.insert(op);
259 return true;
262 bool VisitUnaryOperator(UnaryOperator *expr) {
263 Expr *arg;
264 DeclRefExpr *ref;
265 ValueDecl *decl;
267 switch (expr->getOpcode()) {
268 case UO_AddrOf:
269 case UO_PostInc:
270 case UO_PostDec:
271 case UO_PreInc:
272 case UO_PreDec:
273 break;
274 default:
275 return true;
277 if (skip.find(expr) != skip.end())
278 return true;
280 arg = expr->getSubExpr();
281 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
282 return true;
283 ref = cast<DeclRefExpr>(arg);
284 decl = ref->getDecl();
285 clear_assignment(assigned_value, decl);
286 return true;
289 bool VisitBinaryOperator(BinaryOperator *expr) {
290 Expr *lhs;
291 DeclRefExpr *ref;
292 ValueDecl *decl;
294 if (!expr->isAssignmentOp())
295 return true;
296 lhs = expr->getLHS();
297 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
298 return true;
299 ref = cast<DeclRefExpr>(lhs);
300 decl = ref->getDecl();
301 clear_assignment(assigned_value, decl);
302 return true;
306 /* Keep a copy of the currently assigned values.
308 * Any variable that is assigned a value inside the current scope
309 * is removed again when we leave the scope (either because it wasn't
310 * stored in the cache or because it has a different value in the cache).
312 struct assigned_value_cache {
313 map<ValueDecl *, isl_pw_aff *> &assigned_value;
314 map<ValueDecl *, isl_pw_aff *> cache;
316 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
317 assigned_value(assigned_value), cache(assigned_value) {}
318 ~assigned_value_cache() {
319 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
320 for (it = assigned_value.begin(); it != assigned_value.end();
321 ++it) {
322 if (!it->second ||
323 (cache.find(it->first) != cache.end() &&
324 cache[it->first] != it->second))
325 cache[it->first] = NULL;
327 assigned_value = cache;
331 /* Insert an expression into the collection of expressions,
332 * provided it is not already in there.
333 * The isl_pw_affs are freed in the destructor.
335 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
337 std::set<isl_pw_aff *>::iterator it;
339 if (expressions.find(expr) == expressions.end())
340 expressions.insert(expr);
341 else
342 isl_pw_aff_free(expr);
345 PetScan::~PetScan()
347 std::set<isl_pw_aff *>::iterator it;
349 for (it = expressions.begin(); it != expressions.end(); ++it)
350 isl_pw_aff_free(*it);
352 isl_union_map_free(value_bounds);
355 /* Report a diagnostic, unless autodetect is set.
357 void PetScan::report(Stmt *stmt, unsigned id)
359 if (options->autodetect)
360 return;
362 SourceLocation loc = stmt->getLocStart();
363 DiagnosticsEngine &diag = PP.getDiagnostics();
364 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
367 /* Called if we found something we (currently) cannot handle.
368 * We'll provide more informative warnings later.
370 * We only actually complain if autodetect is false.
372 void PetScan::unsupported(Stmt *stmt)
374 DiagnosticsEngine &diag = PP.getDiagnostics();
375 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
376 "unsupported");
377 report(stmt, id);
380 /* Report a missing prototype, unless autodetect is set.
382 void PetScan::report_prototype_required(Stmt *stmt)
384 DiagnosticsEngine &diag = PP.getDiagnostics();
385 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
386 "prototype required");
387 report(stmt, id);
390 /* Report a missing increment, unless autodetect is set.
392 void PetScan::report_missing_increment(Stmt *stmt)
394 DiagnosticsEngine &diag = PP.getDiagnostics();
395 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
396 "missing increment");
397 report(stmt, id);
400 /* Extract an integer from "expr".
402 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
404 const Type *type = expr->getType().getTypePtr();
405 int is_signed = type->hasSignedIntegerRepresentation();
406 llvm::APInt val = expr->getValue();
407 int is_negative = is_signed && val.isNegative();
408 isl_val *v;
410 if (is_negative)
411 val = -val;
413 v = extract_unsigned(ctx, val);
415 if (is_negative)
416 v = isl_val_neg(v);
417 return v;
420 /* Extract an integer from "val", which is assumed to be non-negative.
422 __isl_give isl_val *PetScan::extract_unsigned(isl_ctx *ctx,
423 const llvm::APInt &val)
425 unsigned n;
426 const uint64_t *data;
428 data = val.getRawData();
429 n = val.getNumWords();
430 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
433 /* Extract an integer from "expr".
434 * Return NULL if "expr" does not (obviously) represent an integer.
436 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
438 return extract_int(expr->getSubExpr());
441 /* Extract an integer from "expr".
442 * Return NULL if "expr" does not (obviously) represent an integer.
444 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
446 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
447 return extract_int(ctx, cast<IntegerLiteral>(expr));
448 if (expr->getStmtClass() == Stmt::ParenExprClass)
449 return extract_int(cast<ParenExpr>(expr));
451 unsupported(expr);
452 return NULL;
455 /* Extract an affine expression from the IntegerLiteral "expr".
457 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
459 isl_space *dim = isl_space_params_alloc(ctx, 0);
460 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
461 isl_aff *aff = isl_aff_zero_on_domain(ls);
462 isl_set *dom = isl_set_universe(dim);
463 isl_val *v;
465 v = extract_int(expr);
466 aff = isl_aff_add_constant_val(aff, v);
468 return isl_pw_aff_alloc(dom, aff);
471 /* Extract an affine expression from the APInt "val", which is assumed
472 * to be non-negative.
474 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
476 isl_space *dim = isl_space_params_alloc(ctx, 0);
477 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
478 isl_aff *aff = isl_aff_zero_on_domain(ls);
479 isl_set *dom = isl_set_universe(dim);
480 isl_val *v;
482 v = extract_unsigned(ctx, val);
483 aff = isl_aff_add_constant_val(aff, v);
485 return isl_pw_aff_alloc(dom, aff);
488 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
490 return extract_affine(expr->getSubExpr());
493 static unsigned get_type_size(ValueDecl *decl)
495 return decl->getASTContext().getIntWidth(decl->getType());
498 /* Bound parameter "pos" of "set" to the possible values of "decl".
500 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
501 unsigned pos, ValueDecl *decl)
503 unsigned width;
504 isl_ctx *ctx;
505 isl_val *bound;
507 ctx = isl_set_get_ctx(set);
508 width = get_type_size(decl);
509 if (decl->getType()->isUnsignedIntegerType()) {
510 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
511 bound = isl_val_int_from_ui(ctx, width);
512 bound = isl_val_2exp(bound);
513 bound = isl_val_sub_ui(bound, 1);
514 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
515 } else {
516 bound = isl_val_int_from_ui(ctx, width - 1);
517 bound = isl_val_2exp(bound);
518 bound = isl_val_sub_ui(bound, 1);
519 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
520 isl_val_copy(bound));
521 bound = isl_val_neg(bound);
522 bound = isl_val_sub_ui(bound, 1);
523 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
526 return set;
529 /* Extract an affine expression from the DeclRefExpr "expr".
531 * If the variable has been assigned a value, then we check whether
532 * we know what (affine) value was assigned.
533 * If so, we return this value. Otherwise we convert "expr"
534 * to an extra parameter (provided nesting_enabled is set).
536 * Otherwise, we simply return an expression that is equal
537 * to a parameter corresponding to the referenced variable.
539 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
541 ValueDecl *decl = expr->getDecl();
542 const Type *type = decl->getType().getTypePtr();
543 isl_id *id;
544 isl_space *dim;
545 isl_aff *aff;
546 isl_set *dom;
548 if (!type->isIntegerType()) {
549 unsupported(expr);
550 return NULL;
553 if (assigned_value.find(decl) != assigned_value.end()) {
554 if (assigned_value[decl])
555 return isl_pw_aff_copy(assigned_value[decl]);
556 else
557 return nested_access(expr);
560 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
561 dim = isl_space_params_alloc(ctx, 1);
563 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
565 dom = isl_set_universe(isl_space_copy(dim));
566 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
567 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
569 return isl_pw_aff_alloc(dom, aff);
572 /* Extract an affine expression from an integer division operation.
573 * In particular, if "expr" is lhs/rhs, then return
575 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
577 * The second argument (rhs) is required to be a (positive) integer constant.
579 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
581 int is_cst;
582 isl_pw_aff *rhs, *lhs;
584 rhs = extract_affine(expr->getRHS());
585 is_cst = isl_pw_aff_is_cst(rhs);
586 if (is_cst < 0 || !is_cst) {
587 isl_pw_aff_free(rhs);
588 if (!is_cst)
589 unsupported(expr);
590 return NULL;
593 lhs = extract_affine(expr->getLHS());
595 return isl_pw_aff_tdiv_q(lhs, rhs);
598 /* Extract an affine expression from a modulo operation.
599 * In particular, if "expr" is lhs/rhs, then return
601 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
603 * The second argument (rhs) is required to be a (positive) integer constant.
605 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
607 int is_cst;
608 isl_pw_aff *rhs, *lhs;
610 rhs = extract_affine(expr->getRHS());
611 is_cst = isl_pw_aff_is_cst(rhs);
612 if (is_cst < 0 || !is_cst) {
613 isl_pw_aff_free(rhs);
614 if (!is_cst)
615 unsupported(expr);
616 return NULL;
619 lhs = extract_affine(expr->getLHS());
621 return isl_pw_aff_tdiv_r(lhs, rhs);
624 /* Extract an affine expression from a multiplication operation.
625 * This is only allowed if at least one of the two arguments
626 * is a (piecewise) constant.
628 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
630 isl_pw_aff *lhs;
631 isl_pw_aff *rhs;
633 lhs = extract_affine(expr->getLHS());
634 rhs = extract_affine(expr->getRHS());
636 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
637 isl_pw_aff_free(lhs);
638 isl_pw_aff_free(rhs);
639 unsupported(expr);
640 return NULL;
643 return isl_pw_aff_mul(lhs, rhs);
646 /* Extract an affine expression from an addition or subtraction operation.
648 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
650 isl_pw_aff *lhs;
651 isl_pw_aff *rhs;
653 lhs = extract_affine(expr->getLHS());
654 rhs = extract_affine(expr->getRHS());
656 switch (expr->getOpcode()) {
657 case BO_Add:
658 return isl_pw_aff_add(lhs, rhs);
659 case BO_Sub:
660 return isl_pw_aff_sub(lhs, rhs);
661 default:
662 isl_pw_aff_free(lhs);
663 isl_pw_aff_free(rhs);
664 return NULL;
669 /* Compute
671 * pwaff mod 2^width
673 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
674 unsigned width)
676 isl_ctx *ctx;
677 isl_val *mod;
679 ctx = isl_pw_aff_get_ctx(pwaff);
680 mod = isl_val_int_from_ui(ctx, width);
681 mod = isl_val_2exp(mod);
683 pwaff = isl_pw_aff_mod_val(pwaff, mod);
685 return pwaff;
688 /* Limit the domain of "pwaff" to those elements where the function
689 * value satisfies
691 * 2^{width-1} <= pwaff < 2^{width-1}
693 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
694 unsigned width)
696 isl_ctx *ctx;
697 isl_val *v;
698 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
699 isl_local_space *ls = isl_local_space_from_space(space);
700 isl_aff *bound;
701 isl_set *dom;
702 isl_pw_aff *b;
704 ctx = isl_pw_aff_get_ctx(pwaff);
705 v = isl_val_int_from_ui(ctx, width - 1);
706 v = isl_val_2exp(v);
708 bound = isl_aff_zero_on_domain(ls);
709 bound = isl_aff_add_constant_val(bound, v);
710 b = isl_pw_aff_from_aff(bound);
712 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
713 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
715 b = isl_pw_aff_neg(b);
716 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
717 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
719 return pwaff;
722 /* Handle potential overflows on signed computations.
724 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
725 * the we adjust the domain of "pa" to avoid overflows.
727 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
728 unsigned width)
730 if (options->signed_overflow == PET_OVERFLOW_AVOID)
731 pa = avoid_overflow(pa, width);
733 return pa;
736 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
738 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
739 __isl_take isl_set *dom)
741 isl_pw_aff *pa;
742 pa = isl_set_indicator_function(set);
743 pa = isl_pw_aff_intersect_domain(pa, isl_set_coalesce(dom));
744 return pa;
747 /* Extract an affine expression from some binary operations.
748 * If the result of the expression is unsigned, then we wrap it
749 * based on the size of the type. Otherwise, we ensure that
750 * no overflow occurs.
752 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
754 isl_pw_aff *res;
755 unsigned width;
757 switch (expr->getOpcode()) {
758 case BO_Add:
759 case BO_Sub:
760 res = extract_affine_add(expr);
761 break;
762 case BO_Div:
763 res = extract_affine_div(expr);
764 break;
765 case BO_Rem:
766 res = extract_affine_mod(expr);
767 break;
768 case BO_Mul:
769 res = extract_affine_mul(expr);
770 break;
771 case BO_LT:
772 case BO_LE:
773 case BO_GT:
774 case BO_GE:
775 case BO_EQ:
776 case BO_NE:
777 case BO_LAnd:
778 case BO_LOr:
779 return extract_condition(expr);
780 default:
781 unsupported(expr);
782 return NULL;
785 width = ast_context.getIntWidth(expr->getType());
786 if (expr->getType()->isUnsignedIntegerType())
787 res = wrap(res, width);
788 else
789 res = signed_overflow(res, width);
791 return res;
794 /* Extract an affine expression from a negation operation.
796 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
798 if (expr->getOpcode() == UO_Minus)
799 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
800 if (expr->getOpcode() == UO_LNot)
801 return extract_condition(expr);
803 unsupported(expr);
804 return NULL;
807 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
809 return extract_affine(expr->getSubExpr());
812 /* Extract an affine expression from some special function calls.
813 * In particular, we handle "min", "max", "ceild", "floord",
814 * "intMod", "intFloor" and "intCeil".
815 * In case of the latter five, the second argument needs to be
816 * a (positive) integer constant.
818 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
820 FunctionDecl *fd;
821 string name;
822 isl_pw_aff *aff1, *aff2;
824 fd = expr->getDirectCallee();
825 if (!fd) {
826 unsupported(expr);
827 return NULL;
830 name = fd->getDeclName().getAsString();
831 if (!(expr->getNumArgs() == 2 && name == "min") &&
832 !(expr->getNumArgs() == 2 && name == "max") &&
833 !(expr->getNumArgs() == 2 && name == "intMod") &&
834 !(expr->getNumArgs() == 2 && name == "intFloor") &&
835 !(expr->getNumArgs() == 2 && name == "intCeil") &&
836 !(expr->getNumArgs() == 2 && name == "floord") &&
837 !(expr->getNumArgs() == 2 && name == "ceild")) {
838 unsupported(expr);
839 return NULL;
842 if (name == "min" || name == "max") {
843 aff1 = extract_affine(expr->getArg(0));
844 aff2 = extract_affine(expr->getArg(1));
846 if (name == "min")
847 aff1 = isl_pw_aff_min(aff1, aff2);
848 else
849 aff1 = isl_pw_aff_max(aff1, aff2);
850 } else if (name == "intMod") {
851 isl_val *v;
852 Expr *arg2 = expr->getArg(1);
854 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
855 unsupported(expr);
856 return NULL;
858 aff1 = extract_affine(expr->getArg(0));
859 v = extract_int(cast<IntegerLiteral>(arg2));
860 aff1 = isl_pw_aff_mod_val(aff1, v);
861 } else if (name == "floord" || name == "ceild" ||
862 name == "intFloor" || name == "intCeil") {
863 isl_val *v;
864 Expr *arg2 = expr->getArg(1);
866 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
867 unsupported(expr);
868 return NULL;
870 aff1 = extract_affine(expr->getArg(0));
871 v = extract_int(cast<IntegerLiteral>(arg2));
872 aff1 = isl_pw_aff_scale_down_val(aff1, v);
873 if (name == "floord" || name == "intFloor")
874 aff1 = isl_pw_aff_floor(aff1);
875 else
876 aff1 = isl_pw_aff_ceil(aff1);
877 } else {
878 unsupported(expr);
879 return NULL;
882 return aff1;
885 /* This method is called when we come across an access that is
886 * nested in what is supposed to be an affine expression.
887 * If nesting is allowed, we return a new parameter that corresponds
888 * to this nested access. Otherwise, we simply complain.
890 * Note that we currently don't allow nested accesses themselves
891 * to contain any nested accesses, so we check if we can extract
892 * the access without any nesting and complain if we can't.
894 * The new parameter is resolved in resolve_nested.
896 isl_pw_aff *PetScan::nested_access(Expr *expr)
898 isl_id *id;
899 isl_space *dim;
900 isl_aff *aff;
901 isl_set *dom;
902 isl_multi_pw_aff *index;
904 if (!nesting_enabled) {
905 unsupported(expr);
906 return NULL;
909 allow_nested = false;
910 index = extract_index(expr);
911 allow_nested = true;
912 if (!index) {
913 unsupported(expr);
914 return NULL;
916 isl_multi_pw_aff_free(index);
918 id = pet_nested_clang_expr(ctx, expr);
919 dim = isl_space_params_alloc(ctx, 1);
921 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
923 dom = isl_set_universe(isl_space_copy(dim));
924 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
925 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
927 return isl_pw_aff_alloc(dom, aff);
930 /* Affine expressions are not supposed to contain array accesses,
931 * but if nesting is allowed, we return a parameter corresponding
932 * to the array access.
934 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
936 return nested_access(expr);
939 /* Affine expressions are not supposed to contain member accesses,
940 * but if nesting is allowed, we return a parameter corresponding
941 * to the member access.
943 __isl_give isl_pw_aff *PetScan::extract_affine(MemberExpr *expr)
945 return nested_access(expr);
948 /* Extract an affine expression from a conditional operation.
950 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
952 isl_pw_aff *cond, *lhs, *rhs;
954 cond = extract_condition(expr->getCond());
955 lhs = extract_affine(expr->getTrueExpr());
956 rhs = extract_affine(expr->getFalseExpr());
958 return isl_pw_aff_cond(cond, lhs, rhs);
961 /* Extract an affine expression, if possible, from "expr".
962 * Otherwise return NULL.
964 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
966 switch (expr->getStmtClass()) {
967 case Stmt::ImplicitCastExprClass:
968 return extract_affine(cast<ImplicitCastExpr>(expr));
969 case Stmt::IntegerLiteralClass:
970 return extract_affine(cast<IntegerLiteral>(expr));
971 case Stmt::DeclRefExprClass:
972 return extract_affine(cast<DeclRefExpr>(expr));
973 case Stmt::BinaryOperatorClass:
974 return extract_affine(cast<BinaryOperator>(expr));
975 case Stmt::UnaryOperatorClass:
976 return extract_affine(cast<UnaryOperator>(expr));
977 case Stmt::ParenExprClass:
978 return extract_affine(cast<ParenExpr>(expr));
979 case Stmt::CallExprClass:
980 return extract_affine(cast<CallExpr>(expr));
981 case Stmt::ArraySubscriptExprClass:
982 return extract_affine(cast<ArraySubscriptExpr>(expr));
983 case Stmt::MemberExprClass:
984 return extract_affine(cast<MemberExpr>(expr));
985 case Stmt::ConditionalOperatorClass:
986 return extract_affine(cast<ConditionalOperator>(expr));
987 default:
988 unsupported(expr);
990 return NULL;
993 __isl_give isl_multi_pw_aff *PetScan::extract_index(ImplicitCastExpr *expr)
995 return extract_index(expr->getSubExpr());
998 /* Return the depth of an array of the given type.
1000 static int array_depth(const Type *type)
1002 if (type->isPointerType())
1003 return 1 + array_depth(type->getPointeeType().getTypePtr());
1004 if (type->isArrayType()) {
1005 const ArrayType *atype;
1006 type = type->getCanonicalTypeInternal().getTypePtr();
1007 atype = cast<ArrayType>(type);
1008 return 1 + array_depth(atype->getElementType().getTypePtr());
1010 return 0;
1013 /* Return the depth of the array accessed by the index expression "index".
1014 * If "index" is an affine expression, i.e., if it does not access
1015 * any array, then return 1.
1016 * If "index" represent a member access, i.e., if its range is a wrapped
1017 * relation, then return the sum of the depth of the array of structures
1018 * and that of the member inside the structure.
1020 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
1022 isl_id *id;
1023 ValueDecl *decl;
1025 if (!index)
1026 return -1;
1028 if (isl_multi_pw_aff_range_is_wrapping(index)) {
1029 int domain_depth, range_depth;
1030 isl_multi_pw_aff *domain, *range;
1032 domain = isl_multi_pw_aff_copy(index);
1033 domain = isl_multi_pw_aff_range_factor_domain(domain);
1034 domain_depth = extract_depth(domain);
1035 isl_multi_pw_aff_free(domain);
1036 range = isl_multi_pw_aff_copy(index);
1037 range = isl_multi_pw_aff_range_factor_range(range);
1038 range_depth = extract_depth(range);
1039 isl_multi_pw_aff_free(range);
1041 return domain_depth + range_depth;
1044 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
1045 return 1;
1047 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
1048 if (!id)
1049 return -1;
1050 decl = (ValueDecl *) isl_id_get_user(id);
1051 isl_id_free(id);
1053 return array_depth(decl->getType().getTypePtr());
1056 /* Extract an index expression from a reference to a variable.
1057 * If the variable has name "A", then the returned index expression
1058 * is of the form
1060 * { [] -> A[] }
1062 __isl_give isl_multi_pw_aff *PetScan::extract_index(DeclRefExpr *expr)
1064 return extract_index(expr->getDecl());
1067 /* Extract an index expression from a variable.
1068 * If the variable has name "A", then the returned index expression
1069 * is of the form
1071 * { [] -> A[] }
1073 __isl_give isl_multi_pw_aff *PetScan::extract_index(ValueDecl *decl)
1075 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
1076 isl_space *space = isl_space_alloc(ctx, 0, 0, 0);
1078 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1080 return isl_multi_pw_aff_zero(space);
1083 /* Extract an index expression from an integer contant.
1084 * If the value of the constant is "v", then the returned access relation
1085 * is
1087 * { [] -> [v] }
1089 __isl_give isl_multi_pw_aff *PetScan::extract_index(IntegerLiteral *expr)
1091 isl_multi_pw_aff *mpa;
1093 mpa = isl_multi_pw_aff_from_pw_aff(extract_affine(expr));
1094 mpa = isl_multi_pw_aff_from_range(mpa);
1095 return mpa;
1098 /* Try and extract an index expression from the given Expr.
1099 * Return NULL if it doesn't work out.
1101 __isl_give isl_multi_pw_aff *PetScan::extract_index(Expr *expr)
1103 switch (expr->getStmtClass()) {
1104 case Stmt::ImplicitCastExprClass:
1105 return extract_index(cast<ImplicitCastExpr>(expr));
1106 case Stmt::DeclRefExprClass:
1107 return extract_index(cast<DeclRefExpr>(expr));
1108 case Stmt::ArraySubscriptExprClass:
1109 return extract_index(cast<ArraySubscriptExpr>(expr));
1110 case Stmt::IntegerLiteralClass:
1111 return extract_index(cast<IntegerLiteral>(expr));
1112 case Stmt::MemberExprClass:
1113 return extract_index(cast<MemberExpr>(expr));
1114 default:
1115 unsupported(expr);
1117 return NULL;
1120 /* Given a partial index expression "base" and an extra index "index",
1121 * append the extra index to "base" and return the result.
1122 * Additionally, add the constraints that the extra index is non-negative.
1123 * If "index" represent a member access, i.e., if its range is a wrapped
1124 * relation, then we recursively extend the range of this nested relation.
1126 static __isl_give isl_multi_pw_aff *subscript(__isl_take isl_multi_pw_aff *base,
1127 __isl_take isl_pw_aff *index)
1129 isl_id *id;
1130 isl_set *domain;
1131 isl_multi_pw_aff *access;
1132 int member_access;
1134 member_access = isl_multi_pw_aff_range_is_wrapping(base);
1135 if (member_access < 0)
1136 goto error;
1137 if (member_access) {
1138 isl_multi_pw_aff *domain, *range;
1139 isl_id *id;
1141 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_out);
1142 domain = isl_multi_pw_aff_copy(base);
1143 domain = isl_multi_pw_aff_range_factor_domain(domain);
1144 range = isl_multi_pw_aff_range_factor_range(base);
1145 range = subscript(range, index);
1146 access = isl_multi_pw_aff_range_product(domain, range);
1147 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_out, id);
1148 return access;
1151 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_set);
1152 index = isl_pw_aff_from_range(index);
1153 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
1154 index = isl_pw_aff_intersect_domain(index, domain);
1155 access = isl_multi_pw_aff_from_pw_aff(index);
1156 access = isl_multi_pw_aff_flat_range_product(base, access);
1157 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_set, id);
1159 return access;
1160 error:
1161 isl_multi_pw_aff_free(base);
1162 isl_pw_aff_free(index);
1163 return NULL;
1166 /* Extract an index expression from the given array subscript expression.
1167 * If nesting is allowed in general, then we turn it on while
1168 * examining the index expression.
1170 * We first extract an index expression from the base.
1171 * This will result in an index expression with a range that corresponds
1172 * to the earlier indices.
1173 * We then extract the current index, restrict its domain
1174 * to those values that result in a non-negative index and
1175 * append the index to the base index expression.
1177 __isl_give isl_multi_pw_aff *PetScan::extract_index(ArraySubscriptExpr *expr)
1179 Expr *base = expr->getBase();
1180 Expr *idx = expr->getIdx();
1181 isl_pw_aff *index;
1182 isl_multi_pw_aff *base_access;
1183 isl_multi_pw_aff *access;
1184 bool save_nesting = nesting_enabled;
1186 nesting_enabled = allow_nested;
1188 base_access = extract_index(base);
1189 index = extract_affine(idx);
1191 nesting_enabled = save_nesting;
1193 access = subscript(base_access, index);
1195 return access;
1198 /* Construct a name for a member access by concatenating the name
1199 * of the array of structures and the member, separated by an underscore.
1201 * The caller is responsible for freeing the result.
1203 static char *member_access_name(isl_ctx *ctx, const char *base,
1204 const char *field)
1206 int len;
1207 char *name;
1209 len = strlen(base) + 1 + strlen(field);
1210 name = isl_alloc_array(ctx, char, len + 1);
1211 if (!name)
1212 return NULL;
1213 snprintf(name, len + 1, "%s_%s", base, field);
1215 return name;
1218 /* Given an index expression "base" for an element of an array of structures
1219 * and an expression "field" for the field member being accessed, construct
1220 * an index expression for an access to that member of the given structure.
1221 * In particular, take the range product of "base" and "field" and
1222 * attach a name to the result.
1224 static __isl_give isl_multi_pw_aff *member(__isl_take isl_multi_pw_aff *base,
1225 __isl_take isl_multi_pw_aff *field)
1227 isl_ctx *ctx;
1228 isl_multi_pw_aff *access;
1229 const char *base_name, *field_name;
1230 char *name;
1232 ctx = isl_multi_pw_aff_get_ctx(base);
1234 base_name = isl_multi_pw_aff_get_tuple_name(base, isl_dim_out);
1235 field_name = isl_multi_pw_aff_get_tuple_name(field, isl_dim_out);
1236 name = member_access_name(ctx, base_name, field_name);
1238 access = isl_multi_pw_aff_range_product(base, field);
1240 access = isl_multi_pw_aff_set_tuple_name(access, isl_dim_out, name);
1241 free(name);
1243 return access;
1246 /* Extract an index expression from a member expression.
1248 * If the base access (to the structure containing the member)
1249 * is of the form
1251 * [] -> A[..]
1253 * and the member is called "f", then the member access is of
1254 * the form
1256 * [] -> A_f[A[..] -> f[]]
1258 * If the member access is to an anonymous struct, then simply return
1260 * [] -> A[..]
1262 * If the member access in the source code is of the form
1264 * A->f
1266 * then it is treated as
1268 * A[0].f
1270 __isl_give isl_multi_pw_aff *PetScan::extract_index(MemberExpr *expr)
1272 Expr *base = expr->getBase();
1273 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
1274 isl_multi_pw_aff *base_access, *field_access;
1275 isl_id *id;
1276 isl_space *space;
1278 base_access = extract_index(base);
1280 if (expr->isArrow()) {
1281 isl_space *space = isl_space_params_alloc(ctx, 0);
1282 isl_local_space *ls = isl_local_space_from_space(space);
1283 isl_aff *aff = isl_aff_zero_on_domain(ls);
1284 isl_pw_aff *index = isl_pw_aff_from_aff(aff);
1285 base_access = subscript(base_access, index);
1288 if (field->isAnonymousStructOrUnion())
1289 return base_access;
1291 id = isl_id_alloc(ctx, field->getName().str().c_str(), field);
1292 space = isl_multi_pw_aff_get_domain_space(base_access);
1293 space = isl_space_from_domain(space);
1294 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1295 field_access = isl_multi_pw_aff_zero(space);
1297 return member(base_access, field_access);
1300 /* Check if "expr" calls function "minmax" with two arguments and if so
1301 * make lhs and rhs refer to these two arguments.
1303 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1305 CallExpr *call;
1306 FunctionDecl *fd;
1307 string name;
1309 if (expr->getStmtClass() != Stmt::CallExprClass)
1310 return false;
1312 call = cast<CallExpr>(expr);
1313 fd = call->getDirectCallee();
1314 if (!fd)
1315 return false;
1317 if (call->getNumArgs() != 2)
1318 return false;
1320 name = fd->getDeclName().getAsString();
1321 if (name != minmax)
1322 return false;
1324 lhs = call->getArg(0);
1325 rhs = call->getArg(1);
1327 return true;
1330 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1331 * lhs and rhs refer to the two arguments.
1333 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1335 return is_minmax(expr, "min", lhs, rhs);
1338 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1339 * lhs and rhs refer to the two arguments.
1341 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1343 return is_minmax(expr, "max", lhs, rhs);
1346 /* Return "lhs && rhs", defined on the shared definition domain.
1348 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1349 __isl_take isl_pw_aff *rhs)
1351 isl_set *cond;
1352 isl_set *dom;
1354 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1355 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1356 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1357 isl_pw_aff_non_zero_set(rhs));
1358 return indicator_function(cond, dom);
1361 /* Return "lhs && rhs", with shortcut semantics.
1362 * That is, if lhs is false, then the result is defined even if rhs is not.
1363 * In practice, we compute lhs ? rhs : lhs.
1365 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1366 __isl_take isl_pw_aff *rhs)
1368 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1371 /* Return "lhs || rhs", with shortcut semantics.
1372 * That is, if lhs is true, then the result is defined even if rhs is not.
1373 * In practice, we compute lhs ? lhs : rhs.
1375 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1376 __isl_take isl_pw_aff *rhs)
1378 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1381 /* Extract an affine expressions representing the comparison "LHS op RHS"
1382 * "comp" is the original statement that "LHS op RHS" is derived from
1383 * and is used for diagnostics.
1385 * If the comparison is of the form
1387 * a <= min(b,c)
1389 * then the expression is constructed as the conjunction of
1390 * the comparisons
1392 * a <= b and a <= c
1394 * A similar optimization is performed for max(a,b) <= c.
1395 * We do this because that will lead to simpler representations
1396 * of the expression.
1397 * If isl is ever enhanced to explicitly deal with min and max expressions,
1398 * this optimization can be removed.
1400 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1401 Expr *LHS, Expr *RHS, Stmt *comp)
1403 isl_pw_aff *lhs;
1404 isl_pw_aff *rhs;
1405 isl_pw_aff *res;
1406 isl_set *cond;
1407 isl_set *dom;
1408 enum pet_op_type type;
1410 if (op == BO_GT)
1411 return extract_comparison(BO_LT, RHS, LHS, comp);
1412 if (op == BO_GE)
1413 return extract_comparison(BO_LE, RHS, LHS, comp);
1415 if (op == BO_LT || op == BO_LE) {
1416 Expr *expr1, *expr2;
1417 if (is_min(RHS, expr1, expr2)) {
1418 lhs = extract_comparison(op, LHS, expr1, comp);
1419 rhs = extract_comparison(op, LHS, expr2, comp);
1420 return pw_aff_and(lhs, rhs);
1422 if (is_max(LHS, expr1, expr2)) {
1423 lhs = extract_comparison(op, expr1, RHS, comp);
1424 rhs = extract_comparison(op, expr2, RHS, comp);
1425 return pw_aff_and(lhs, rhs);
1429 lhs = extract_affine(LHS);
1430 rhs = extract_affine(RHS);
1432 type = BinaryOperatorKind2pet_op_type(op);
1433 return pet_comparison(type, lhs, rhs);
1436 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1438 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1439 comp->getRHS(), comp);
1442 /* Extract an affine expression representing the negation (logical not)
1443 * of a subexpression.
1445 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1447 isl_set *set_cond, *dom;
1448 isl_pw_aff *cond, *res;
1450 cond = extract_condition(op->getSubExpr());
1452 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1454 set_cond = isl_pw_aff_zero_set(cond);
1456 res = indicator_function(set_cond, dom);
1458 return res;
1461 /* Extract an affine expression representing the disjunction (logical or)
1462 * or conjunction (logical and) of two subexpressions.
1464 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1466 isl_pw_aff *lhs, *rhs;
1468 lhs = extract_condition(comp->getLHS());
1469 rhs = extract_condition(comp->getRHS());
1471 switch (comp->getOpcode()) {
1472 case BO_LAnd:
1473 return pw_aff_and_then(lhs, rhs);
1474 case BO_LOr:
1475 return pw_aff_or_else(lhs, rhs);
1476 default:
1477 isl_pw_aff_free(lhs);
1478 isl_pw_aff_free(rhs);
1481 unsupported(comp);
1482 return NULL;
1485 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1487 switch (expr->getOpcode()) {
1488 case UO_LNot:
1489 return extract_boolean(expr);
1490 default:
1491 unsupported(expr);
1492 return NULL;
1496 /* Extract the affine expression "expr != 0 ? 1 : 0".
1498 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1500 isl_pw_aff *res;
1501 isl_set *set, *dom;
1503 res = extract_affine(expr);
1505 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1506 set = isl_pw_aff_non_zero_set(res);
1508 res = indicator_function(set, dom);
1510 return res;
1513 /* Extract an affine expression from a boolean expression.
1514 * In particular, return the expression "expr ? 1 : 0".
1516 * If the expression doesn't look like a condition, we assume it
1517 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1519 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1521 BinaryOperator *comp;
1523 if (!expr) {
1524 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1525 return indicator_function(u, isl_set_copy(u));
1528 if (expr->getStmtClass() == Stmt::ParenExprClass)
1529 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1531 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1532 return extract_condition(cast<UnaryOperator>(expr));
1534 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1535 return extract_implicit_condition(expr);
1537 comp = cast<BinaryOperator>(expr);
1538 switch (comp->getOpcode()) {
1539 case BO_LT:
1540 case BO_LE:
1541 case BO_GT:
1542 case BO_GE:
1543 case BO_EQ:
1544 case BO_NE:
1545 return extract_comparison(comp);
1546 case BO_LAnd:
1547 case BO_LOr:
1548 return extract_boolean(comp);
1549 default:
1550 return extract_implicit_condition(expr);
1554 /* Construct a pet_expr representing a unary operator expression.
1556 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1558 pet_expr *arg;
1559 enum pet_op_type op;
1561 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1562 if (op == pet_op_last) {
1563 unsupported(expr);
1564 return NULL;
1567 arg = extract_expr(expr->getSubExpr());
1569 if (expr->isIncrementDecrementOp() &&
1570 pet_expr_get_type(arg) == pet_expr_access) {
1571 arg = mark_write(arg);
1572 arg = pet_expr_access_set_read(arg, 1);
1575 return pet_expr_new_unary(op, arg);
1578 /* Mark the given access pet_expr as a write.
1579 * If a scalar is being accessed, then mark its value
1580 * as unknown in assigned_value.
1582 __isl_give pet_expr *PetScan::mark_write(__isl_take pet_expr *access)
1584 isl_id *id;
1585 ValueDecl *decl;
1587 access = pet_expr_access_set_write(access, 1);
1588 access = pet_expr_access_set_read(access, 0);
1590 if (!access || !pet_expr_is_scalar_access(access))
1591 return access;
1593 id = pet_expr_access_get_id(access);
1594 decl = (ValueDecl *) isl_id_get_user(id);
1595 clear_assignment(assigned_value, decl);
1596 isl_id_free(id);
1598 return access;
1601 /* Assign "rhs" to "lhs".
1603 * In particular, if "lhs" is a scalar variable, then mark
1604 * the variable as having been assigned. If, furthermore, "rhs"
1605 * is an affine expression, then keep track of this value in assigned_value
1606 * so that we can plug it in when we later come across the same variable.
1608 void PetScan::assign(__isl_keep pet_expr *lhs, Expr *rhs)
1610 isl_id *id;
1611 ValueDecl *decl;
1612 isl_pw_aff *pa;
1614 if (!lhs)
1615 return;
1616 if (!pet_expr_is_scalar_access(lhs))
1617 return;
1619 id = pet_expr_access_get_id(lhs);
1620 decl = (ValueDecl *) isl_id_get_user(id);
1621 isl_id_free(id);
1623 pa = try_extract_affine(rhs);
1624 clear_assignment(assigned_value, decl);
1625 if (!pa)
1626 return;
1627 assigned_value[decl] = pa;
1628 insert_expression(pa);
1631 /* Construct a pet_expr representing a binary operator expression.
1633 * If the top level operator is an assignment and the LHS is an access,
1634 * then we mark that access as a write. If the operator is a compound
1635 * assignment, the access is marked as both a read and a write.
1637 * If "expr" assigns something to a scalar variable, then we mark
1638 * the variable as having been assigned. If, furthermore, the expression
1639 * is affine, then keep track of this value in assigned_value
1640 * so that we can plug it in when we later come across the same variable.
1642 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1644 pet_expr *lhs, *rhs;
1645 enum pet_op_type op;
1647 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1648 if (op == pet_op_last) {
1649 unsupported(expr);
1650 return NULL;
1653 lhs = extract_expr(expr->getLHS());
1654 rhs = extract_expr(expr->getRHS());
1656 if (expr->isAssignmentOp() &&
1657 pet_expr_get_type(lhs) == pet_expr_access) {
1658 lhs = mark_write(lhs);
1659 if (expr->isCompoundAssignmentOp())
1660 lhs = pet_expr_access_set_read(lhs, 1);
1663 if (expr->getOpcode() == BO_Assign)
1664 assign(lhs, expr->getRHS());
1666 return pet_expr_new_binary(op, lhs, rhs);
1669 /* Construct a pet_scop with a single statement killing the entire
1670 * array "array".
1672 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1674 isl_id *id;
1675 isl_space *space;
1676 isl_multi_pw_aff *index;
1677 isl_map *access;
1678 pet_expr *expr;
1680 if (!array)
1681 return NULL;
1682 access = isl_map_from_range(isl_set_copy(array->extent));
1683 id = isl_set_get_tuple_id(array->extent);
1684 space = isl_space_alloc(ctx, 0, 0, 0);
1685 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1686 index = isl_multi_pw_aff_zero(space);
1687 expr = pet_expr_kill_from_access_and_index(access, index);
1688 return extract(stmt, expr);
1691 /* Construct a pet_scop for a (single) variable declaration.
1693 * The scop contains the variable being declared (as an array)
1694 * and a statement killing the array.
1696 * If the variable is initialized in the AST, then the scop
1697 * also contains an assignment to the variable.
1699 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1701 Decl *decl;
1702 VarDecl *vd;
1703 pet_expr *lhs, *rhs, *pe;
1704 struct pet_scop *scop_decl, *scop;
1705 struct pet_array *array;
1707 if (!stmt->isSingleDecl()) {
1708 unsupported(stmt);
1709 return NULL;
1712 decl = stmt->getSingleDecl();
1713 vd = cast<VarDecl>(decl);
1715 array = extract_array(ctx, vd, NULL);
1716 if (array)
1717 array->declared = 1;
1718 scop_decl = kill(stmt, array);
1719 scop_decl = pet_scop_add_array(scop_decl, array);
1721 if (!vd->getInit())
1722 return scop_decl;
1724 lhs = extract_access_expr(vd);
1725 rhs = extract_expr(vd->getInit());
1727 lhs = mark_write(lhs);
1728 assign(lhs, vd->getInit());
1730 pe = pet_expr_new_binary(pet_op_assign, lhs, rhs);
1731 scop = extract(stmt, pe);
1733 scop_decl = pet_scop_prefix(scop_decl, 0);
1734 scop = pet_scop_prefix(scop, 1);
1736 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1738 return scop;
1741 /* Construct a pet_expr representing a conditional operation.
1743 * We first try to extract the condition as an affine expression.
1744 * If that fails, we construct a pet_expr tree representing the condition.
1746 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1748 pet_expr *cond, *lhs, *rhs;
1749 isl_pw_aff *pa;
1751 pa = try_extract_affine(expr->getCond());
1752 if (pa) {
1753 isl_multi_pw_aff *test = isl_multi_pw_aff_from_pw_aff(pa);
1754 test = isl_multi_pw_aff_from_range(test);
1755 cond = pet_expr_from_index(test);
1756 } else
1757 cond = extract_expr(expr->getCond());
1758 lhs = extract_expr(expr->getTrueExpr());
1759 rhs = extract_expr(expr->getFalseExpr());
1761 return pet_expr_new_ternary(cond, lhs, rhs);
1764 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1766 return extract_expr(expr->getSubExpr());
1769 /* Construct a pet_expr representing a floating point value.
1771 * If the floating point literal does not appear in a macro,
1772 * then we use the original representation in the source code
1773 * as the string representation. Otherwise, we use the pretty
1774 * printer to produce a string representation.
1776 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1778 double d;
1779 string s;
1780 const LangOptions &LO = PP.getLangOpts();
1781 SourceLocation loc = expr->getLocation();
1783 if (!loc.isMacroID()) {
1784 SourceManager &SM = PP.getSourceManager();
1785 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1786 s = string(SM.getCharacterData(loc), len);
1787 } else {
1788 llvm::raw_string_ostream S(s);
1789 expr->printPretty(S, 0, PrintingPolicy(LO));
1790 S.str();
1792 d = expr->getValueAsApproximateDouble();
1793 return pet_expr_new_double(ctx, d, s.c_str());
1796 /* Convert the index expression "index" into an access pet_expr.
1798 __isl_give pet_expr *PetScan::extract_access_expr(
1799 __isl_take isl_multi_pw_aff *index)
1801 pet_expr *pe;
1802 int depth;
1804 depth = extract_depth(index);
1805 pe = pet_expr_from_index_and_depth(index, depth);
1807 return pe;
1810 /* Extract an index expression from "expr" and then convert it into
1811 * an access pet_expr.
1813 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
1815 return extract_access_expr(extract_index(expr));
1818 /* Extract an index expression from "decl" and then convert it into
1819 * an access pet_expr.
1821 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1823 return extract_access_expr(extract_index(decl));
1826 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
1828 return extract_expr(expr->getSubExpr());
1831 /* Extract an assume statement from the argument "expr"
1832 * of a __pencil_assume statement.
1834 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
1836 isl_pw_aff *cond;
1837 pet_expr *res;
1839 cond = try_extract_affine_condition(expr);
1840 if (!cond) {
1841 res = extract_expr(expr);
1842 } else {
1843 isl_multi_pw_aff *index;
1844 index = isl_multi_pw_aff_from_pw_aff(cond);
1845 index = isl_multi_pw_aff_from_range(index);
1846 res = pet_expr_from_index(index);
1848 return pet_expr_new_unary(pet_op_assume, res);
1851 /* Construct a pet_expr corresponding to the function call argument "expr".
1852 * The argument appears in position "pos" of a call to function "fd".
1854 * If we are passing along a pointer to an array element
1855 * or an entire row or even higher dimensional slice of an array,
1856 * then the function being called may write into the array.
1858 * We assume here that if the function is declared to take a pointer
1859 * to a const type, then the function will perform a read
1860 * and that otherwise, it will perform a write.
1862 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
1863 Expr *expr)
1865 pet_expr *res;
1866 int is_addr = 0, is_partial = 0;
1867 Stmt::StmtClass sc;
1869 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
1870 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
1871 expr = ice->getSubExpr();
1873 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
1874 UnaryOperator *op = cast<UnaryOperator>(expr);
1875 if (op->getOpcode() == UO_AddrOf) {
1876 is_addr = 1;
1877 expr = op->getSubExpr();
1880 res = extract_expr(expr);
1881 if (!res)
1882 return NULL;
1883 sc = expr->getStmtClass();
1884 if ((sc == Stmt::ArraySubscriptExprClass ||
1885 sc == Stmt::MemberExprClass) &&
1886 array_depth(expr->getType().getTypePtr()) > 0)
1887 is_partial = 1;
1888 if ((is_addr || is_partial) &&
1889 pet_expr_get_type(res) == pet_expr_access) {
1890 ParmVarDecl *parm;
1891 if (!fd->hasPrototype()) {
1892 report_prototype_required(expr);
1893 return pet_expr_free(res);
1895 parm = fd->getParamDecl(pos);
1896 if (!const_base(parm->getType()))
1897 res = mark_write(res);
1900 if (is_addr)
1901 res = pet_expr_new_unary(pet_op_address_of, res);
1902 return res;
1905 /* Construct a pet_expr representing a function call.
1907 * In the special case of a "call" to __pencil_assume,
1908 * construct an assume expression instead.
1910 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1912 pet_expr *res = NULL;
1913 FunctionDecl *fd;
1914 string name;
1915 unsigned n_arg;
1917 fd = expr->getDirectCallee();
1918 if (!fd) {
1919 unsupported(expr);
1920 return NULL;
1923 name = fd->getDeclName().getAsString();
1924 n_arg = expr->getNumArgs();
1926 if (n_arg == 1 && name == "__pencil_assume")
1927 return extract_assume(expr->getArg(0));
1929 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1930 if (!res)
1931 return NULL;
1933 for (int i = 0; i < n_arg; ++i) {
1934 Expr *arg = expr->getArg(i);
1935 res = pet_expr_set_arg(res, i,
1936 PetScan::extract_argument(fd, i, arg));
1939 return res;
1942 /* Construct a pet_expr representing a (C style) cast.
1944 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1946 pet_expr *arg;
1947 QualType type;
1949 arg = extract_expr(expr->getSubExpr());
1950 if (!arg)
1951 return NULL;
1953 type = expr->getTypeAsWritten();
1954 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1957 /* Construct a pet_expr representing an integer.
1959 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1961 return pet_expr_new_int(extract_int(expr));
1964 /* Try and construct a pet_expr representing "expr".
1966 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1968 switch (expr->getStmtClass()) {
1969 case Stmt::UnaryOperatorClass:
1970 return extract_expr(cast<UnaryOperator>(expr));
1971 case Stmt::CompoundAssignOperatorClass:
1972 case Stmt::BinaryOperatorClass:
1973 return extract_expr(cast<BinaryOperator>(expr));
1974 case Stmt::ImplicitCastExprClass:
1975 return extract_expr(cast<ImplicitCastExpr>(expr));
1976 case Stmt::ArraySubscriptExprClass:
1977 case Stmt::DeclRefExprClass:
1978 case Stmt::MemberExprClass:
1979 return extract_access_expr(expr);
1980 case Stmt::IntegerLiteralClass:
1981 return extract_expr(cast<IntegerLiteral>(expr));
1982 case Stmt::FloatingLiteralClass:
1983 return extract_expr(cast<FloatingLiteral>(expr));
1984 case Stmt::ParenExprClass:
1985 return extract_expr(cast<ParenExpr>(expr));
1986 case Stmt::ConditionalOperatorClass:
1987 return extract_expr(cast<ConditionalOperator>(expr));
1988 case Stmt::CallExprClass:
1989 return extract_expr(cast<CallExpr>(expr));
1990 case Stmt::CStyleCastExprClass:
1991 return extract_expr(cast<CStyleCastExpr>(expr));
1992 default:
1993 unsupported(expr);
1995 return NULL;
1998 /* Check if the given initialization statement is an assignment.
1999 * If so, return that assignment. Otherwise return NULL.
2001 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
2003 BinaryOperator *ass;
2005 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
2006 return NULL;
2008 ass = cast<BinaryOperator>(init);
2009 if (ass->getOpcode() != BO_Assign)
2010 return NULL;
2012 return ass;
2015 /* Check if the given initialization statement is a declaration
2016 * of a single variable.
2017 * If so, return that declaration. Otherwise return NULL.
2019 Decl *PetScan::initialization_declaration(Stmt *init)
2021 DeclStmt *decl;
2023 if (init->getStmtClass() != Stmt::DeclStmtClass)
2024 return NULL;
2026 decl = cast<DeclStmt>(init);
2028 if (!decl->isSingleDecl())
2029 return NULL;
2031 return decl->getSingleDecl();
2034 /* Given the assignment operator in the initialization of a for loop,
2035 * extract the induction variable, i.e., the (integer)variable being
2036 * assigned.
2038 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
2040 Expr *lhs;
2041 DeclRefExpr *ref;
2042 ValueDecl *decl;
2043 const Type *type;
2045 lhs = init->getLHS();
2046 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2047 unsupported(init);
2048 return NULL;
2051 ref = cast<DeclRefExpr>(lhs);
2052 decl = ref->getDecl();
2053 type = decl->getType().getTypePtr();
2055 if (!type->isIntegerType()) {
2056 unsupported(lhs);
2057 return NULL;
2060 return decl;
2063 /* Given the initialization statement of a for loop and the single
2064 * declaration in this initialization statement,
2065 * extract the induction variable, i.e., the (integer) variable being
2066 * declared.
2068 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
2070 VarDecl *vd;
2072 vd = cast<VarDecl>(decl);
2074 const QualType type = vd->getType();
2075 if (!type->isIntegerType()) {
2076 unsupported(init);
2077 return NULL;
2080 if (!vd->getInit()) {
2081 unsupported(init);
2082 return NULL;
2085 return vd;
2088 /* Check that op is of the form iv++ or iv--.
2089 * Return an affine expression "1" or "-1" accordingly.
2091 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
2092 clang::UnaryOperator *op, clang::ValueDecl *iv)
2094 Expr *sub;
2095 DeclRefExpr *ref;
2096 isl_space *space;
2097 isl_aff *aff;
2099 if (!op->isIncrementDecrementOp()) {
2100 unsupported(op);
2101 return NULL;
2104 sub = op->getSubExpr();
2105 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
2106 unsupported(op);
2107 return NULL;
2110 ref = cast<DeclRefExpr>(sub);
2111 if (ref->getDecl() != iv) {
2112 unsupported(op);
2113 return NULL;
2116 space = isl_space_params_alloc(ctx, 0);
2117 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2119 if (op->isIncrementOp())
2120 aff = isl_aff_add_constant_si(aff, 1);
2121 else
2122 aff = isl_aff_add_constant_si(aff, -1);
2124 return isl_pw_aff_from_aff(aff);
2127 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
2128 * has a single constant expression, then put this constant in *user.
2129 * The caller is assumed to have checked that this function will
2130 * be called exactly once.
2132 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
2133 void *user)
2135 isl_val **inc = (isl_val **)user;
2136 int res = 0;
2138 if (isl_aff_is_cst(aff))
2139 *inc = isl_aff_get_constant_val(aff);
2140 else
2141 res = -1;
2143 isl_set_free(set);
2144 isl_aff_free(aff);
2146 return res;
2149 /* Check if op is of the form
2151 * iv = iv + inc
2153 * and return inc as an affine expression.
2155 * We extract an affine expression from the RHS, subtract iv and return
2156 * the result.
2158 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
2159 clang::ValueDecl *iv)
2161 Expr *lhs;
2162 DeclRefExpr *ref;
2163 isl_id *id;
2164 isl_space *dim;
2165 isl_aff *aff;
2166 isl_pw_aff *val;
2168 if (op->getOpcode() != BO_Assign) {
2169 unsupported(op);
2170 return NULL;
2173 lhs = op->getLHS();
2174 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2175 unsupported(op);
2176 return NULL;
2179 ref = cast<DeclRefExpr>(lhs);
2180 if (ref->getDecl() != iv) {
2181 unsupported(op);
2182 return NULL;
2185 val = extract_affine(op->getRHS());
2187 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2189 dim = isl_space_params_alloc(ctx, 1);
2190 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2191 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2192 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2194 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
2196 return val;
2199 /* Check that op is of the form iv += cst or iv -= cst
2200 * and return an affine expression corresponding oto cst or -cst accordingly.
2202 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
2203 CompoundAssignOperator *op, clang::ValueDecl *iv)
2205 Expr *lhs;
2206 DeclRefExpr *ref;
2207 bool neg = false;
2208 isl_pw_aff *val;
2209 BinaryOperatorKind opcode;
2211 opcode = op->getOpcode();
2212 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
2213 unsupported(op);
2214 return NULL;
2216 if (opcode == BO_SubAssign)
2217 neg = true;
2219 lhs = op->getLHS();
2220 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2221 unsupported(op);
2222 return NULL;
2225 ref = cast<DeclRefExpr>(lhs);
2226 if (ref->getDecl() != iv) {
2227 unsupported(op);
2228 return NULL;
2231 val = extract_affine(op->getRHS());
2232 if (neg)
2233 val = isl_pw_aff_neg(val);
2235 return val;
2238 /* Check that the increment of the given for loop increments
2239 * (or decrements) the induction variable "iv" and return
2240 * the increment as an affine expression if successful.
2242 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
2243 ValueDecl *iv)
2245 Stmt *inc = stmt->getInc();
2247 if (!inc) {
2248 report_missing_increment(stmt);
2249 return NULL;
2252 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
2253 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
2254 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
2255 return extract_compound_increment(
2256 cast<CompoundAssignOperator>(inc), iv);
2257 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
2258 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
2260 unsupported(inc);
2261 return NULL;
2264 /* Embed the given iteration domain in an extra outer loop
2265 * with induction variable "var".
2266 * If this variable appeared as a parameter in the constraints,
2267 * it is replaced by the new outermost dimension.
2269 static __isl_give isl_set *embed(__isl_take isl_set *set,
2270 __isl_take isl_id *var)
2272 int pos;
2274 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
2275 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
2276 if (pos >= 0) {
2277 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
2278 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2281 isl_id_free(var);
2282 return set;
2285 /* Return those elements in the space of "cond" that come after
2286 * (based on "sign") an element in "cond".
2288 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
2290 isl_map *previous_to_this;
2292 if (sign > 0)
2293 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
2294 else
2295 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
2297 cond = isl_set_apply(cond, previous_to_this);
2299 return cond;
2302 /* Create the infinite iteration domain
2304 * { [id] : id >= 0 }
2306 * If "scop" has an affine skip of type pet_skip_later,
2307 * then remove those iterations i that have an earlier iteration
2308 * where the skip condition is satisfied, meaning that iteration i
2309 * is not executed.
2310 * Since we are dealing with a loop without loop iterator,
2311 * the skip condition cannot refer to the current loop iterator and
2312 * so effectively, the returned set is of the form
2314 * { [0]; [id] : id >= 1 and not skip }
2316 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
2317 struct pet_scop *scop)
2319 isl_ctx *ctx = isl_id_get_ctx(id);
2320 isl_set *domain;
2321 isl_set *skip;
2323 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
2324 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
2326 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
2327 return domain;
2329 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2330 skip = embed(skip, isl_id_copy(id));
2331 skip = isl_set_intersect(skip , isl_set_copy(domain));
2332 domain = isl_set_subtract(domain, after(skip, 1));
2334 return domain;
2337 /* Create an identity affine expression on the space containing "domain",
2338 * which is assumed to be one-dimensional.
2340 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
2342 isl_local_space *ls;
2344 ls = isl_local_space_from_space(isl_set_get_space(domain));
2345 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
2348 /* Create an affine expression that maps elements
2349 * of a single-dimensional array "id_test" to the previous element
2350 * (according to "inc"), provided this element belongs to "domain".
2351 * That is, create the affine expression
2353 * { id[x] -> id[x - inc] : x - inc in domain }
2355 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
2356 __isl_take isl_set *domain, __isl_take isl_val *inc)
2358 isl_space *space;
2359 isl_local_space *ls;
2360 isl_aff *aff;
2361 isl_multi_pw_aff *prev;
2363 space = isl_set_get_space(domain);
2364 ls = isl_local_space_from_space(space);
2365 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2366 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
2367 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
2368 domain = isl_set_preimage_multi_pw_aff(domain,
2369 isl_multi_pw_aff_copy(prev));
2370 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
2371 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
2373 return prev;
2376 /* Add an implication to "scop" expressing that if an element of
2377 * virtual array "id_test" has value "satisfied" then all previous elements
2378 * of this array also have that value. The set of previous elements
2379 * is bounded by "domain". If "sign" is negative then the iterator
2380 * is decreasing and we express that all subsequent array elements
2381 * (but still defined previously) have the same value.
2383 static struct pet_scop *add_implication(struct pet_scop *scop,
2384 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
2385 int satisfied)
2387 isl_space *space;
2388 isl_map *map;
2390 domain = isl_set_set_tuple_id(domain, id_test);
2391 space = isl_set_get_space(domain);
2392 if (sign > 0)
2393 map = isl_map_lex_ge(space);
2394 else
2395 map = isl_map_lex_le(space);
2396 map = isl_map_intersect_range(map, domain);
2397 scop = pet_scop_add_implication(scop, map, satisfied);
2399 return scop;
2402 /* Add a filter to "scop" that imposes that it is only executed
2403 * when the variable identified by "id_test" has a zero value
2404 * for all previous iterations of "domain".
2406 * In particular, add a filter that imposes that the array
2407 * has a zero value at the previous iteration of domain and
2408 * add an implication that implies that it then has that
2409 * value for all previous iterations.
2411 static struct pet_scop *scop_add_break(struct pet_scop *scop,
2412 __isl_take isl_id *id_test, __isl_take isl_set *domain,
2413 __isl_take isl_val *inc)
2415 isl_multi_pw_aff *prev;
2416 int sign = isl_val_sgn(inc);
2418 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2419 scop = add_implication(scop, id_test, domain, sign, 0);
2420 scop = pet_scop_filter(scop, prev, 0);
2422 return scop;
2425 /* Construct a pet_scop for an infinite loop around the given body.
2427 * We extract a pet_scop for the body and then embed it in a loop with
2428 * iteration domain
2430 * { [t] : t >= 0 }
2432 * and schedule
2434 * { [t] -> [t] }
2436 * If the body contains any break, then it is taken into
2437 * account in infinite_domain (if the skip condition is affine)
2438 * or in scop_add_break (if the skip condition is not affine).
2440 * If we were only able to extract part of the body, then simply
2441 * return that part.
2443 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2445 isl_id *id, *id_test;
2446 isl_set *domain;
2447 isl_aff *ident;
2448 struct pet_scop *scop;
2449 bool has_var_break;
2451 scop = extract(body);
2452 if (!scop)
2453 return NULL;
2454 if (partial)
2455 return scop;
2457 id = isl_id_alloc(ctx, "t", NULL);
2458 domain = infinite_domain(isl_id_copy(id), scop);
2459 ident = identity_aff(domain);
2461 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2462 if (has_var_break)
2463 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
2465 scop = pet_scop_embed(scop, isl_set_copy(domain),
2466 isl_aff_copy(ident), ident, id);
2467 if (has_var_break)
2468 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
2469 else
2470 isl_set_free(domain);
2472 return scop;
2475 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2477 * for (;;)
2478 * body
2481 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2483 clear_assignments clear(assigned_value);
2484 clear.TraverseStmt(stmt->getBody());
2486 return extract_infinite_loop(stmt->getBody());
2489 /* Create an index expression for an access to a virtual array
2490 * representing the result of a condition.
2491 * Unlike other accessed data, the id of the array is NULL as
2492 * there is no ValueDecl in the program corresponding to the virtual
2493 * array.
2494 * The array starts out as a scalar, but grows along with the
2495 * statement writing to the array in pet_scop_embed.
2497 static __isl_give isl_multi_pw_aff *create_test_index(isl_ctx *ctx, int test_nr)
2499 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2500 isl_id *id;
2501 char name[50];
2503 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2504 id = isl_id_alloc(ctx, name, NULL);
2505 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2506 return isl_multi_pw_aff_zero(dim);
2509 /* Add an array with the given extent (range of "index") to the list
2510 * of arrays in "scop" and return the extended pet_scop.
2511 * The array is marked as attaining values 0 and 1 only and
2512 * as each element being assigned at most once.
2514 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2515 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
2517 isl_ctx *ctx = isl_multi_pw_aff_get_ctx(index);
2518 isl_space *dim;
2519 struct pet_array *array;
2520 isl_map *access;
2522 if (!scop)
2523 return NULL;
2524 if (!ctx)
2525 goto error;
2527 array = isl_calloc_type(ctx, struct pet_array);
2528 if (!array)
2529 goto error;
2531 access = isl_map_from_multi_pw_aff(isl_multi_pw_aff_copy(index));
2532 array->extent = isl_map_range(access);
2533 dim = isl_space_params_alloc(ctx, 0);
2534 array->context = isl_set_universe(dim);
2535 dim = isl_space_set_alloc(ctx, 0, 1);
2536 array->value_bounds = isl_set_universe(dim);
2537 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2538 isl_dim_set, 0, 0);
2539 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2540 isl_dim_set, 0, 1);
2541 array->element_type = strdup("int");
2542 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2543 array->uniquely_defined = 1;
2545 if (!array->extent || !array->context)
2546 array = pet_array_free(array);
2548 scop = pet_scop_add_array(scop, array);
2550 return scop;
2551 error:
2552 pet_scop_free(scop);
2553 return NULL;
2556 /* Construct a pet_scop for a while loop of the form
2558 * while (pa)
2559 * body
2561 * In particular, construct a scop for an infinite loop around body and
2562 * intersect the domain with the affine expression.
2563 * Note that this intersection may result in an empty loop.
2565 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2566 Stmt *body)
2568 struct pet_scop *scop;
2569 isl_set *dom;
2570 isl_set *valid;
2572 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2573 dom = isl_pw_aff_non_zero_set(pa);
2574 scop = extract_infinite_loop(body);
2575 scop = pet_scop_restrict(scop, dom);
2576 scop = pet_scop_restrict_context(scop, valid);
2578 return scop;
2581 /* Construct a scop for a while, given the scops for the condition
2582 * and the body, the filter identifier and the iteration domain of
2583 * the while loop.
2585 * In particular, the scop for the condition is filtered to depend
2586 * on "id_test" evaluating to true for all previous iterations
2587 * of the loop, while the scop for the body is filtered to depend
2588 * on "id_test" evaluating to true for all iterations up to the
2589 * current iteration.
2590 * The actual filter only imposes that this virtual array has
2591 * value one on the previous or the current iteration.
2592 * The fact that this condition also applies to the previous
2593 * iterations is enforced by an implication.
2595 * These filtered scops are then combined into a single scop.
2597 * "sign" is positive if the iterator increases and negative
2598 * if it decreases.
2600 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2601 struct pet_scop *scop_body, __isl_take isl_id *id_test,
2602 __isl_take isl_set *domain, __isl_take isl_val *inc)
2604 isl_ctx *ctx = isl_set_get_ctx(domain);
2605 isl_space *space;
2606 isl_multi_pw_aff *test_index;
2607 isl_multi_pw_aff *prev;
2608 int sign = isl_val_sgn(inc);
2609 struct pet_scop *scop;
2611 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2612 scop_cond = pet_scop_filter(scop_cond, prev, 1);
2614 space = isl_space_map_from_set(isl_set_get_space(domain));
2615 test_index = isl_multi_pw_aff_identity(space);
2616 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
2617 isl_id_copy(id_test));
2618 scop_body = pet_scop_filter(scop_body, test_index, 1);
2620 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
2621 scop = add_implication(scop, id_test, domain, sign, 1);
2623 return scop;
2626 /* Check if the while loop is of the form
2628 * while (affine expression)
2629 * body
2631 * If so, call extract_affine_while to construct a scop.
2633 * Otherwise, construct a generic while scop, with iteration domain
2634 * { [t] : t >= 0 }. The scop consists of two parts, one for
2635 * evaluating the condition and one for the body.
2636 * The schedule is adjusted to reflect that the condition is evaluated
2637 * before the body is executed and the body is filtered to depend
2638 * on the result of the condition evaluating to true on all iterations
2639 * up to the current iteration, while the evaluation of the condition itself
2640 * is filtered to depend on the result of the condition evaluating to true
2641 * on all previous iterations.
2642 * The context of the scop representing the body is dropped
2643 * because we don't know how many times the body will be executed,
2644 * if at all.
2646 * If the body contains any break, then it is taken into
2647 * account in infinite_domain (if the skip condition is affine)
2648 * or in scop_add_break (if the skip condition is not affine).
2650 * If we were only able to extract part of the body, then simply
2651 * return that part.
2653 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2655 Expr *cond;
2656 int test_nr, stmt_nr;
2657 isl_id *id, *id_test, *id_break_test;
2658 isl_multi_pw_aff *test_index;
2659 isl_set *domain;
2660 isl_aff *ident;
2661 isl_pw_aff *pa;
2662 struct pet_scop *scop, *scop_body;
2663 bool has_var_break;
2665 cond = stmt->getCond();
2666 if (!cond) {
2667 unsupported(stmt);
2668 return NULL;
2671 clear_assignments clear(assigned_value);
2672 clear.TraverseStmt(stmt->getBody());
2674 pa = try_extract_affine_condition(cond);
2675 if (pa)
2676 return extract_affine_while(pa, stmt->getBody());
2678 if (!allow_nested) {
2679 unsupported(stmt);
2680 return NULL;
2683 test_nr = n_test++;
2684 stmt_nr = n_stmt++;
2685 scop_body = extract(stmt->getBody());
2686 if (partial)
2687 return scop_body;
2689 test_index = create_test_index(ctx, test_nr);
2690 scop = extract_non_affine_condition(cond, stmt_nr,
2691 isl_multi_pw_aff_copy(test_index));
2692 scop = scop_add_array(scop, test_index, ast_context);
2693 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2694 isl_multi_pw_aff_free(test_index);
2696 id = isl_id_alloc(ctx, "t", NULL);
2697 domain = infinite_domain(isl_id_copy(id), scop_body);
2698 ident = identity_aff(domain);
2700 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2701 if (has_var_break)
2702 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2704 scop = pet_scop_prefix(scop, 0);
2705 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_aff_copy(ident),
2706 isl_aff_copy(ident), isl_id_copy(id));
2707 scop_body = pet_scop_reset_context(scop_body);
2708 scop_body = pet_scop_prefix(scop_body, 1);
2709 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2710 isl_aff_copy(ident), ident, id);
2712 if (has_var_break) {
2713 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2714 isl_set_copy(domain), isl_val_one(ctx));
2715 scop_body = scop_add_break(scop_body, id_break_test,
2716 isl_set_copy(domain), isl_val_one(ctx));
2718 scop = scop_add_while(scop, scop_body, id_test, domain,
2719 isl_val_one(ctx));
2721 return scop;
2724 /* Check whether "cond" expresses a simple loop bound
2725 * on the only set dimension.
2726 * In particular, if "up" is set then "cond" should contain only
2727 * upper bounds on the set dimension.
2728 * Otherwise, it should contain only lower bounds.
2730 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2732 if (isl_val_is_pos(inc))
2733 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2734 else
2735 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2738 /* Extend a condition on a given iteration of a loop to one that
2739 * imposes the same condition on all previous iterations.
2740 * "domain" expresses the lower [upper] bound on the iterations
2741 * when inc is positive [negative].
2743 * In particular, we construct the condition (when inc is positive)
2745 * forall i' : (domain(i') and i' <= i) => cond(i')
2747 * which is equivalent to
2749 * not exists i' : domain(i') and i' <= i and not cond(i')
2751 * We construct this set by negating cond, applying a map
2753 * { [i'] -> [i] : domain(i') and i' <= i }
2755 * and then negating the result again.
2757 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2758 __isl_take isl_set *domain, __isl_take isl_val *inc)
2760 isl_map *previous_to_this;
2762 if (isl_val_is_pos(inc))
2763 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2764 else
2765 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2767 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2769 cond = isl_set_complement(cond);
2770 cond = isl_set_apply(cond, previous_to_this);
2771 cond = isl_set_complement(cond);
2773 isl_val_free(inc);
2775 return cond;
2778 /* Construct a domain of the form
2780 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2782 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2783 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2785 isl_aff *aff;
2786 isl_space *dim;
2787 isl_set *set;
2789 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2790 dim = isl_pw_aff_get_domain_space(init);
2791 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2792 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2793 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2795 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2796 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2797 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2798 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2800 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2802 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2804 return isl_set_params(set);
2807 /* Assuming "cond" represents a bound on a loop where the loop
2808 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2809 * is possible.
2811 * Under the given assumptions, wrapping is only possible if "cond" allows
2812 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2813 * increasing iterator and 0 in case of a decreasing iterator.
2815 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2816 __isl_keep isl_val *inc)
2818 bool cw;
2819 isl_ctx *ctx;
2820 isl_val *limit;
2821 isl_set *test;
2823 test = isl_set_copy(cond);
2825 ctx = isl_set_get_ctx(test);
2826 if (isl_val_is_neg(inc))
2827 limit = isl_val_zero(ctx);
2828 else {
2829 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2830 limit = isl_val_2exp(limit);
2831 limit = isl_val_sub_ui(limit, 1);
2834 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2835 cw = !isl_set_is_empty(test);
2836 isl_set_free(test);
2838 return cw;
2841 /* Given a one-dimensional space, construct the following affine expression
2842 * on this space
2844 * { [v] -> [v mod 2^width] }
2846 * where width is the number of bits used to represent the values
2847 * of the unsigned variable "iv".
2849 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2850 ValueDecl *iv)
2852 isl_ctx *ctx;
2853 isl_val *mod;
2854 isl_aff *aff;
2856 ctx = isl_space_get_ctx(dim);
2857 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2858 mod = isl_val_2exp(mod);
2860 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2861 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2862 aff = isl_aff_mod_val(aff, mod);
2864 return aff;
2867 /* Project out the parameter "id" from "set".
2869 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2870 __isl_keep isl_id *id)
2872 int pos;
2874 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2875 if (pos >= 0)
2876 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2878 return set;
2881 /* Compute the set of parameters for which "set1" is a subset of "set2".
2883 * set1 is a subset of set2 if
2885 * forall i in set1 : i in set2
2887 * or
2889 * not exists i in set1 and i not in set2
2891 * i.e.,
2893 * not exists i in set1 \ set2
2895 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2896 __isl_take isl_set *set2)
2898 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2901 /* Compute the set of parameter values for which "cond" holds
2902 * on the next iteration for each element of "dom".
2904 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2905 * and then compute the set of parameters for which the result is a subset
2906 * of "cond".
2908 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2909 __isl_take isl_set *dom, __isl_take isl_val *inc)
2911 isl_space *space;
2912 isl_aff *aff;
2913 isl_map *next;
2915 space = isl_set_get_space(dom);
2916 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2917 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2918 aff = isl_aff_add_constant_val(aff, inc);
2919 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2921 dom = isl_set_apply(dom, next);
2923 return enforce_subset(dom, cond);
2926 /* Construct a pet_scop for a for statement.
2927 * The for loop is required to be of the form
2929 * for (i = init; condition; ++i)
2931 * or
2933 * for (i = init; condition; --i)
2935 * The initialization of the for loop should either be an assignment
2936 * to an integer variable, or a declaration of such a variable with
2937 * initialization.
2939 * The condition is allowed to contain nested accesses, provided
2940 * they are not being written to inside the body of the loop.
2941 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2942 * essentially treated as a while loop, with iteration domain
2943 * { [i] : i >= init }.
2945 * We extract a pet_scop for the body and then embed it in a loop with
2946 * iteration domain and schedule
2948 * { [i] : i >= init and condition' }
2949 * { [i] -> [i] }
2951 * or
2953 * { [i] : i <= init and condition' }
2954 * { [i] -> [-i] }
2956 * Where condition' is equal to condition if the latter is
2957 * a simple upper [lower] bound and a condition that is extended
2958 * to apply to all previous iterations otherwise.
2960 * If the condition is non-affine, then we drop the condition from the
2961 * iteration domain and instead create a separate statement
2962 * for evaluating the condition. The body is then filtered to depend
2963 * on the result of the condition evaluating to true on all iterations
2964 * up to the current iteration, while the evaluation the condition itself
2965 * is filtered to depend on the result of the condition evaluating to true
2966 * on all previous iterations.
2967 * The context of the scop representing the body is dropped
2968 * because we don't know how many times the body will be executed,
2969 * if at all.
2971 * If the stride of the loop is not 1, then "i >= init" is replaced by
2973 * (exists a: i = init + stride * a and a >= 0)
2975 * If the loop iterator i is unsigned, then wrapping may occur.
2976 * We therefore use a virtual iterator instead that does not wrap.
2977 * However, the condition in the code applies
2978 * to the wrapped value, so we need to change condition(i)
2979 * into condition([i % 2^width]). Similarly, we replace all accesses
2980 * to the original iterator by the wrapping of the virtual iterator.
2981 * Note that there may be no need to perform this final wrapping
2982 * if the loop condition (after wrapping) satisfies certain conditions.
2983 * However, the is_simple_bound condition is not enough since it doesn't
2984 * check if there even is an upper bound.
2986 * Wrapping on unsigned iterators can be avoided entirely if
2987 * loop condition is simple, the loop iterator is incremented
2988 * [decremented] by one and the last value before wrapping cannot
2989 * possibly satisfy the loop condition.
2991 * Before extracting a pet_scop from the body we remove all
2992 * assignments in assigned_value to variables that are assigned
2993 * somewhere in the body of the loop.
2995 * Valid parameters for a for loop are those for which the initial
2996 * value itself, the increment on each domain iteration and
2997 * the condition on both the initial value and
2998 * the result of incrementing the iterator for each iteration of the domain
2999 * can be evaluated.
3000 * If the loop condition is non-affine, then we only consider validity
3001 * of the initial value.
3003 * If the body contains any break, then we keep track of it in "skip"
3004 * (if the skip condition is affine) or it is handled in scop_add_break
3005 * (if the skip condition is not affine).
3006 * Note that the affine break condition needs to be considered with
3007 * respect to previous iterations in the virtual domain (if any).
3009 * If we were only able to extract part of the body, then simply
3010 * return that part.
3012 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
3014 BinaryOperator *ass;
3015 Decl *decl;
3016 Stmt *init;
3017 Expr *lhs, *rhs;
3018 ValueDecl *iv;
3019 isl_local_space *ls;
3020 isl_set *domain;
3021 isl_aff *sched;
3022 isl_set *cond = NULL;
3023 isl_set *skip = NULL;
3024 isl_id *id, *id_test = NULL, *id_break_test;
3025 struct pet_scop *scop, *scop_cond = NULL;
3026 assigned_value_cache cache(assigned_value);
3027 isl_val *inc;
3028 bool was_assigned;
3029 bool is_one;
3030 bool is_unsigned;
3031 bool is_simple;
3032 bool is_virtual;
3033 bool has_affine_break;
3034 bool has_var_break;
3035 isl_aff *wrap = NULL;
3036 isl_pw_aff *pa, *pa_inc, *init_val;
3037 isl_set *valid_init;
3038 isl_set *valid_cond;
3039 isl_set *valid_cond_init;
3040 isl_set *valid_cond_next;
3041 isl_set *valid_inc;
3042 int stmt_id;
3044 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
3045 return extract_infinite_for(stmt);
3047 init = stmt->getInit();
3048 if (!init) {
3049 unsupported(stmt);
3050 return NULL;
3052 if ((ass = initialization_assignment(init)) != NULL) {
3053 iv = extract_induction_variable(ass);
3054 if (!iv)
3055 return NULL;
3056 lhs = ass->getLHS();
3057 rhs = ass->getRHS();
3058 } else if ((decl = initialization_declaration(init)) != NULL) {
3059 VarDecl *var = extract_induction_variable(init, decl);
3060 if (!var)
3061 return NULL;
3062 iv = var;
3063 rhs = var->getInit();
3064 lhs = create_DeclRefExpr(var);
3065 } else {
3066 unsupported(stmt->getInit());
3067 return NULL;
3070 assigned_value.erase(iv);
3071 clear_assignments clear(assigned_value);
3072 clear.TraverseStmt(stmt->getBody());
3074 was_assigned = assigned_value.find(iv) != assigned_value.end();
3075 clear_assignment(assigned_value, iv);
3076 init_val = extract_affine(rhs);
3077 if (!was_assigned)
3078 assigned_value.erase(iv);
3079 if (!init_val)
3080 return NULL;
3082 pa_inc = extract_increment(stmt, iv);
3083 if (!pa_inc) {
3084 isl_pw_aff_free(init_val);
3085 return NULL;
3088 inc = NULL;
3089 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
3090 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
3091 isl_pw_aff_free(init_val);
3092 isl_pw_aff_free(pa_inc);
3093 unsupported(stmt->getInc());
3094 isl_val_free(inc);
3095 return NULL;
3098 pa = try_extract_nested_condition(stmt->getCond());
3099 if (allow_nested && (!pa || pet_nested_any_in_pw_aff(pa)))
3100 stmt_id = n_stmt++;
3102 scop = extract(stmt->getBody());
3103 if (partial) {
3104 isl_pw_aff_free(init_val);
3105 isl_pw_aff_free(pa_inc);
3106 isl_pw_aff_free(pa);
3107 isl_val_free(inc);
3108 return scop;
3111 valid_inc = isl_pw_aff_domain(pa_inc);
3113 is_unsigned = iv->getType()->isUnsignedIntegerType();
3115 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
3117 has_affine_break = scop &&
3118 pet_scop_has_affine_skip(scop, pet_skip_later);
3119 if (has_affine_break)
3120 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
3121 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
3122 if (has_var_break)
3123 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
3125 if (pa && !is_nested_allowed(pa, scop)) {
3126 isl_pw_aff_free(pa);
3127 pa = NULL;
3130 if (!allow_nested && !pa)
3131 pa = try_extract_affine_condition(stmt->getCond());
3132 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3133 cond = isl_pw_aff_non_zero_set(pa);
3134 if (allow_nested && !cond) {
3135 isl_multi_pw_aff *test_index;
3136 int save_n_stmt = n_stmt;
3137 test_index = create_test_index(ctx, n_test++);
3138 n_stmt = stmt_id;
3139 scop_cond = extract_non_affine_condition(stmt->getCond(),
3140 n_stmt++, isl_multi_pw_aff_copy(test_index));
3141 n_stmt = save_n_stmt;
3142 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
3143 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
3144 isl_dim_out);
3145 isl_multi_pw_aff_free(test_index);
3146 scop_cond = pet_scop_prefix(scop_cond, 0);
3147 scop = pet_scop_reset_context(scop);
3148 scop = pet_scop_prefix(scop, 1);
3149 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
3152 cond = embed(cond, isl_id_copy(id));
3153 skip = embed(skip, isl_id_copy(id));
3154 valid_cond = isl_set_coalesce(valid_cond);
3155 valid_cond = embed(valid_cond, isl_id_copy(id));
3156 valid_inc = embed(valid_inc, isl_id_copy(id));
3157 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
3158 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
3160 valid_cond_init = enforce_subset(
3161 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
3162 isl_set_copy(valid_cond));
3163 if (is_one && !is_virtual) {
3164 isl_pw_aff_free(init_val);
3165 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
3166 lhs, rhs, init);
3167 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3168 valid_init = set_project_out_by_id(valid_init, id);
3169 domain = isl_pw_aff_non_zero_set(pa);
3170 } else {
3171 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
3172 domain = strided_domain(isl_id_copy(id), init_val,
3173 isl_val_copy(inc));
3176 domain = embed(domain, isl_id_copy(id));
3177 if (is_virtual) {
3178 isl_map *rev_wrap;
3179 wrap = compute_wrapping(isl_set_get_space(cond), iv);
3180 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
3181 rev_wrap = isl_map_reverse(rev_wrap);
3182 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
3183 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
3184 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
3185 valid_inc = isl_set_apply(valid_inc, rev_wrap);
3187 is_simple = is_simple_bound(cond, inc);
3188 if (!is_simple) {
3189 cond = isl_set_gist(cond, isl_set_copy(domain));
3190 is_simple = is_simple_bound(cond, inc);
3192 if (!is_simple)
3193 cond = valid_for_each_iteration(cond,
3194 isl_set_copy(domain), isl_val_copy(inc));
3195 domain = isl_set_intersect(domain, cond);
3196 if (has_affine_break) {
3197 skip = isl_set_intersect(skip , isl_set_copy(domain));
3198 skip = after(skip, isl_val_sgn(inc));
3199 domain = isl_set_subtract(domain, skip);
3201 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
3202 ls = isl_local_space_from_space(isl_set_get_space(domain));
3203 sched = isl_aff_var_on_domain(ls, isl_dim_set, 0);
3204 if (isl_val_is_neg(inc))
3205 sched = isl_aff_neg(sched);
3207 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
3208 isl_val_copy(inc));
3209 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
3211 if (!is_virtual)
3212 wrap = identity_aff(domain);
3214 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
3215 isl_aff_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
3216 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
3217 scop = resolve_nested(scop);
3218 if (has_var_break)
3219 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
3220 isl_val_copy(inc));
3221 if (id_test) {
3222 scop = scop_add_while(scop_cond, scop, id_test, domain,
3223 isl_val_copy(inc));
3224 isl_set_free(valid_inc);
3225 } else {
3226 scop = pet_scop_restrict_context(scop, valid_inc);
3227 scop = pet_scop_restrict_context(scop, valid_cond_next);
3228 scop = pet_scop_restrict_context(scop, valid_cond_init);
3229 isl_set_free(domain);
3231 clear_assignment(assigned_value, iv);
3233 isl_val_free(inc);
3235 scop = pet_scop_restrict_context(scop, valid_init);
3237 return scop;
3240 /* Try and construct a pet_scop corresponding to a compound statement.
3242 * "skip_declarations" is set if we should skip initial declarations
3243 * in the children of the compound statements. This then implies
3244 * that this sequence of children should not be treated as a block
3245 * since the initial statements may be skipped.
3247 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
3249 return extract(stmt->children(), !skip_declarations, skip_declarations);
3252 /* For each nested access parameter in "space",
3253 * construct a corresponding pet_expr, place it in args and
3254 * record its position in "param2pos".
3255 * "n_arg" is the number of elements that are already in args.
3256 * The position recorded in "param2pos" takes this number into account.
3257 * If the pet_expr corresponding to a parameter is identical to
3258 * the pet_expr corresponding to an earlier parameter, then these two
3259 * parameters are made to refer to the same element in args.
3261 * Return the final number of elements in args or -1 if an error has occurred.
3263 int PetScan::extract_nested(__isl_keep isl_space *space,
3264 int n_arg, pet_expr **args, std::map<int,int> &param2pos)
3266 int nparam;
3268 nparam = isl_space_dim(space, isl_dim_param);
3269 for (int i = 0; i < nparam; ++i) {
3270 int j;
3271 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3272 Expr *nested;
3274 if (!pet_nested_in_id(id)) {
3275 isl_id_free(id);
3276 continue;
3279 nested = (Expr *) isl_id_get_user(id);
3280 args[n_arg] = extract_expr(nested);
3281 isl_id_free(id);
3282 if (!args[n_arg])
3283 return -1;
3285 for (j = 0; j < n_arg; ++j)
3286 if (pet_expr_is_equal(args[j], args[n_arg]))
3287 break;
3289 if (j < n_arg) {
3290 pet_expr_free(args[n_arg]);
3291 args[n_arg] = NULL;
3292 param2pos[i] = j;
3293 } else
3294 param2pos[i] = n_arg++;
3297 return n_arg;
3300 /* For each nested access parameter in the access relations in "expr",
3301 * construct a corresponding pet_expr, place it in the arguments of "expr"
3302 * and record its position in "param2pos".
3303 * n is the number of nested access parameters.
3305 __isl_give pet_expr *PetScan::extract_nested(__isl_take pet_expr *expr, int n,
3306 std::map<int,int> &param2pos)
3308 isl_space *space;
3309 int i;
3310 pet_expr **args;
3312 args = isl_calloc_array(ctx, pet_expr *, n);
3313 if (!args)
3314 return pet_expr_free(expr);
3316 space = pet_expr_access_get_parameter_space(expr);
3317 n = extract_nested(space, 0, args, param2pos);
3318 isl_space_free(space);
3320 if (n < 0)
3321 expr = pet_expr_free(expr);
3322 else
3323 expr = pet_expr_set_n_arg(expr, n);
3325 for (i = 0; i < n; ++i)
3326 expr = pet_expr_set_arg(expr, i, args[i]);
3327 free(args);
3329 return expr;
3332 /* Look for parameters in any access relation in "expr" that
3333 * refer to nested accesses. In particular, these are
3334 * parameters with no name.
3336 * If there are any such parameters, then the domain of the index
3337 * expression and the access relation, which is still [] at this point,
3338 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
3339 * (after identifying identical nested accesses).
3341 * This transformation is performed in several steps.
3342 * We first extract the arguments in extract_nested.
3343 * param2pos maps the original parameter position to the position
3344 * of the argument.
3345 * Then we move these parameters to input dimensions.
3346 * t2pos maps the positions of these temporary input dimensions
3347 * to the positions of the corresponding arguments.
3348 * Finally, we express these temporary dimensions in terms of the domain
3349 * [[] -> [t_1,...,t_n]] and precompose index expression and access
3350 * relations with this function.
3352 __isl_give pet_expr *PetScan::resolve_nested(__isl_take pet_expr *expr)
3354 int n;
3355 int nparam;
3356 isl_space *space;
3357 isl_local_space *ls;
3358 isl_aff *aff;
3359 isl_multi_aff *ma;
3360 std::map<int,int> param2pos;
3361 std::map<int,int> t2pos;
3363 if (!expr)
3364 return expr;
3366 n = pet_expr_get_n_arg(expr);
3367 for (int i = 0; i < n; ++i) {
3368 pet_expr *arg;
3369 arg = pet_expr_get_arg(expr, i);
3370 arg = resolve_nested(arg);
3371 expr = pet_expr_set_arg(expr, i, arg);
3374 if (pet_expr_get_type(expr) != pet_expr_access)
3375 return expr;
3377 space = pet_expr_access_get_parameter_space(expr);
3378 n = pet_nested_n_in_space(space);
3379 isl_space_free(space);
3380 if (n == 0)
3381 return expr;
3383 expr = extract_nested(expr, n, param2pos);
3384 if (!expr)
3385 return NULL;
3387 expr = pet_expr_access_align_params(expr);
3388 if (!expr)
3389 return NULL;
3391 n = 0;
3392 space = pet_expr_access_get_parameter_space(expr);
3393 nparam = isl_space_dim(space, isl_dim_param);
3394 for (int i = nparam - 1; i >= 0; --i) {
3395 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3396 if (!pet_nested_in_id(id)) {
3397 isl_id_free(id);
3398 continue;
3401 expr = pet_expr_access_move_dims(expr,
3402 isl_dim_in, n, isl_dim_param, i, 1);
3403 t2pos[n] = param2pos[i];
3404 n++;
3406 isl_id_free(id);
3408 isl_space_free(space);
3410 space = pet_expr_access_get_parameter_space(expr);
3411 space = isl_space_set_from_params(space);
3412 space = isl_space_add_dims(space, isl_dim_set,
3413 pet_expr_get_n_arg(expr));
3414 space = isl_space_wrap(isl_space_from_range(space));
3415 ls = isl_local_space_from_space(isl_space_copy(space));
3416 space = isl_space_from_domain(space);
3417 space = isl_space_add_dims(space, isl_dim_out, n);
3418 ma = isl_multi_aff_zero(space);
3420 for (int i = 0; i < n; ++i) {
3421 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3422 isl_dim_set, t2pos[i]);
3423 ma = isl_multi_aff_set_aff(ma, i, aff);
3425 isl_local_space_free(ls);
3427 expr = pet_expr_access_pullback_multi_aff(expr, ma);
3429 return expr;
3432 /* Return the file offset of the expansion location of "Loc".
3434 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3436 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3439 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3441 /* Return a SourceLocation for the location after the first semicolon
3442 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3443 * call it and also skip trailing spaces and newline.
3445 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3446 const LangOptions &LO)
3448 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3451 #else
3453 /* Return a SourceLocation for the location after the first semicolon
3454 * after "loc". If Lexer::findLocationAfterToken is not available,
3455 * we look in the underlying character data for the first semicolon.
3457 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3458 const LangOptions &LO)
3460 const char *semi;
3461 const char *s = SM.getCharacterData(loc);
3463 semi = strchr(s, ';');
3464 if (!semi)
3465 return SourceLocation();
3466 return loc.getFileLocWithOffset(semi + 1 - s);
3469 #endif
3471 /* If the token at "loc" is the first token on the line, then return
3472 * a location referring to the start of the line.
3473 * Otherwise, return "loc".
3475 * This function is used to extend a scop to the start of the line
3476 * if the first token of the scop is also the first token on the line.
3478 * We look for the first token on the line. If its location is equal to "loc",
3479 * then the latter is the location of the first token on the line.
3481 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3482 SourceManager &SM, const LangOptions &LO)
3484 std::pair<FileID, unsigned> file_offset_pair;
3485 llvm::StringRef file;
3486 const char *pos;
3487 Token tok;
3488 SourceLocation token_loc, line_loc;
3489 int col;
3491 loc = SM.getExpansionLoc(loc);
3492 col = SM.getExpansionColumnNumber(loc);
3493 line_loc = loc.getLocWithOffset(1 - col);
3494 file_offset_pair = SM.getDecomposedLoc(line_loc);
3495 file = SM.getBufferData(file_offset_pair.first, NULL);
3496 pos = file.data() + file_offset_pair.second;
3498 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3499 file.begin(), pos, file.end());
3500 lexer.LexFromRawLexer(tok);
3501 token_loc = tok.getLocation();
3503 if (token_loc == loc)
3504 return line_loc;
3505 else
3506 return loc;
3509 /* Update start and end of "scop" to include the region covered by "range".
3510 * If "skip_semi" is set, then we assume "range" is followed by
3511 * a semicolon and also include this semicolon.
3513 struct pet_scop *PetScan::update_scop_start_end(struct pet_scop *scop,
3514 SourceRange range, bool skip_semi)
3516 SourceLocation loc = range.getBegin();
3517 SourceManager &SM = PP.getSourceManager();
3518 const LangOptions &LO = PP.getLangOpts();
3519 unsigned start, end;
3521 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3522 start = getExpansionOffset(SM, loc);
3523 loc = range.getEnd();
3524 if (skip_semi)
3525 loc = location_after_semi(loc, SM, LO);
3526 else
3527 loc = PP.getLocForEndOfToken(loc);
3528 end = getExpansionOffset(SM, loc);
3530 scop = pet_scop_update_start_end(scop, start, end);
3531 return scop;
3534 /* Convert a top-level pet_expr to a pet_scop with one statement.
3535 * This mainly involves resolving nested expression parameters
3536 * and setting the name of the iteration space.
3537 * The name is given by "label" if it is non-NULL. Otherwise,
3538 * it is of the form S_<n_stmt>.
3539 * start and end of the pet_scop are derived from those of "stmt".
3540 * If "stmt" is an expression statement, then its range does not
3541 * include the semicolon, while it should be included in the pet_scop.
3543 struct pet_scop *PetScan::extract(Stmt *stmt, __isl_take pet_expr *expr,
3544 __isl_take isl_id *label)
3546 struct pet_stmt *ps;
3547 struct pet_scop *scop;
3548 SourceLocation loc = stmt->getLocStart();
3549 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3550 bool skip_semi;
3552 expr = resolve_nested(expr);
3553 ps = pet_stmt_from_pet_expr(line, label, n_stmt++, expr);
3554 scop = pet_scop_from_pet_stmt(ctx, ps);
3556 skip_semi = isa<Expr>(stmt);
3557 scop = update_scop_start_end(scop, stmt->getSourceRange(), skip_semi);
3558 return scop;
3561 /* Check if we can extract an affine expression from "expr".
3562 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3563 * We turn on autodetection so that we won't generate any warnings
3564 * and turn off nesting, so that we won't accept any non-affine constructs.
3566 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3568 isl_pw_aff *pwaff;
3569 int save_autodetect = options->autodetect;
3570 bool save_nesting = nesting_enabled;
3572 options->autodetect = 1;
3573 nesting_enabled = false;
3575 pwaff = extract_affine(expr);
3577 options->autodetect = save_autodetect;
3578 nesting_enabled = save_nesting;
3580 return pwaff;
3583 /* Check if we can extract an affine constraint from "expr".
3584 * Return the constraint as an isl_set if we can and NULL otherwise.
3585 * We turn on autodetection so that we won't generate any warnings
3586 * and turn off nesting, so that we won't accept any non-affine constructs.
3588 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3590 isl_pw_aff *cond;
3591 int save_autodetect = options->autodetect;
3592 bool save_nesting = nesting_enabled;
3594 options->autodetect = 1;
3595 nesting_enabled = false;
3597 cond = extract_condition(expr);
3599 options->autodetect = save_autodetect;
3600 nesting_enabled = save_nesting;
3602 return cond;
3605 /* Check whether "expr" is an affine constraint.
3607 bool PetScan::is_affine_condition(Expr *expr)
3609 isl_pw_aff *cond;
3611 cond = try_extract_affine_condition(expr);
3612 isl_pw_aff_free(cond);
3614 return cond != NULL;
3617 /* Check if we can extract a condition from "expr".
3618 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3619 * If allow_nested is set, then the condition may involve parameters
3620 * corresponding to nested accesses.
3621 * We turn on autodetection so that we won't generate any warnings.
3623 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3625 isl_pw_aff *cond;
3626 int save_autodetect = options->autodetect;
3627 bool save_nesting = nesting_enabled;
3629 options->autodetect = 1;
3630 nesting_enabled = allow_nested;
3631 cond = extract_condition(expr);
3633 options->autodetect = save_autodetect;
3634 nesting_enabled = save_nesting;
3636 return cond;
3639 /* If the top-level expression of "stmt" is an assignment, then
3640 * return that assignment as a BinaryOperator.
3641 * Otherwise return NULL.
3643 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3645 BinaryOperator *ass;
3647 if (!stmt)
3648 return NULL;
3649 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3650 return NULL;
3652 ass = cast<BinaryOperator>(stmt);
3653 if(ass->getOpcode() != BO_Assign)
3654 return NULL;
3656 return ass;
3659 /* Check if the given if statement is a conditional assignement
3660 * with a non-affine condition. If so, construct a pet_scop
3661 * corresponding to this conditional assignment. Otherwise return NULL.
3663 * In particular we check if "stmt" is of the form
3665 * if (condition)
3666 * a = f(...);
3667 * else
3668 * a = g(...);
3670 * where a is some array or scalar access.
3671 * The constructed pet_scop then corresponds to the expression
3673 * a = condition ? f(...) : g(...)
3675 * All access relations in f(...) are intersected with condition
3676 * while all access relation in g(...) are intersected with the complement.
3678 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3680 BinaryOperator *ass_then, *ass_else;
3681 isl_multi_pw_aff *write_then, *write_else;
3682 isl_set *cond, *comp;
3683 isl_multi_pw_aff *index;
3684 isl_pw_aff *pa;
3685 int equal;
3686 pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3687 bool save_nesting = nesting_enabled;
3689 if (!options->detect_conditional_assignment)
3690 return NULL;
3692 ass_then = top_assignment_or_null(stmt->getThen());
3693 ass_else = top_assignment_or_null(stmt->getElse());
3695 if (!ass_then || !ass_else)
3696 return NULL;
3698 if (is_affine_condition(stmt->getCond()))
3699 return NULL;
3701 write_then = extract_index(ass_then->getLHS());
3702 write_else = extract_index(ass_else->getLHS());
3704 equal = isl_multi_pw_aff_plain_is_equal(write_then, write_else);
3705 isl_multi_pw_aff_free(write_else);
3706 if (equal < 0 || !equal) {
3707 isl_multi_pw_aff_free(write_then);
3708 return NULL;
3711 nesting_enabled = allow_nested;
3712 pa = extract_condition(stmt->getCond());
3713 nesting_enabled = save_nesting;
3714 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3715 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3716 index = isl_multi_pw_aff_from_range(isl_multi_pw_aff_from_pw_aff(pa));
3718 pe_cond = pet_expr_from_index(index);
3720 pe_then = extract_expr(ass_then->getRHS());
3721 pe_then = pet_expr_restrict(pe_then, cond);
3722 pe_else = extract_expr(ass_else->getRHS());
3723 pe_else = pet_expr_restrict(pe_else, comp);
3725 pe = pet_expr_new_ternary(pe_cond, pe_then, pe_else);
3726 pe_write = pet_expr_from_index_and_depth(write_then,
3727 extract_depth(write_then));
3728 pe_write = pet_expr_access_set_write(pe_write, 1);
3729 pe_write = pet_expr_access_set_read(pe_write, 0);
3730 pe = pet_expr_new_binary(pet_op_assign, pe_write, pe);
3731 return extract(stmt, pe);
3734 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3735 * evaluating "cond" and writing the result to a virtual scalar,
3736 * as expressed by "index".
3738 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond, int stmt_nr,
3739 __isl_take isl_multi_pw_aff *index)
3741 pet_expr *expr, *write;
3742 struct pet_stmt *ps;
3743 SourceLocation loc = cond->getLocStart();
3744 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3746 write = pet_expr_from_index(index);
3747 write = pet_expr_access_set_write(write, 1);
3748 write = pet_expr_access_set_read(write, 0);
3749 expr = extract_expr(cond);
3750 expr = resolve_nested(expr);
3751 expr = pet_expr_new_binary(pet_op_assign, write, expr);
3752 ps = pet_stmt_from_pet_expr(line, NULL, stmt_nr, expr);
3753 return pet_scop_from_pet_stmt(ctx, ps);
3756 extern "C" {
3757 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr,
3758 void *user);
3761 /* Precompose the access relation and the index expression associated
3762 * to "expr" with the function pointed to by "user",
3763 * thereby embedding the access relation in the domain of this function.
3764 * The initial domain of the access relation and the index expression
3765 * is the zero-dimensional domain.
3767 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr, void *user)
3769 isl_multi_aff *ma = (isl_multi_aff *) user;
3771 return pet_expr_access_pullback_multi_aff(expr, isl_multi_aff_copy(ma));
3774 /* Precompose all access relations in "expr" with "ma", thereby
3775 * embedding them in the domain of "ma".
3777 static __isl_give pet_expr *embed(__isl_take pet_expr *expr,
3778 __isl_keep isl_multi_aff *ma)
3780 return pet_expr_map_access(expr, &embed_access, ma);
3783 /* For each nested access parameter in the domain of "stmt",
3784 * construct a corresponding pet_expr, place it before the original
3785 * elements in stmt->args and record its position in "param2pos".
3786 * n is the number of nested access parameters.
3788 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3789 std::map<int,int> &param2pos)
3791 int i;
3792 isl_space *space;
3793 int n_arg;
3794 pet_expr **args;
3796 n_arg = stmt->n_arg;
3797 args = isl_calloc_array(ctx, pet_expr *, n + n_arg);
3798 if (!args)
3799 goto error;
3801 space = isl_set_get_space(stmt->domain);
3802 n_arg = extract_nested(space, 0, args, param2pos);
3803 isl_space_free(space);
3805 if (n_arg < 0)
3806 goto error;
3808 for (i = 0; i < stmt->n_arg; ++i)
3809 args[n_arg + i] = stmt->args[i];
3810 free(stmt->args);
3811 stmt->args = args;
3812 stmt->n_arg += n_arg;
3814 return stmt;
3815 error:
3816 if (args) {
3817 for (i = 0; i < n; ++i)
3818 pet_expr_free(args[i]);
3819 free(args);
3821 pet_stmt_free(stmt);
3822 return NULL;
3825 /* Check whether any of the arguments i of "stmt" starting at position "n"
3826 * is equal to one of the first "n" arguments j.
3827 * If so, combine the constraints on arguments i and j and remove
3828 * argument i.
3830 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3832 int i, j;
3833 isl_map *map;
3835 if (!stmt)
3836 return NULL;
3837 if (n == 0)
3838 return stmt;
3839 if (n == stmt->n_arg)
3840 return stmt;
3842 map = isl_set_unwrap(stmt->domain);
3844 for (i = stmt->n_arg - 1; i >= n; --i) {
3845 for (j = 0; j < n; ++j)
3846 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3847 break;
3848 if (j >= n)
3849 continue;
3851 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3852 map = isl_map_project_out(map, isl_dim_out, i, 1);
3854 pet_expr_free(stmt->args[i]);
3855 for (j = i; j + 1 < stmt->n_arg; ++j)
3856 stmt->args[j] = stmt->args[j + 1];
3857 stmt->n_arg--;
3860 stmt->domain = isl_map_wrap(map);
3861 if (!stmt->domain)
3862 goto error;
3863 return stmt;
3864 error:
3865 pet_stmt_free(stmt);
3866 return NULL;
3869 /* Look for parameters in the iteration domain of "stmt" that
3870 * refer to nested accesses. In particular, these are
3871 * parameters with no name.
3873 * If there are any such parameters, then as many extra variables
3874 * (after identifying identical nested accesses) are inserted in the
3875 * range of the map wrapped inside the domain, before the original variables.
3876 * If the original domain is not a wrapped map, then a new wrapped
3877 * map is created with zero output dimensions.
3878 * The parameters are then equated to the corresponding output dimensions
3879 * and subsequently projected out, from the iteration domain,
3880 * the schedule and the access relations.
3881 * For each of the output dimensions, a corresponding argument
3882 * expression is inserted. Initially they are created with
3883 * a zero-dimensional domain, so they have to be embedded
3884 * in the current iteration domain.
3885 * param2pos maps the position of the parameter to the position
3886 * of the corresponding output dimension in the wrapped map.
3888 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3890 int n;
3891 int nparam;
3892 unsigned n_arg;
3893 isl_map *map;
3894 isl_space *space;
3895 isl_multi_aff *ma;
3896 std::map<int,int> param2pos;
3898 if (!stmt)
3899 return NULL;
3901 n = pet_nested_n_in_set(stmt->domain);
3902 if (n == 0)
3903 return stmt;
3905 n_arg = stmt->n_arg;
3906 stmt = extract_nested(stmt, n, param2pos);
3907 if (!stmt)
3908 return NULL;
3910 n = stmt->n_arg - n_arg;
3911 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3912 if (isl_set_is_wrapping(stmt->domain))
3913 map = isl_set_unwrap(stmt->domain);
3914 else
3915 map = isl_map_from_domain(stmt->domain);
3916 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3918 for (int i = nparam - 1; i >= 0; --i) {
3919 isl_id *id;
3921 if (!pet_nested_in_map(map, i))
3922 continue;
3924 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
3925 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3926 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3927 param2pos[i]);
3928 map = isl_map_project_out(map, isl_dim_param, i, 1);
3931 stmt->domain = isl_map_wrap(map);
3933 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
3934 space = isl_space_from_domain(isl_space_domain(space));
3935 ma = isl_multi_aff_zero(space);
3936 for (int pos = 0; pos < n; ++pos)
3937 stmt->args[pos] = embed(stmt->args[pos], ma);
3938 isl_multi_aff_free(ma);
3940 stmt = pet_stmt_remove_nested_parameters(stmt);
3941 stmt = remove_duplicate_arguments(stmt, n);
3943 return stmt;
3946 /* For each statement in "scop", move the parameters that correspond
3947 * to nested access into the ranges of the domains and create
3948 * corresponding argument expressions.
3950 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3952 if (!scop)
3953 return NULL;
3955 for (int i = 0; i < scop->n_stmt; ++i) {
3956 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3957 if (!scop->stmts[i])
3958 goto error;
3961 return scop;
3962 error:
3963 pet_scop_free(scop);
3964 return NULL;
3967 /* Given an access expression "expr", is the variable accessed by
3968 * "expr" assigned anywhere inside "scop"?
3970 static bool is_assigned(__isl_keep pet_expr *expr, pet_scop *scop)
3972 bool assigned = false;
3973 isl_id *id;
3975 id = pet_expr_access_get_id(expr);
3976 assigned = pet_scop_writes(scop, id);
3977 isl_id_free(id);
3979 return assigned;
3982 /* Are all nested access parameters in "pa" allowed given "scop".
3983 * In particular, is none of them written by anywhere inside "scop".
3985 * If "scop" has any skip conditions, then no nested access parameters
3986 * are allowed. In particular, if there is any nested access in a guard
3987 * for a piece of code containing a "continue", then we want to introduce
3988 * a separate statement for evaluating this guard so that we can express
3989 * that the result is false for all previous iterations.
3991 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3993 int nparam;
3995 if (!scop)
3996 return true;
3998 if (!pet_nested_any_in_pw_aff(pa))
3999 return true;
4001 if (pet_scop_has_skip(scop, pet_skip_now))
4002 return false;
4004 nparam = isl_pw_aff_dim(pa, isl_dim_param);
4005 for (int i = 0; i < nparam; ++i) {
4006 Expr *nested;
4007 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
4008 pet_expr *expr;
4009 bool allowed;
4011 if (!pet_nested_in_id(id)) {
4012 isl_id_free(id);
4013 continue;
4016 nested = (Expr *) isl_id_get_user(id);
4017 expr = extract_expr(nested);
4018 allowed = pet_expr_get_type(expr) == pet_expr_access &&
4019 !is_assigned(expr, scop);
4021 pet_expr_free(expr);
4022 isl_id_free(id);
4024 if (!allowed)
4025 return false;
4028 return true;
4031 /* Do we need to construct a skip condition of the given type
4032 * on an if statement, given that the if condition is non-affine?
4034 * pet_scop_filter_skip can only handle the case where the if condition
4035 * holds (the then branch) and the skip condition is universal.
4036 * In any other case, we need to construct a new skip condition.
4038 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
4039 bool have_else, enum pet_skip type)
4041 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
4042 return true;
4043 if (scop_then && pet_scop_has_skip(scop_then, type) &&
4044 !pet_scop_has_universal_skip(scop_then, type))
4045 return true;
4046 return false;
4049 /* Do we need to construct a skip condition of the given type
4050 * on an if statement, given that the if condition is affine?
4052 * There is no need to construct a new skip condition if all
4053 * the skip conditions are affine.
4055 static bool need_skip_aff(struct pet_scop *scop_then,
4056 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
4058 if (scop_then && pet_scop_has_var_skip(scop_then, type))
4059 return true;
4060 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
4061 return true;
4062 return false;
4065 /* Do we need to construct a skip condition of the given type
4066 * on an if statement?
4068 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
4069 bool have_else, enum pet_skip type, bool affine)
4071 if (affine)
4072 return need_skip_aff(scop_then, scop_else, have_else, type);
4073 else
4074 return need_skip(scop_then, scop_else, have_else, type);
4077 /* Construct an affine expression pet_expr that evaluates
4078 * to the constant "val".
4080 static __isl_give pet_expr *universally(isl_ctx *ctx, int val)
4082 isl_local_space *ls;
4083 isl_aff *aff;
4084 isl_multi_pw_aff *mpa;
4086 ls = isl_local_space_from_space(isl_space_set_alloc(ctx, 0, 0));
4087 aff = isl_aff_val_on_domain(ls, isl_val_int_from_si(ctx, val));
4088 mpa = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4090 return pet_expr_from_index(mpa);
4093 /* Construct an affine expression pet_expr that evaluates
4094 * to the constant 1.
4096 static __isl_give pet_expr *universally_true(isl_ctx *ctx)
4098 return universally(ctx, 1);
4101 /* Construct an affine expression pet_expr that evaluates
4102 * to the constant 0.
4104 static __isl_give pet_expr *universally_false(isl_ctx *ctx)
4106 return universally(ctx, 0);
4109 /* Given an index expression "test_index" for the if condition,
4110 * an index expression "skip_index" for the skip condition and
4111 * scops for the then and else branches, construct a scop for
4112 * computing "skip_index".
4114 * The computed scop contains a single statement that essentially does
4116 * skip_index = test_cond ? skip_cond_then : skip_cond_else
4118 * If the skip conditions of the then and/or else branch are not affine,
4119 * then they need to be filtered by test_index.
4120 * If they are missing, then this means the skip condition is false.
4122 * Since we are constructing a skip condition for the if statement,
4123 * the skip conditions on the then and else branches are removed.
4125 static struct pet_scop *extract_skip(PetScan *scan,
4126 __isl_take isl_multi_pw_aff *test_index,
4127 __isl_take isl_multi_pw_aff *skip_index,
4128 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
4129 enum pet_skip type)
4131 pet_expr *expr_then, *expr_else, *expr, *expr_skip;
4132 struct pet_stmt *stmt;
4133 struct pet_scop *scop;
4134 isl_ctx *ctx = scan->ctx;
4136 if (!scop_then)
4137 goto error;
4138 if (have_else && !scop_else)
4139 goto error;
4141 if (pet_scop_has_skip(scop_then, type)) {
4142 expr_then = pet_scop_get_skip_expr(scop_then, type);
4143 pet_scop_reset_skip(scop_then, type);
4144 if (!pet_expr_is_affine(expr_then))
4145 expr_then = pet_expr_filter(expr_then,
4146 isl_multi_pw_aff_copy(test_index), 1);
4147 } else
4148 expr_then = universally_false(ctx);
4150 if (have_else && pet_scop_has_skip(scop_else, type)) {
4151 expr_else = pet_scop_get_skip_expr(scop_else, type);
4152 pet_scop_reset_skip(scop_else, type);
4153 if (!pet_expr_is_affine(expr_else))
4154 expr_else = pet_expr_filter(expr_else,
4155 isl_multi_pw_aff_copy(test_index), 0);
4156 } else
4157 expr_else = universally_false(ctx);
4159 expr = pet_expr_from_index(test_index);
4160 expr = pet_expr_new_ternary(expr, expr_then, expr_else);
4161 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4162 expr_skip = pet_expr_access_set_write(expr_skip, 1);
4163 expr_skip = pet_expr_access_set_read(expr_skip, 0);
4164 expr = pet_expr_new_binary(pet_op_assign, expr_skip, expr);
4165 stmt = pet_stmt_from_pet_expr(-1, NULL, scan->n_stmt++, expr);
4167 scop = pet_scop_from_pet_stmt(ctx, stmt);
4168 scop = scop_add_array(scop, skip_index, scan->ast_context);
4169 isl_multi_pw_aff_free(skip_index);
4171 return scop;
4172 error:
4173 isl_multi_pw_aff_free(test_index);
4174 isl_multi_pw_aff_free(skip_index);
4175 return NULL;
4178 /* Is scop's skip_now condition equal to its skip_later condition?
4179 * In particular, this means that it either has no skip_now condition
4180 * or both a skip_now and a skip_later condition (that are equal to each other).
4182 static bool skip_equals_skip_later(struct pet_scop *scop)
4184 int has_skip_now, has_skip_later;
4185 int equal;
4186 isl_multi_pw_aff *skip_now, *skip_later;
4188 if (!scop)
4189 return false;
4190 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
4191 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
4192 if (has_skip_now != has_skip_later)
4193 return false;
4194 if (!has_skip_now)
4195 return true;
4197 skip_now = pet_scop_get_skip(scop, pet_skip_now);
4198 skip_later = pet_scop_get_skip(scop, pet_skip_later);
4199 equal = isl_multi_pw_aff_is_equal(skip_now, skip_later);
4200 isl_multi_pw_aff_free(skip_now);
4201 isl_multi_pw_aff_free(skip_later);
4203 return equal;
4206 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
4208 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
4210 pet_scop_reset_skip(scop1, pet_skip_later);
4211 pet_scop_reset_skip(scop2, pet_skip_later);
4214 /* Structure that handles the construction of skip conditions.
4216 * scop_then and scop_else represent the then and else branches
4217 * of the if statement
4219 * skip[type] is true if we need to construct a skip condition of that type
4220 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
4221 * are equal to each other
4222 * index[type] is an index expression from a zero-dimension domain
4223 * to the virtual array representing the skip condition
4224 * scop[type] is a scop for computing the skip condition
4226 struct pet_skip_info {
4227 isl_ctx *ctx;
4229 bool skip[2];
4230 bool equal;
4231 isl_multi_pw_aff *index[2];
4232 struct pet_scop *scop[2];
4234 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
4236 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
4239 /* Structure that handles the construction of skip conditions on if statements.
4241 * scop_then and scop_else represent the then and else branches
4242 * of the if statement
4244 struct pet_skip_info_if : public pet_skip_info {
4245 struct pet_scop *scop_then, *scop_else;
4246 bool have_else;
4248 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4249 struct pet_scop *scop_else, bool have_else, bool affine);
4250 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index,
4251 enum pet_skip type);
4252 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index);
4253 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
4254 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4255 int offset);
4256 struct pet_scop *add(struct pet_scop *scop, int offset);
4259 /* Initialize a pet_skip_info_if structure based on the then and else branches
4260 * and based on whether the if condition is affine or not.
4262 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4263 struct pet_scop *scop_else, bool have_else, bool affine) :
4264 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
4265 have_else(have_else)
4267 skip[pet_skip_now] =
4268 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
4269 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
4270 (!have_else || skip_equals_skip_later(scop_else));
4271 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4272 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
4275 /* If we need to construct a skip condition of the given type,
4276 * then do so now.
4278 * "mpa" represents the if condition.
4280 void pet_skip_info_if::extract(PetScan *scan,
4281 __isl_keep isl_multi_pw_aff *mpa, enum pet_skip type)
4283 isl_ctx *ctx;
4285 if (!skip[type])
4286 return;
4288 ctx = isl_multi_pw_aff_get_ctx(mpa);
4289 index[type] = create_test_index(ctx, scan->n_test++);
4290 scop[type] = extract_skip(scan, isl_multi_pw_aff_copy(mpa),
4291 isl_multi_pw_aff_copy(index[type]),
4292 scop_then, scop_else, have_else, type);
4295 /* Construct the required skip conditions, given the if condition "index".
4297 void pet_skip_info_if::extract(PetScan *scan,
4298 __isl_keep isl_multi_pw_aff *index)
4300 extract(scan, index, pet_skip_now);
4301 extract(scan, index, pet_skip_later);
4302 if (equal)
4303 drop_skip_later(scop_then, scop_else);
4306 /* Construct the required skip conditions, given the if condition "cond".
4308 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
4310 isl_multi_pw_aff *test;
4312 if (!skip[pet_skip_now] && !skip[pet_skip_later])
4313 return;
4315 test = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_copy(cond));
4316 test = isl_multi_pw_aff_from_range(test);
4317 extract(scan, test);
4318 isl_multi_pw_aff_free(test);
4321 /* Add the computed skip condition of the give type to "main" and
4322 * add the scop for computing the condition at the given offset.
4324 * If equal is set, then we only computed a skip condition for pet_skip_now,
4325 * but we also need to set it as main's pet_skip_later.
4327 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
4328 enum pet_skip type, int offset)
4330 if (!skip[type])
4331 return main;
4333 scop[type] = pet_scop_prefix(scop[type], offset);
4334 main = pet_scop_add_par(ctx, main, scop[type]);
4335 scop[type] = NULL;
4337 if (equal)
4338 main = pet_scop_set_skip(main, pet_skip_later,
4339 isl_multi_pw_aff_copy(index[type]));
4341 main = pet_scop_set_skip(main, type, index[type]);
4342 index[type] = NULL;
4344 return main;
4347 /* Add the computed skip conditions to "main" and
4348 * add the scops for computing the conditions at the given offset.
4350 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
4352 scop = add(scop, pet_skip_now, offset);
4353 scop = add(scop, pet_skip_later, offset);
4355 return scop;
4358 /* Construct a pet_scop for a non-affine if statement.
4360 * We create a separate statement that writes the result
4361 * of the non-affine condition to a virtual scalar.
4362 * A constraint requiring the value of this virtual scalar to be one
4363 * is added to the iteration domains of the then branch.
4364 * Similarly, a constraint requiring the value of this virtual scalar
4365 * to be zero is added to the iteration domains of the else branch, if any.
4366 * We adjust the schedules to ensure that the virtual scalar is written
4367 * before it is read.
4369 * If there are any breaks or continues in the then and/or else
4370 * branches, then we may have to compute a new skip condition.
4371 * This is handled using a pet_skip_info_if object.
4372 * On initialization, the object checks if skip conditions need
4373 * to be computed. If so, it does so in "extract" and adds them in "add".
4375 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
4376 struct pet_scop *scop_then, struct pet_scop *scop_else,
4377 bool have_else, int stmt_id)
4379 struct pet_scop *scop;
4380 isl_multi_pw_aff *test_index;
4381 int save_n_stmt = n_stmt;
4383 test_index = create_test_index(ctx, n_test++);
4384 n_stmt = stmt_id;
4385 scop = extract_non_affine_condition(cond, n_stmt++,
4386 isl_multi_pw_aff_copy(test_index));
4387 n_stmt = save_n_stmt;
4388 scop = scop_add_array(scop, test_index, ast_context);
4390 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
4391 skip.extract(this, test_index);
4393 scop = pet_scop_prefix(scop, 0);
4394 scop_then = pet_scop_prefix(scop_then, 1);
4395 scop_then = pet_scop_filter(scop_then,
4396 isl_multi_pw_aff_copy(test_index), 1);
4397 if (have_else) {
4398 scop_else = pet_scop_prefix(scop_else, 1);
4399 scop_else = pet_scop_filter(scop_else, test_index, 0);
4400 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
4401 } else
4402 isl_multi_pw_aff_free(test_index);
4404 scop = pet_scop_add_seq(ctx, scop, scop_then);
4406 scop = skip.add(scop, 2);
4408 return scop;
4411 /* Construct a pet_scop for an if statement.
4413 * If the condition fits the pattern of a conditional assignment,
4414 * then it is handled by extract_conditional_assignment.
4415 * Otherwise, we do the following.
4417 * If the condition is affine, then the condition is added
4418 * to the iteration domains of the then branch, while the
4419 * opposite of the condition in added to the iteration domains
4420 * of the else branch, if any.
4421 * We allow the condition to be dynamic, i.e., to refer to
4422 * scalars or array elements that may be written to outside
4423 * of the given if statement. These nested accesses are then represented
4424 * as output dimensions in the wrapping iteration domain.
4425 * If it is also written _inside_ the then or else branch, then
4426 * we treat the condition as non-affine.
4427 * As explained in extract_non_affine_if, this will introduce
4428 * an extra statement.
4429 * For aesthetic reasons, we want this statement to have a statement
4430 * number that is lower than those of the then and else branches.
4431 * In order to evaluate if we will need such a statement, however, we
4432 * first construct scops for the then and else branches.
4433 * We therefore reserve a statement number if we might have to
4434 * introduce such an extra statement.
4436 * If the condition is not affine, then the scop is created in
4437 * extract_non_affine_if.
4439 * If there are any breaks or continues in the then and/or else
4440 * branches, then we may have to compute a new skip condition.
4441 * This is handled using a pet_skip_info_if object.
4442 * On initialization, the object checks if skip conditions need
4443 * to be computed. If so, it does so in "extract" and adds them in "add".
4445 struct pet_scop *PetScan::extract(IfStmt *stmt)
4447 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4448 isl_pw_aff *cond;
4449 int stmt_id;
4450 isl_set *set;
4451 isl_set *valid;
4453 clear_assignments clear(assigned_value);
4454 clear.TraverseStmt(stmt->getThen());
4455 if (stmt->getElse())
4456 clear.TraverseStmt(stmt->getElse());
4458 scop = extract_conditional_assignment(stmt);
4459 if (scop)
4460 return scop;
4462 cond = try_extract_nested_condition(stmt->getCond());
4463 if (allow_nested && (!cond || pet_nested_any_in_pw_aff(cond)))
4464 stmt_id = n_stmt++;
4467 assigned_value_cache cache(assigned_value);
4468 scop_then = extract(stmt->getThen());
4471 if (stmt->getElse()) {
4472 assigned_value_cache cache(assigned_value);
4473 scop_else = extract(stmt->getElse());
4474 if (options->autodetect) {
4475 if (scop_then && !scop_else) {
4476 partial = true;
4477 isl_pw_aff_free(cond);
4478 return scop_then;
4480 if (!scop_then && scop_else) {
4481 partial = true;
4482 isl_pw_aff_free(cond);
4483 return scop_else;
4488 if (cond &&
4489 (!is_nested_allowed(cond, scop_then) ||
4490 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4491 isl_pw_aff_free(cond);
4492 cond = NULL;
4494 if (allow_nested && !cond)
4495 return extract_non_affine_if(stmt->getCond(), scop_then,
4496 scop_else, stmt->getElse(), stmt_id);
4498 if (!cond)
4499 cond = extract_condition(stmt->getCond());
4501 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4502 skip.extract(this, cond);
4504 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4505 set = isl_pw_aff_non_zero_set(cond);
4506 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4508 if (stmt->getElse()) {
4509 set = isl_set_subtract(isl_set_copy(valid), set);
4510 scop_else = pet_scop_restrict(scop_else, set);
4511 scop = pet_scop_add_par(ctx, scop, scop_else);
4512 } else
4513 isl_set_free(set);
4514 scop = resolve_nested(scop);
4515 scop = pet_scop_restrict_context(scop, valid);
4517 if (skip)
4518 scop = pet_scop_prefix(scop, 0);
4519 scop = skip.add(scop, 1);
4521 return scop;
4524 /* Try and construct a pet_scop for a label statement.
4525 * We currently only allow labels on expression statements.
4527 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4529 isl_id *label;
4530 Stmt *sub;
4532 sub = stmt->getSubStmt();
4533 if (!isa<Expr>(sub)) {
4534 unsupported(stmt);
4535 return NULL;
4538 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4540 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4543 /* Return a one-dimensional multi piecewise affine expression that is equal
4544 * to the constant 1 and is defined over a zero-dimensional domain.
4546 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
4548 isl_space *space;
4549 isl_local_space *ls;
4550 isl_aff *aff;
4552 space = isl_space_set_alloc(ctx, 0, 0);
4553 ls = isl_local_space_from_space(space);
4554 aff = isl_aff_zero_on_domain(ls);
4555 aff = isl_aff_set_constant_si(aff, 1);
4557 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4560 /* Construct a pet_scop for a continue statement.
4562 * We simply create an empty scop with a universal pet_skip_now
4563 * skip condition. This skip condition will then be taken into
4564 * account by the enclosing loop construct, possibly after
4565 * being incorporated into outer skip conditions.
4567 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4569 pet_scop *scop;
4571 scop = pet_scop_empty(ctx);
4572 if (!scop)
4573 return NULL;
4575 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
4577 return scop;
4580 /* Construct a pet_scop for a break statement.
4582 * We simply create an empty scop with both a universal pet_skip_now
4583 * skip condition and a universal pet_skip_later skip condition.
4584 * These skip conditions will then be taken into
4585 * account by the enclosing loop construct, possibly after
4586 * being incorporated into outer skip conditions.
4588 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4590 pet_scop *scop;
4591 isl_multi_pw_aff *skip;
4593 scop = pet_scop_empty(ctx);
4594 if (!scop)
4595 return NULL;
4597 skip = one_mpa(ctx);
4598 scop = pet_scop_set_skip(scop, pet_skip_now,
4599 isl_multi_pw_aff_copy(skip));
4600 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
4602 return scop;
4605 /* Try and construct a pet_scop corresponding to "stmt".
4607 * If "stmt" is a compound statement, then "skip_declarations"
4608 * indicates whether we should skip initial declarations in the
4609 * compound statement.
4611 * If the constructed pet_scop is not a (possibly) partial representation
4612 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4613 * In particular, if skip_declarations is set, then we may have skipped
4614 * declarations inside "stmt" and so the pet_scop may not represent
4615 * the entire "stmt".
4616 * Note that this function may be called with "stmt" referring to the entire
4617 * body of the function, including the outer braces. In such cases,
4618 * skip_declarations will be set and the braces will not be taken into
4619 * account in scop->start and scop->end.
4621 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
4623 struct pet_scop *scop;
4625 if (isa<Expr>(stmt))
4626 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4628 switch (stmt->getStmtClass()) {
4629 case Stmt::WhileStmtClass:
4630 scop = extract(cast<WhileStmt>(stmt));
4631 break;
4632 case Stmt::ForStmtClass:
4633 scop = extract_for(cast<ForStmt>(stmt));
4634 break;
4635 case Stmt::IfStmtClass:
4636 scop = extract(cast<IfStmt>(stmt));
4637 break;
4638 case Stmt::CompoundStmtClass:
4639 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
4640 break;
4641 case Stmt::LabelStmtClass:
4642 scop = extract(cast<LabelStmt>(stmt));
4643 break;
4644 case Stmt::ContinueStmtClass:
4645 scop = extract(cast<ContinueStmt>(stmt));
4646 break;
4647 case Stmt::BreakStmtClass:
4648 scop = extract(cast<BreakStmt>(stmt));
4649 break;
4650 case Stmt::DeclStmtClass:
4651 scop = extract(cast<DeclStmt>(stmt));
4652 break;
4653 default:
4654 unsupported(stmt);
4655 return NULL;
4658 if (partial || skip_declarations)
4659 return scop;
4661 scop = update_scop_start_end(scop, stmt->getSourceRange(), false);
4663 return scop;
4666 /* Do we need to construct a skip condition of the given type
4667 * on a sequence of statements?
4669 * There is no need to construct a new skip condition if only
4670 * only of the two statements has a skip condition or if both
4671 * of their skip conditions are affine.
4673 * In principle we also don't need a new continuation variable if
4674 * the continuation of scop2 is affine, but then we would need
4675 * to allow more complicated forms of continuations.
4677 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4678 enum pet_skip type)
4680 if (!scop1 || !pet_scop_has_skip(scop1, type))
4681 return false;
4682 if (!scop2 || !pet_scop_has_skip(scop2, type))
4683 return false;
4684 if (pet_scop_has_affine_skip(scop1, type) &&
4685 pet_scop_has_affine_skip(scop2, type))
4686 return false;
4687 return true;
4690 /* Construct a scop for computing the skip condition of the given type and
4691 * with index expression "skip_index" for a sequence of two scops "scop1"
4692 * and "scop2".
4694 * The computed scop contains a single statement that essentially does
4696 * skip_index = skip_cond_1 ? 1 : skip_cond_2
4698 * or, in other words, skip_cond1 || skip_cond2.
4699 * In this expression, skip_cond_2 is filtered to reflect that it is
4700 * only evaluated when skip_cond_1 is false.
4702 * The skip condition on scop1 is not removed because it still needs
4703 * to be applied to scop2 when these two scops are combined.
4705 static struct pet_scop *extract_skip_seq(PetScan *ps,
4706 __isl_take isl_multi_pw_aff *skip_index,
4707 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4709 pet_expr *expr1, *expr2, *expr, *expr_skip;
4710 struct pet_stmt *stmt;
4711 struct pet_scop *scop;
4712 isl_ctx *ctx = ps->ctx;
4714 if (!scop1 || !scop2)
4715 goto error;
4717 expr1 = pet_scop_get_skip_expr(scop1, type);
4718 expr2 = pet_scop_get_skip_expr(scop2, type);
4719 pet_scop_reset_skip(scop2, type);
4721 expr2 = pet_expr_filter(expr2, pet_expr_access_get_index(expr1), 0);
4723 expr = universally_true(ctx);
4724 expr = pet_expr_new_ternary(expr1, expr, expr2);
4725 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4726 expr_skip = pet_expr_access_set_write(expr_skip, 1);
4727 expr_skip = pet_expr_access_set_read(expr_skip, 0);
4728 expr = pet_expr_new_binary(pet_op_assign, expr_skip, expr);
4729 stmt = pet_stmt_from_pet_expr(-1, NULL, ps->n_stmt++, expr);
4731 scop = pet_scop_from_pet_stmt(ctx, stmt);
4732 scop = scop_add_array(scop, skip_index, ps->ast_context);
4733 isl_multi_pw_aff_free(skip_index);
4735 return scop;
4736 error:
4737 isl_multi_pw_aff_free(skip_index);
4738 return NULL;
4741 /* Structure that handles the construction of skip conditions
4742 * on sequences of statements.
4744 * scop1 and scop2 represent the two statements that are combined
4746 struct pet_skip_info_seq : public pet_skip_info {
4747 struct pet_scop *scop1, *scop2;
4749 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4750 struct pet_scop *scop2);
4751 void extract(PetScan *scan, enum pet_skip type);
4752 void extract(PetScan *scan);
4753 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4754 int offset);
4755 struct pet_scop *add(struct pet_scop *scop, int offset);
4758 /* Initialize a pet_skip_info_seq structure based on
4759 * on the two statements that are going to be combined.
4761 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4762 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
4764 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
4765 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
4766 skip_equals_skip_later(scop2);
4767 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4768 need_skip_seq(scop1, scop2, pet_skip_later);
4771 /* If we need to construct a skip condition of the given type,
4772 * then do so now.
4774 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
4776 if (!skip[type])
4777 return;
4779 index[type] = create_test_index(ctx, scan->n_test++);
4780 scop[type] = extract_skip_seq(scan, isl_multi_pw_aff_copy(index[type]),
4781 scop1, scop2, type);
4784 /* Construct the required skip conditions.
4786 void pet_skip_info_seq::extract(PetScan *scan)
4788 extract(scan, pet_skip_now);
4789 extract(scan, pet_skip_later);
4790 if (equal)
4791 drop_skip_later(scop1, scop2);
4794 /* Add the computed skip condition of the given type to "main" and
4795 * add the scop for computing the condition at the given offset (the statement
4796 * number). Within this offset, the condition is computed at position 1
4797 * to ensure that it is computed after the corresponding statement.
4799 * If equal is set, then we only computed a skip condition for pet_skip_now,
4800 * but we also need to set it as main's pet_skip_later.
4802 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
4803 enum pet_skip type, int offset)
4805 if (!skip[type])
4806 return main;
4808 scop[type] = pet_scop_prefix(scop[type], 1);
4809 scop[type] = pet_scop_prefix(scop[type], offset);
4810 main = pet_scop_add_par(ctx, main, scop[type]);
4811 scop[type] = NULL;
4813 if (equal)
4814 main = pet_scop_set_skip(main, pet_skip_later,
4815 isl_multi_pw_aff_copy(index[type]));
4817 main = pet_scop_set_skip(main, type, index[type]);
4818 index[type] = NULL;
4820 return main;
4823 /* Add the computed skip conditions to "main" and
4824 * add the scops for computing the conditions at the given offset.
4826 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
4828 scop = add(scop, pet_skip_now, offset);
4829 scop = add(scop, pet_skip_later, offset);
4831 return scop;
4834 /* Extract a clone of the kill statement in "scop".
4835 * "scop" is expected to have been created from a DeclStmt
4836 * and should have the kill as its first statement.
4838 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
4840 pet_expr *kill;
4841 struct pet_stmt *stmt;
4842 isl_multi_pw_aff *index;
4843 isl_map *access;
4844 pet_expr *arg;
4846 if (!scop)
4847 return NULL;
4848 if (scop->n_stmt < 1)
4849 isl_die(ctx, isl_error_internal,
4850 "expecting at least one statement", return NULL);
4851 stmt = scop->stmts[0];
4852 if (!pet_stmt_is_kill(stmt))
4853 isl_die(ctx, isl_error_internal,
4854 "expecting kill statement", return NULL);
4856 arg = pet_expr_get_arg(stmt->body, 0);
4857 index = pet_expr_access_get_index(arg);
4858 access = pet_expr_access_get_access(arg);
4859 pet_expr_free(arg);
4860 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
4861 access = isl_map_reset_tuple_id(access, isl_dim_in);
4862 kill = pet_expr_kill_from_access_and_index(access, index);
4863 return pet_stmt_from_pet_expr(stmt->line, NULL, n_stmt++, kill);
4866 /* Mark all arrays in "scop" as being exposed.
4868 static struct pet_scop *mark_exposed(struct pet_scop *scop)
4870 if (!scop)
4871 return NULL;
4872 for (int i = 0; i < scop->n_array; ++i)
4873 scop->arrays[i]->exposed = 1;
4874 return scop;
4877 /* Try and construct a pet_scop corresponding to (part of)
4878 * a sequence of statements.
4880 * "block" is set if the sequence respresents the children of
4881 * a compound statement.
4882 * "skip_declarations" is set if we should skip initial declarations
4883 * in the sequence of statements.
4885 * If there are any breaks or continues in the individual statements,
4886 * then we may have to compute a new skip condition.
4887 * This is handled using a pet_skip_info_seq object.
4888 * On initialization, the object checks if skip conditions need
4889 * to be computed. If so, it does so in "extract" and adds them in "add".
4891 * If "block" is set, then we need to insert kill statements at
4892 * the end of the block for any array that has been declared by
4893 * one of the statements in the sequence. Each of these declarations
4894 * results in the construction of a kill statement at the place
4895 * of the declaration, so we simply collect duplicates of
4896 * those kill statements and append these duplicates to the constructed scop.
4898 * If "block" is not set, then any array declared by one of the statements
4899 * in the sequence is marked as being exposed.
4901 * If autodetect is set, then we allow the extraction of only a subrange
4902 * of the sequence of statements. However, if there is at least one statement
4903 * for which we could not construct a scop and the final range contains
4904 * either no statements or at least one kill, then we discard the entire
4905 * range.
4907 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
4908 bool skip_declarations)
4910 pet_scop *scop;
4911 StmtIterator i;
4912 int j;
4913 bool partial_range = false;
4914 set<struct pet_stmt *> kills;
4915 set<struct pet_stmt *>::iterator it;
4917 scop = pet_scop_empty(ctx);
4918 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4919 Stmt *child = *i;
4920 struct pet_scop *scop_i;
4922 if (scop->n_stmt == 0 && skip_declarations &&
4923 child->getStmtClass() == Stmt::DeclStmtClass)
4924 continue;
4926 scop_i = extract(child);
4927 if (scop->n_stmt != 0 && partial) {
4928 pet_scop_free(scop_i);
4929 break;
4931 pet_skip_info_seq skip(ctx, scop, scop_i);
4932 skip.extract(this);
4933 if (skip)
4934 scop_i = pet_scop_prefix(scop_i, 0);
4935 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4936 if (block)
4937 kills.insert(extract_kill(scop_i));
4938 else
4939 scop_i = mark_exposed(scop_i);
4941 scop_i = pet_scop_prefix(scop_i, j);
4942 if (options->autodetect) {
4943 if (scop_i)
4944 scop = pet_scop_add_seq(ctx, scop, scop_i);
4945 else
4946 partial_range = true;
4947 if (scop->n_stmt != 0 && !scop_i)
4948 partial = true;
4949 } else {
4950 scop = pet_scop_add_seq(ctx, scop, scop_i);
4953 scop = skip.add(scop, j);
4955 if (partial || !scop)
4956 break;
4959 for (it = kills.begin(); it != kills.end(); ++it) {
4960 pet_scop *scop_j;
4961 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4962 scop_j = pet_scop_prefix(scop_j, j);
4963 scop = pet_scop_add_seq(ctx, scop, scop_j);
4966 if (scop && partial_range) {
4967 if (scop->n_stmt == 0 || kills.size() != 0) {
4968 pet_scop_free(scop);
4969 return NULL;
4971 partial = true;
4974 return scop;
4977 /* Check if the scop marked by the user is exactly this Stmt
4978 * or part of this Stmt.
4979 * If so, return a pet_scop corresponding to the marked region.
4980 * Otherwise, return NULL.
4982 struct pet_scop *PetScan::scan(Stmt *stmt)
4984 SourceManager &SM = PP.getSourceManager();
4985 unsigned start_off, end_off;
4987 start_off = getExpansionOffset(SM, stmt->getLocStart());
4988 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4990 if (start_off > loc.end)
4991 return NULL;
4992 if (end_off < loc.start)
4993 return NULL;
4994 if (start_off >= loc.start && end_off <= loc.end) {
4995 return extract(stmt);
4998 StmtIterator start;
4999 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
5000 Stmt *child = *start;
5001 if (!child)
5002 continue;
5003 start_off = getExpansionOffset(SM, child->getLocStart());
5004 end_off = getExpansionOffset(SM, child->getLocEnd());
5005 if (start_off < loc.start && end_off >= loc.end)
5006 return scan(child);
5007 if (start_off >= loc.start)
5008 break;
5011 StmtIterator end;
5012 for (end = start; end != stmt->child_end(); ++end) {
5013 Stmt *child = *end;
5014 start_off = SM.getFileOffset(child->getLocStart());
5015 if (start_off >= loc.end)
5016 break;
5019 return extract(StmtRange(start, end), false, false);
5022 /* Set the size of index "pos" of "array" to "size".
5023 * In particular, add a constraint of the form
5025 * i_pos < size
5027 * to array->extent and a constraint of the form
5029 * size >= 0
5031 * to array->context.
5033 static struct pet_array *update_size(struct pet_array *array, int pos,
5034 __isl_take isl_pw_aff *size)
5036 isl_set *valid;
5037 isl_set *univ;
5038 isl_set *bound;
5039 isl_space *dim;
5040 isl_aff *aff;
5041 isl_pw_aff *index;
5042 isl_id *id;
5044 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
5045 array->context = isl_set_intersect(array->context, valid);
5047 dim = isl_set_get_space(array->extent);
5048 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
5049 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
5050 univ = isl_set_universe(isl_aff_get_domain_space(aff));
5051 index = isl_pw_aff_alloc(univ, aff);
5053 size = isl_pw_aff_add_dims(size, isl_dim_in,
5054 isl_set_dim(array->extent, isl_dim_set));
5055 id = isl_set_get_tuple_id(array->extent);
5056 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
5057 bound = isl_pw_aff_lt_set(index, size);
5059 array->extent = isl_set_intersect(array->extent, bound);
5061 if (!array->context || !array->extent)
5062 goto error;
5064 return array;
5065 error:
5066 pet_array_free(array);
5067 return NULL;
5070 /* Figure out the size of the array at position "pos" and all
5071 * subsequent positions from "type" and update "array" accordingly.
5073 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
5074 const Type *type, int pos)
5076 const ArrayType *atype;
5077 isl_pw_aff *size;
5079 if (!array)
5080 return NULL;
5082 if (type->isPointerType()) {
5083 type = type->getPointeeType().getTypePtr();
5084 return set_upper_bounds(array, type, pos + 1);
5086 if (!type->isArrayType())
5087 return array;
5089 type = type->getCanonicalTypeInternal().getTypePtr();
5090 atype = cast<ArrayType>(type);
5092 if (type->isConstantArrayType()) {
5093 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
5094 size = extract_affine(ca->getSize());
5095 array = update_size(array, pos, size);
5096 } else if (type->isVariableArrayType()) {
5097 const VariableArrayType *vla = cast<VariableArrayType>(atype);
5098 size = extract_affine(vla->getSizeExpr());
5099 array = update_size(array, pos, size);
5102 type = atype->getElementType().getTypePtr();
5104 return set_upper_bounds(array, type, pos + 1);
5107 /* Is "T" the type of a variable length array with static size?
5109 static bool is_vla_with_static_size(QualType T)
5111 const VariableArrayType *vlatype;
5113 if (!T->isVariableArrayType())
5114 return false;
5115 vlatype = cast<VariableArrayType>(T);
5116 return vlatype->getSizeModifier() == VariableArrayType::Static;
5119 /* Return the type of "decl" as an array.
5121 * In particular, if "decl" is a parameter declaration that
5122 * is a variable length array with a static size, then
5123 * return the original type (i.e., the variable length array).
5124 * Otherwise, return the type of decl.
5126 static QualType get_array_type(ValueDecl *decl)
5128 ParmVarDecl *parm;
5129 QualType T;
5131 parm = dyn_cast<ParmVarDecl>(decl);
5132 if (!parm)
5133 return decl->getType();
5135 T = parm->getOriginalType();
5136 if (!is_vla_with_static_size(T))
5137 return decl->getType();
5138 return T;
5141 /* Does "decl" have definition that we can keep track of in a pet_type?
5143 static bool has_printable_definition(RecordDecl *decl)
5145 if (!decl->getDeclName())
5146 return false;
5147 return decl->getLexicalDeclContext() == decl->getDeclContext();
5150 /* Construct and return a pet_array corresponding to the variable "decl".
5151 * In particular, initialize array->extent to
5153 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
5155 * and then call set_upper_bounds to set the upper bounds on the indices
5156 * based on the type of the variable.
5158 * If the base type is that of a record with a top-level definition and
5159 * if "types" is not null, then the RecordDecl corresponding to the type
5160 * is added to "types".
5162 * If the base type is that of a record with no top-level definition,
5163 * then we replace it by "<subfield>".
5165 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
5166 lex_recorddecl_set *types)
5168 struct pet_array *array;
5169 QualType qt = get_array_type(decl);
5170 const Type *type = qt.getTypePtr();
5171 int depth = array_depth(type);
5172 QualType base = pet_clang_base_type(qt);
5173 string name;
5174 isl_id *id;
5175 isl_space *dim;
5177 array = isl_calloc_type(ctx, struct pet_array);
5178 if (!array)
5179 return NULL;
5181 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
5182 dim = isl_space_set_alloc(ctx, 0, depth);
5183 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
5185 array->extent = isl_set_nat_universe(dim);
5187 dim = isl_space_params_alloc(ctx, 0);
5188 array->context = isl_set_universe(dim);
5190 array = set_upper_bounds(array, type, 0);
5191 if (!array)
5192 return NULL;
5194 name = base.getAsString();
5196 if (types && base->isRecordType()) {
5197 RecordDecl *decl = pet_clang_record_decl(base);
5198 if (has_printable_definition(decl))
5199 types->insert(decl);
5200 else
5201 name = "<subfield>";
5204 array->element_type = strdup(name.c_str());
5205 array->element_is_record = base->isRecordType();
5206 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
5208 return array;
5211 /* Construct and return a pet_array corresponding to the sequence
5212 * of declarations "decls".
5213 * If the sequence contains a single declaration, then it corresponds
5214 * to a simple array access. Otherwise, it corresponds to a member access,
5215 * with the declaration for the substructure following that of the containing
5216 * structure in the sequence of declarations.
5217 * We start with the outermost substructure and then combine it with
5218 * information from the inner structures.
5220 * Additionally, keep track of all required types in "types".
5222 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
5223 vector<ValueDecl *> decls, lex_recorddecl_set *types)
5225 struct pet_array *array;
5226 vector<ValueDecl *>::iterator it;
5228 it = decls.begin();
5230 array = extract_array(ctx, *it, types);
5232 for (++it; it != decls.end(); ++it) {
5233 struct pet_array *parent;
5234 const char *base_name, *field_name;
5235 char *product_name;
5237 parent = array;
5238 array = extract_array(ctx, *it, types);
5239 if (!array)
5240 return pet_array_free(parent);
5242 base_name = isl_set_get_tuple_name(parent->extent);
5243 field_name = isl_set_get_tuple_name(array->extent);
5244 product_name = member_access_name(ctx, base_name, field_name);
5246 array->extent = isl_set_product(isl_set_copy(parent->extent),
5247 array->extent);
5248 if (product_name)
5249 array->extent = isl_set_set_tuple_name(array->extent,
5250 product_name);
5251 array->context = isl_set_intersect(array->context,
5252 isl_set_copy(parent->context));
5254 pet_array_free(parent);
5255 free(product_name);
5257 if (!array->extent || !array->context || !product_name)
5258 return pet_array_free(array);
5261 return array;
5264 /* Add a pet_type corresponding to "decl" to "scop, provided
5265 * it is a member of "types" and it has not been added before
5266 * (i.e., it is not a member of "types_done".
5268 * Since we want the user to be able to print the types
5269 * in the order in which they appear in the scop, we need to
5270 * make sure that types of fields in a structure appear before
5271 * that structure. We therefore call ourselves recursively
5272 * on the types of all record subfields.
5274 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
5275 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
5276 lex_recorddecl_set &types_done)
5278 string s;
5279 llvm::raw_string_ostream S(s);
5280 RecordDecl::field_iterator it;
5282 if (types.find(decl) == types.end())
5283 return scop;
5284 if (types_done.find(decl) != types_done.end())
5285 return scop;
5287 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
5288 RecordDecl *record;
5289 QualType type = it->getType();
5291 if (!type->isRecordType())
5292 continue;
5293 record = pet_clang_record_decl(type);
5294 scop = add_type(ctx, scop, record, PP, types, types_done);
5297 if (strlen(decl->getName().str().c_str()) == 0)
5298 return scop;
5300 decl->print(S, PrintingPolicy(PP.getLangOpts()));
5301 S.str();
5303 scop->types[scop->n_type] = pet_type_alloc(ctx,
5304 decl->getName().str().c_str(), s.c_str());
5305 if (!scop->types[scop->n_type])
5306 return pet_scop_free(scop);
5308 types_done.insert(decl);
5310 scop->n_type++;
5312 return scop;
5315 /* Construct a list of pet_arrays, one for each array (or scalar)
5316 * accessed inside "scop", add this list to "scop" and return the result.
5318 * The context of "scop" is updated with the intersection of
5319 * the contexts of all arrays, i.e., constraints on the parameters
5320 * that ensure that the arrays have a valid (non-negative) size.
5322 * If the any of the extracted arrays refers to a member access,
5323 * then also add the required types to "scop".
5325 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
5327 int i;
5328 array_desc_set arrays;
5329 array_desc_set::iterator it;
5330 lex_recorddecl_set types;
5331 lex_recorddecl_set types_done;
5332 lex_recorddecl_set::iterator types_it;
5333 int n_array;
5334 struct pet_array **scop_arrays;
5336 if (!scop)
5337 return NULL;
5339 pet_scop_collect_arrays(scop, arrays);
5340 if (arrays.size() == 0)
5341 return scop;
5343 n_array = scop->n_array;
5345 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
5346 n_array + arrays.size());
5347 if (!scop_arrays)
5348 goto error;
5349 scop->arrays = scop_arrays;
5351 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
5352 struct pet_array *array;
5353 array = extract_array(ctx, *it, &types);
5354 scop->arrays[n_array + i] = array;
5355 if (!scop->arrays[n_array + i])
5356 goto error;
5357 scop->n_array++;
5358 scop->context = isl_set_intersect(scop->context,
5359 isl_set_copy(array->context));
5360 if (!scop->context)
5361 goto error;
5364 if (types.size() == 0)
5365 return scop;
5367 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
5368 if (!scop->types)
5369 goto error;
5371 for (types_it = types.begin(); types_it != types.end(); ++types_it)
5372 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
5374 return scop;
5375 error:
5376 pet_scop_free(scop);
5377 return NULL;
5380 /* Bound all parameters in scop->context to the possible values
5381 * of the corresponding C variable.
5383 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
5385 int n;
5387 if (!scop)
5388 return NULL;
5390 n = isl_set_dim(scop->context, isl_dim_param);
5391 for (int i = 0; i < n; ++i) {
5392 isl_id *id;
5393 ValueDecl *decl;
5395 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
5396 if (pet_nested_in_id(id)) {
5397 isl_id_free(id);
5398 isl_die(isl_set_get_ctx(scop->context),
5399 isl_error_internal,
5400 "unresolved nested parameter", goto error);
5402 decl = (ValueDecl *) isl_id_get_user(id);
5403 isl_id_free(id);
5405 scop->context = set_parameter_bounds(scop->context, i, decl);
5407 if (!scop->context)
5408 goto error;
5411 return scop;
5412 error:
5413 pet_scop_free(scop);
5414 return NULL;
5417 /* Construct a pet_scop from the given function.
5419 * If the scop was delimited by scop and endscop pragmas, then we override
5420 * the file offsets by those derived from the pragmas.
5422 struct pet_scop *PetScan::scan(FunctionDecl *fd)
5424 pet_scop *scop;
5425 Stmt *stmt;
5427 stmt = fd->getBody();
5429 if (options->autodetect)
5430 scop = extract(stmt, true);
5431 else {
5432 scop = scan(stmt);
5433 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
5435 scop = pet_scop_detect_parameter_accesses(scop);
5436 scop = scan_arrays(scop);
5437 scop = add_parameter_bounds(scop);
5438 scop = pet_scop_gist(scop, value_bounds);
5440 return scop;