scan.cc: move UnaryOperatorKind2pet_op_type, BinaryOperatorKind2pet_op_type up
[pet.git] / scan.cc
blob6782a6f85c6f56975824cf0c5de0e40fdb3667fd
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 "clang.h"
51 #include "expr.h"
52 #include "nest.h"
53 #include "options.h"
54 #include "scan.h"
55 #include "scop.h"
56 #include "scop_plus.h"
58 #include "config.h"
60 using namespace std;
61 using namespace clang;
63 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
65 switch (kind) {
66 case UO_Minus:
67 return pet_op_minus;
68 case UO_Not:
69 return pet_op_not;
70 case UO_LNot:
71 return pet_op_lnot;
72 case UO_PostInc:
73 return pet_op_post_inc;
74 case UO_PostDec:
75 return pet_op_post_dec;
76 case UO_PreInc:
77 return pet_op_pre_inc;
78 case UO_PreDec:
79 return pet_op_pre_dec;
80 default:
81 return pet_op_last;
85 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
87 switch (kind) {
88 case BO_AddAssign:
89 return pet_op_add_assign;
90 case BO_SubAssign:
91 return pet_op_sub_assign;
92 case BO_MulAssign:
93 return pet_op_mul_assign;
94 case BO_DivAssign:
95 return pet_op_div_assign;
96 case BO_Assign:
97 return pet_op_assign;
98 case BO_Add:
99 return pet_op_add;
100 case BO_Sub:
101 return pet_op_sub;
102 case BO_Mul:
103 return pet_op_mul;
104 case BO_Div:
105 return pet_op_div;
106 case BO_Rem:
107 return pet_op_mod;
108 case BO_Shl:
109 return pet_op_shl;
110 case BO_Shr:
111 return pet_op_shr;
112 case BO_EQ:
113 return pet_op_eq;
114 case BO_NE:
115 return pet_op_ne;
116 case BO_LE:
117 return pet_op_le;
118 case BO_GE:
119 return pet_op_ge;
120 case BO_LT:
121 return pet_op_lt;
122 case BO_GT:
123 return pet_op_gt;
124 case BO_And:
125 return pet_op_and;
126 case BO_Xor:
127 return pet_op_xor;
128 case BO_Or:
129 return pet_op_or;
130 case BO_LAnd:
131 return pet_op_land;
132 case BO_LOr:
133 return pet_op_lor;
134 default:
135 return pet_op_last;
139 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
140 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
142 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
143 SourceLocation(), var, false, var->getInnerLocStart(),
144 var->getType(), VK_LValue);
146 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
147 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
149 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
150 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
151 VK_LValue);
153 #else
154 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
156 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
157 var, var->getInnerLocStart(), var->getType(), VK_LValue);
159 #endif
161 /* Check if the element type corresponding to the given array type
162 * has a const qualifier.
164 static bool const_base(QualType qt)
166 const Type *type = qt.getTypePtr();
168 if (type->isPointerType())
169 return const_base(type->getPointeeType());
170 if (type->isArrayType()) {
171 const ArrayType *atype;
172 type = type->getCanonicalTypeInternal().getTypePtr();
173 atype = cast<ArrayType>(type);
174 return const_base(atype->getElementType());
177 return qt.isConstQualified();
180 /* Mark "decl" as having an unknown value in "assigned_value".
182 * If no (known or unknown) value was assigned to "decl" before,
183 * then it may have been treated as a parameter before and may
184 * therefore appear in a value assigned to another variable.
185 * If so, this assignment needs to be turned into an unknown value too.
187 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
188 ValueDecl *decl)
190 map<ValueDecl *, isl_pw_aff *>::iterator it;
192 it = assigned_value.find(decl);
194 assigned_value[decl] = NULL;
196 if (it != assigned_value.end())
197 return;
199 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
200 isl_pw_aff *pa = it->second;
201 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
203 for (int i = 0; i < nparam; ++i) {
204 isl_id *id;
206 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
207 continue;
208 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
209 if (isl_id_get_user(id) == decl)
210 it->second = NULL;
211 isl_id_free(id);
216 /* Look for any assignments to scalar variables in part of the parse
217 * tree and set assigned_value to NULL for each of them.
218 * Also reset assigned_value if the address of a scalar variable
219 * is being taken. As an exception, if the address is passed to a function
220 * that is declared to receive a const pointer, then assigned_value is
221 * not reset.
223 * This ensures that we won't use any previously stored value
224 * in the current subtree and its parents.
226 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
227 map<ValueDecl *, isl_pw_aff *> &assigned_value;
228 set<UnaryOperator *> skip;
230 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
231 assigned_value(assigned_value) {}
233 /* Check for "address of" operators whose value is passed
234 * to a const pointer argument and add them to "skip", so that
235 * we can skip them in VisitUnaryOperator.
237 bool VisitCallExpr(CallExpr *expr) {
238 FunctionDecl *fd;
239 fd = expr->getDirectCallee();
240 if (!fd)
241 return true;
242 for (int i = 0; i < expr->getNumArgs(); ++i) {
243 Expr *arg = expr->getArg(i);
244 UnaryOperator *op;
245 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
246 ImplicitCastExpr *ice;
247 ice = cast<ImplicitCastExpr>(arg);
248 arg = ice->getSubExpr();
250 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
251 continue;
252 op = cast<UnaryOperator>(arg);
253 if (op->getOpcode() != UO_AddrOf)
254 continue;
255 if (const_base(fd->getParamDecl(i)->getType()))
256 skip.insert(op);
258 return true;
261 bool VisitUnaryOperator(UnaryOperator *expr) {
262 Expr *arg;
263 DeclRefExpr *ref;
264 ValueDecl *decl;
266 switch (expr->getOpcode()) {
267 case UO_AddrOf:
268 case UO_PostInc:
269 case UO_PostDec:
270 case UO_PreInc:
271 case UO_PreDec:
272 break;
273 default:
274 return true;
276 if (skip.find(expr) != skip.end())
277 return true;
279 arg = expr->getSubExpr();
280 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
281 return true;
282 ref = cast<DeclRefExpr>(arg);
283 decl = ref->getDecl();
284 clear_assignment(assigned_value, decl);
285 return true;
288 bool VisitBinaryOperator(BinaryOperator *expr) {
289 Expr *lhs;
290 DeclRefExpr *ref;
291 ValueDecl *decl;
293 if (!expr->isAssignmentOp())
294 return true;
295 lhs = expr->getLHS();
296 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
297 return true;
298 ref = cast<DeclRefExpr>(lhs);
299 decl = ref->getDecl();
300 clear_assignment(assigned_value, decl);
301 return true;
305 /* Keep a copy of the currently assigned values.
307 * Any variable that is assigned a value inside the current scope
308 * is removed again when we leave the scope (either because it wasn't
309 * stored in the cache or because it has a different value in the cache).
311 struct assigned_value_cache {
312 map<ValueDecl *, isl_pw_aff *> &assigned_value;
313 map<ValueDecl *, isl_pw_aff *> cache;
315 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
316 assigned_value(assigned_value), cache(assigned_value) {}
317 ~assigned_value_cache() {
318 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
319 for (it = assigned_value.begin(); it != assigned_value.end();
320 ++it) {
321 if (!it->second ||
322 (cache.find(it->first) != cache.end() &&
323 cache[it->first] != it->second))
324 cache[it->first] = NULL;
326 assigned_value = cache;
330 /* Insert an expression into the collection of expressions,
331 * provided it is not already in there.
332 * The isl_pw_affs are freed in the destructor.
334 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
336 std::set<isl_pw_aff *>::iterator it;
338 if (expressions.find(expr) == expressions.end())
339 expressions.insert(expr);
340 else
341 isl_pw_aff_free(expr);
344 PetScan::~PetScan()
346 std::set<isl_pw_aff *>::iterator it;
348 for (it = expressions.begin(); it != expressions.end(); ++it)
349 isl_pw_aff_free(*it);
351 isl_union_map_free(value_bounds);
354 /* Report a diagnostic, unless autodetect is set.
356 void PetScan::report(Stmt *stmt, unsigned id)
358 if (options->autodetect)
359 return;
361 SourceLocation loc = stmt->getLocStart();
362 DiagnosticsEngine &diag = PP.getDiagnostics();
363 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
366 /* Called if we found something we (currently) cannot handle.
367 * We'll provide more informative warnings later.
369 * We only actually complain if autodetect is false.
371 void PetScan::unsupported(Stmt *stmt)
373 DiagnosticsEngine &diag = PP.getDiagnostics();
374 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
375 "unsupported");
376 report(stmt, id);
379 /* Report a missing prototype, unless autodetect is set.
381 void PetScan::report_prototype_required(Stmt *stmt)
383 DiagnosticsEngine &diag = PP.getDiagnostics();
384 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
385 "prototype required");
386 report(stmt, id);
389 /* Report a missing increment, unless autodetect is set.
391 void PetScan::report_missing_increment(Stmt *stmt)
393 DiagnosticsEngine &diag = PP.getDiagnostics();
394 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
395 "missing increment");
396 report(stmt, id);
399 /* Extract an integer from "expr".
401 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
403 const Type *type = expr->getType().getTypePtr();
404 int is_signed = type->hasSignedIntegerRepresentation();
405 llvm::APInt val = expr->getValue();
406 int is_negative = is_signed && val.isNegative();
407 isl_val *v;
409 if (is_negative)
410 val = -val;
412 v = extract_unsigned(ctx, val);
414 if (is_negative)
415 v = isl_val_neg(v);
416 return v;
419 /* Extract an integer from "val", which is assumed to be non-negative.
421 __isl_give isl_val *PetScan::extract_unsigned(isl_ctx *ctx,
422 const llvm::APInt &val)
424 unsigned n;
425 const uint64_t *data;
427 data = val.getRawData();
428 n = val.getNumWords();
429 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
432 /* Extract an integer from "expr".
433 * Return NULL if "expr" does not (obviously) represent an integer.
435 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
437 return extract_int(expr->getSubExpr());
440 /* Extract an integer from "expr".
441 * Return NULL if "expr" does not (obviously) represent an integer.
443 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
445 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
446 return extract_int(ctx, cast<IntegerLiteral>(expr));
447 if (expr->getStmtClass() == Stmt::ParenExprClass)
448 return extract_int(cast<ParenExpr>(expr));
450 unsupported(expr);
451 return NULL;
454 /* Extract an affine expression from the IntegerLiteral "expr".
456 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
458 isl_space *dim = isl_space_params_alloc(ctx, 0);
459 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
460 isl_aff *aff = isl_aff_zero_on_domain(ls);
461 isl_set *dom = isl_set_universe(dim);
462 isl_val *v;
464 v = extract_int(expr);
465 aff = isl_aff_add_constant_val(aff, v);
467 return isl_pw_aff_alloc(dom, aff);
470 /* Extract an affine expression from the APInt "val", which is assumed
471 * to be non-negative.
473 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
475 isl_space *dim = isl_space_params_alloc(ctx, 0);
476 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
477 isl_aff *aff = isl_aff_zero_on_domain(ls);
478 isl_set *dom = isl_set_universe(dim);
479 isl_val *v;
481 v = extract_unsigned(ctx, val);
482 aff = isl_aff_add_constant_val(aff, v);
484 return isl_pw_aff_alloc(dom, aff);
487 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
489 return extract_affine(expr->getSubExpr());
492 static unsigned get_type_size(ValueDecl *decl)
494 return decl->getASTContext().getIntWidth(decl->getType());
497 /* Bound parameter "pos" of "set" to the possible values of "decl".
499 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
500 unsigned pos, ValueDecl *decl)
502 unsigned width;
503 isl_ctx *ctx;
504 isl_val *bound;
506 ctx = isl_set_get_ctx(set);
507 width = get_type_size(decl);
508 if (decl->getType()->isUnsignedIntegerType()) {
509 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
510 bound = isl_val_int_from_ui(ctx, width);
511 bound = isl_val_2exp(bound);
512 bound = isl_val_sub_ui(bound, 1);
513 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
514 } else {
515 bound = isl_val_int_from_ui(ctx, width - 1);
516 bound = isl_val_2exp(bound);
517 bound = isl_val_sub_ui(bound, 1);
518 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
519 isl_val_copy(bound));
520 bound = isl_val_neg(bound);
521 bound = isl_val_sub_ui(bound, 1);
522 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
525 return set;
528 /* Extract an affine expression from the DeclRefExpr "expr".
530 * If the variable has been assigned a value, then we check whether
531 * we know what (affine) value was assigned.
532 * If so, we return this value. Otherwise we convert "expr"
533 * to an extra parameter (provided nesting_enabled is set).
535 * Otherwise, we simply return an expression that is equal
536 * to a parameter corresponding to the referenced variable.
538 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
540 ValueDecl *decl = expr->getDecl();
541 const Type *type = decl->getType().getTypePtr();
542 isl_id *id;
543 isl_space *dim;
544 isl_aff *aff;
545 isl_set *dom;
547 if (!type->isIntegerType()) {
548 unsupported(expr);
549 return NULL;
552 if (assigned_value.find(decl) != assigned_value.end()) {
553 if (assigned_value[decl])
554 return isl_pw_aff_copy(assigned_value[decl]);
555 else
556 return nested_access(expr);
559 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
560 dim = isl_space_params_alloc(ctx, 1);
562 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
564 dom = isl_set_universe(isl_space_copy(dim));
565 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
566 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
568 return isl_pw_aff_alloc(dom, aff);
571 /* Extract an affine expression from an integer division operation.
572 * In particular, if "expr" is lhs/rhs, then return
574 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
576 * The second argument (rhs) is required to be a (positive) integer constant.
578 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
580 int is_cst;
581 isl_pw_aff *rhs, *lhs;
583 rhs = extract_affine(expr->getRHS());
584 is_cst = isl_pw_aff_is_cst(rhs);
585 if (is_cst < 0 || !is_cst) {
586 isl_pw_aff_free(rhs);
587 if (!is_cst)
588 unsupported(expr);
589 return NULL;
592 lhs = extract_affine(expr->getLHS());
594 return isl_pw_aff_tdiv_q(lhs, rhs);
597 /* Extract an affine expression from a modulo operation.
598 * In particular, if "expr" is lhs/rhs, then return
600 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
602 * The second argument (rhs) is required to be a (positive) integer constant.
604 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
606 int is_cst;
607 isl_pw_aff *rhs, *lhs;
609 rhs = extract_affine(expr->getRHS());
610 is_cst = isl_pw_aff_is_cst(rhs);
611 if (is_cst < 0 || !is_cst) {
612 isl_pw_aff_free(rhs);
613 if (!is_cst)
614 unsupported(expr);
615 return NULL;
618 lhs = extract_affine(expr->getLHS());
620 return isl_pw_aff_tdiv_r(lhs, rhs);
623 /* Extract an affine expression from a multiplication operation.
624 * This is only allowed if at least one of the two arguments
625 * is a (piecewise) constant.
627 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
629 isl_pw_aff *lhs;
630 isl_pw_aff *rhs;
632 lhs = extract_affine(expr->getLHS());
633 rhs = extract_affine(expr->getRHS());
635 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
636 isl_pw_aff_free(lhs);
637 isl_pw_aff_free(rhs);
638 unsupported(expr);
639 return NULL;
642 return isl_pw_aff_mul(lhs, rhs);
645 /* Extract an affine expression from an addition or subtraction operation.
647 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
649 isl_pw_aff *lhs;
650 isl_pw_aff *rhs;
652 lhs = extract_affine(expr->getLHS());
653 rhs = extract_affine(expr->getRHS());
655 switch (expr->getOpcode()) {
656 case BO_Add:
657 return isl_pw_aff_add(lhs, rhs);
658 case BO_Sub:
659 return isl_pw_aff_sub(lhs, rhs);
660 default:
661 isl_pw_aff_free(lhs);
662 isl_pw_aff_free(rhs);
663 return NULL;
668 /* Compute
670 * pwaff mod 2^width
672 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
673 unsigned width)
675 isl_ctx *ctx;
676 isl_val *mod;
678 ctx = isl_pw_aff_get_ctx(pwaff);
679 mod = isl_val_int_from_ui(ctx, width);
680 mod = isl_val_2exp(mod);
682 pwaff = isl_pw_aff_mod_val(pwaff, mod);
684 return pwaff;
687 /* Limit the domain of "pwaff" to those elements where the function
688 * value satisfies
690 * 2^{width-1} <= pwaff < 2^{width-1}
692 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
693 unsigned width)
695 isl_ctx *ctx;
696 isl_val *v;
697 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
698 isl_local_space *ls = isl_local_space_from_space(space);
699 isl_aff *bound;
700 isl_set *dom;
701 isl_pw_aff *b;
703 ctx = isl_pw_aff_get_ctx(pwaff);
704 v = isl_val_int_from_ui(ctx, width - 1);
705 v = isl_val_2exp(v);
707 bound = isl_aff_zero_on_domain(ls);
708 bound = isl_aff_add_constant_val(bound, v);
709 b = isl_pw_aff_from_aff(bound);
711 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
712 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
714 b = isl_pw_aff_neg(b);
715 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
716 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
718 return pwaff;
721 /* Handle potential overflows on signed computations.
723 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
724 * the we adjust the domain of "pa" to avoid overflows.
726 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
727 unsigned width)
729 if (options->signed_overflow == PET_OVERFLOW_AVOID)
730 pa = avoid_overflow(pa, width);
732 return pa;
735 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
737 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
738 __isl_take isl_set *dom)
740 isl_pw_aff *pa;
741 pa = isl_set_indicator_function(set);
742 pa = isl_pw_aff_intersect_domain(pa, isl_set_coalesce(dom));
743 return pa;
746 /* Extract an affine expression from some binary operations.
747 * If the result of the expression is unsigned, then we wrap it
748 * based on the size of the type. Otherwise, we ensure that
749 * no overflow occurs.
751 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
753 isl_pw_aff *res;
754 unsigned width;
756 switch (expr->getOpcode()) {
757 case BO_Add:
758 case BO_Sub:
759 res = extract_affine_add(expr);
760 break;
761 case BO_Div:
762 res = extract_affine_div(expr);
763 break;
764 case BO_Rem:
765 res = extract_affine_mod(expr);
766 break;
767 case BO_Mul:
768 res = extract_affine_mul(expr);
769 break;
770 case BO_LT:
771 case BO_LE:
772 case BO_GT:
773 case BO_GE:
774 case BO_EQ:
775 case BO_NE:
776 case BO_LAnd:
777 case BO_LOr:
778 return extract_condition(expr);
779 default:
780 unsupported(expr);
781 return NULL;
784 width = ast_context.getIntWidth(expr->getType());
785 if (expr->getType()->isUnsignedIntegerType())
786 res = wrap(res, width);
787 else
788 res = signed_overflow(res, width);
790 return res;
793 /* Extract an affine expression from a negation operation.
795 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
797 if (expr->getOpcode() == UO_Minus)
798 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
799 if (expr->getOpcode() == UO_LNot)
800 return extract_condition(expr);
802 unsupported(expr);
803 return NULL;
806 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
808 return extract_affine(expr->getSubExpr());
811 /* Extract an affine expression from some special function calls.
812 * In particular, we handle "min", "max", "ceild", "floord",
813 * "intMod", "intFloor" and "intCeil".
814 * In case of the latter five, the second argument needs to be
815 * a (positive) integer constant.
817 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
819 FunctionDecl *fd;
820 string name;
821 isl_pw_aff *aff1, *aff2;
823 fd = expr->getDirectCallee();
824 if (!fd) {
825 unsupported(expr);
826 return NULL;
829 name = fd->getDeclName().getAsString();
830 if (!(expr->getNumArgs() == 2 && name == "min") &&
831 !(expr->getNumArgs() == 2 && name == "max") &&
832 !(expr->getNumArgs() == 2 && name == "intMod") &&
833 !(expr->getNumArgs() == 2 && name == "intFloor") &&
834 !(expr->getNumArgs() == 2 && name == "intCeil") &&
835 !(expr->getNumArgs() == 2 && name == "floord") &&
836 !(expr->getNumArgs() == 2 && name == "ceild")) {
837 unsupported(expr);
838 return NULL;
841 if (name == "min" || name == "max") {
842 aff1 = extract_affine(expr->getArg(0));
843 aff2 = extract_affine(expr->getArg(1));
845 if (name == "min")
846 aff1 = isl_pw_aff_min(aff1, aff2);
847 else
848 aff1 = isl_pw_aff_max(aff1, aff2);
849 } else if (name == "intMod") {
850 isl_val *v;
851 Expr *arg2 = expr->getArg(1);
853 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
854 unsupported(expr);
855 return NULL;
857 aff1 = extract_affine(expr->getArg(0));
858 v = extract_int(cast<IntegerLiteral>(arg2));
859 aff1 = isl_pw_aff_mod_val(aff1, v);
860 } else if (name == "floord" || name == "ceild" ||
861 name == "intFloor" || name == "intCeil") {
862 isl_val *v;
863 Expr *arg2 = expr->getArg(1);
865 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
866 unsupported(expr);
867 return NULL;
869 aff1 = extract_affine(expr->getArg(0));
870 v = extract_int(cast<IntegerLiteral>(arg2));
871 aff1 = isl_pw_aff_scale_down_val(aff1, v);
872 if (name == "floord" || name == "intFloor")
873 aff1 = isl_pw_aff_floor(aff1);
874 else
875 aff1 = isl_pw_aff_ceil(aff1);
876 } else {
877 unsupported(expr);
878 return NULL;
881 return aff1;
884 /* This method is called when we come across an access that is
885 * nested in what is supposed to be an affine expression.
886 * If nesting is allowed, we return a new parameter that corresponds
887 * to this nested access. Otherwise, we simply complain.
889 * Note that we currently don't allow nested accesses themselves
890 * to contain any nested accesses, so we check if we can extract
891 * the access without any nesting and complain if we can't.
893 * The new parameter is resolved in resolve_nested.
895 isl_pw_aff *PetScan::nested_access(Expr *expr)
897 isl_id *id;
898 isl_space *dim;
899 isl_aff *aff;
900 isl_set *dom;
901 isl_multi_pw_aff *index;
903 if (!nesting_enabled) {
904 unsupported(expr);
905 return NULL;
908 allow_nested = false;
909 index = extract_index(expr);
910 allow_nested = true;
911 if (!index) {
912 unsupported(expr);
913 return NULL;
915 isl_multi_pw_aff_free(index);
917 id = pet_nested_clang_expr(ctx, expr);
918 dim = isl_space_params_alloc(ctx, 1);
920 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
922 dom = isl_set_universe(isl_space_copy(dim));
923 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
924 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
926 return isl_pw_aff_alloc(dom, aff);
929 /* Affine expressions are not supposed to contain array accesses,
930 * but if nesting is allowed, we return a parameter corresponding
931 * to the array access.
933 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
935 return nested_access(expr);
938 /* Affine expressions are not supposed to contain member accesses,
939 * but if nesting is allowed, we return a parameter corresponding
940 * to the member access.
942 __isl_give isl_pw_aff *PetScan::extract_affine(MemberExpr *expr)
944 return nested_access(expr);
947 /* Extract an affine expression from a conditional operation.
949 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
951 isl_pw_aff *cond, *lhs, *rhs;
953 cond = extract_condition(expr->getCond());
954 lhs = extract_affine(expr->getTrueExpr());
955 rhs = extract_affine(expr->getFalseExpr());
957 return isl_pw_aff_cond(cond, lhs, rhs);
960 /* Extract an affine expression, if possible, from "expr".
961 * Otherwise return NULL.
963 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
965 switch (expr->getStmtClass()) {
966 case Stmt::ImplicitCastExprClass:
967 return extract_affine(cast<ImplicitCastExpr>(expr));
968 case Stmt::IntegerLiteralClass:
969 return extract_affine(cast<IntegerLiteral>(expr));
970 case Stmt::DeclRefExprClass:
971 return extract_affine(cast<DeclRefExpr>(expr));
972 case Stmt::BinaryOperatorClass:
973 return extract_affine(cast<BinaryOperator>(expr));
974 case Stmt::UnaryOperatorClass:
975 return extract_affine(cast<UnaryOperator>(expr));
976 case Stmt::ParenExprClass:
977 return extract_affine(cast<ParenExpr>(expr));
978 case Stmt::CallExprClass:
979 return extract_affine(cast<CallExpr>(expr));
980 case Stmt::ArraySubscriptExprClass:
981 return extract_affine(cast<ArraySubscriptExpr>(expr));
982 case Stmt::MemberExprClass:
983 return extract_affine(cast<MemberExpr>(expr));
984 case Stmt::ConditionalOperatorClass:
985 return extract_affine(cast<ConditionalOperator>(expr));
986 default:
987 unsupported(expr);
989 return NULL;
992 __isl_give isl_multi_pw_aff *PetScan::extract_index(ImplicitCastExpr *expr)
994 return extract_index(expr->getSubExpr());
997 /* Return the depth of an array of the given type.
999 static int array_depth(const Type *type)
1001 if (type->isPointerType())
1002 return 1 + array_depth(type->getPointeeType().getTypePtr());
1003 if (type->isArrayType()) {
1004 const ArrayType *atype;
1005 type = type->getCanonicalTypeInternal().getTypePtr();
1006 atype = cast<ArrayType>(type);
1007 return 1 + array_depth(atype->getElementType().getTypePtr());
1009 return 0;
1012 /* Return the depth of the array accessed by the index expression "index".
1013 * If "index" is an affine expression, i.e., if it does not access
1014 * any array, then return 1.
1015 * If "index" represent a member access, i.e., if its range is a wrapped
1016 * relation, then return the sum of the depth of the array of structures
1017 * and that of the member inside the structure.
1019 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
1021 isl_id *id;
1022 ValueDecl *decl;
1024 if (!index)
1025 return -1;
1027 if (isl_multi_pw_aff_range_is_wrapping(index)) {
1028 int domain_depth, range_depth;
1029 isl_multi_pw_aff *domain, *range;
1031 domain = isl_multi_pw_aff_copy(index);
1032 domain = isl_multi_pw_aff_range_factor_domain(domain);
1033 domain_depth = extract_depth(domain);
1034 isl_multi_pw_aff_free(domain);
1035 range = isl_multi_pw_aff_copy(index);
1036 range = isl_multi_pw_aff_range_factor_range(range);
1037 range_depth = extract_depth(range);
1038 isl_multi_pw_aff_free(range);
1040 return domain_depth + range_depth;
1043 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
1044 return 1;
1046 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
1047 if (!id)
1048 return -1;
1049 decl = (ValueDecl *) isl_id_get_user(id);
1050 isl_id_free(id);
1052 return array_depth(decl->getType().getTypePtr());
1055 /* Extract an index expression from a reference to a variable.
1056 * If the variable has name "A", then the returned index expression
1057 * is of the form
1059 * { [] -> A[] }
1061 __isl_give isl_multi_pw_aff *PetScan::extract_index(DeclRefExpr *expr)
1063 return extract_index(expr->getDecl());
1066 /* Extract an index expression from a variable.
1067 * If the variable has name "A", then the returned index expression
1068 * is of the form
1070 * { [] -> A[] }
1072 __isl_give isl_multi_pw_aff *PetScan::extract_index(ValueDecl *decl)
1074 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
1075 isl_space *space = isl_space_alloc(ctx, 0, 0, 0);
1077 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1079 return isl_multi_pw_aff_zero(space);
1082 /* Extract an index expression from an integer contant.
1083 * If the value of the constant is "v", then the returned access relation
1084 * is
1086 * { [] -> [v] }
1088 __isl_give isl_multi_pw_aff *PetScan::extract_index(IntegerLiteral *expr)
1090 isl_multi_pw_aff *mpa;
1092 mpa = isl_multi_pw_aff_from_pw_aff(extract_affine(expr));
1093 mpa = isl_multi_pw_aff_from_range(mpa);
1094 return mpa;
1097 /* Try and extract an index expression from the given Expr.
1098 * Return NULL if it doesn't work out.
1100 __isl_give isl_multi_pw_aff *PetScan::extract_index(Expr *expr)
1102 switch (expr->getStmtClass()) {
1103 case Stmt::ImplicitCastExprClass:
1104 return extract_index(cast<ImplicitCastExpr>(expr));
1105 case Stmt::DeclRefExprClass:
1106 return extract_index(cast<DeclRefExpr>(expr));
1107 case Stmt::ArraySubscriptExprClass:
1108 return extract_index(cast<ArraySubscriptExpr>(expr));
1109 case Stmt::IntegerLiteralClass:
1110 return extract_index(cast<IntegerLiteral>(expr));
1111 case Stmt::MemberExprClass:
1112 return extract_index(cast<MemberExpr>(expr));
1113 default:
1114 unsupported(expr);
1116 return NULL;
1119 /* Given a partial index expression "base" and an extra index "index",
1120 * append the extra index to "base" and return the result.
1121 * Additionally, add the constraints that the extra index is non-negative.
1122 * If "index" represent a member access, i.e., if its range is a wrapped
1123 * relation, then we recursively extend the range of this nested relation.
1125 static __isl_give isl_multi_pw_aff *subscript(__isl_take isl_multi_pw_aff *base,
1126 __isl_take isl_pw_aff *index)
1128 isl_id *id;
1129 isl_set *domain;
1130 isl_multi_pw_aff *access;
1131 int member_access;
1133 member_access = isl_multi_pw_aff_range_is_wrapping(base);
1134 if (member_access < 0)
1135 goto error;
1136 if (member_access) {
1137 isl_multi_pw_aff *domain, *range;
1138 isl_id *id;
1140 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_out);
1141 domain = isl_multi_pw_aff_copy(base);
1142 domain = isl_multi_pw_aff_range_factor_domain(domain);
1143 range = isl_multi_pw_aff_range_factor_range(base);
1144 range = subscript(range, index);
1145 access = isl_multi_pw_aff_range_product(domain, range);
1146 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_out, id);
1147 return access;
1150 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_set);
1151 index = isl_pw_aff_from_range(index);
1152 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
1153 index = isl_pw_aff_intersect_domain(index, domain);
1154 access = isl_multi_pw_aff_from_pw_aff(index);
1155 access = isl_multi_pw_aff_flat_range_product(base, access);
1156 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_set, id);
1158 return access;
1159 error:
1160 isl_multi_pw_aff_free(base);
1161 isl_pw_aff_free(index);
1162 return NULL;
1165 /* Extract an index expression from the given array subscript expression.
1166 * If nesting is allowed in general, then we turn it on while
1167 * examining the index expression.
1169 * We first extract an index expression from the base.
1170 * This will result in an index expression with a range that corresponds
1171 * to the earlier indices.
1172 * We then extract the current index, restrict its domain
1173 * to those values that result in a non-negative index and
1174 * append the index to the base index expression.
1176 __isl_give isl_multi_pw_aff *PetScan::extract_index(ArraySubscriptExpr *expr)
1178 Expr *base = expr->getBase();
1179 Expr *idx = expr->getIdx();
1180 isl_pw_aff *index;
1181 isl_multi_pw_aff *base_access;
1182 isl_multi_pw_aff *access;
1183 bool save_nesting = nesting_enabled;
1185 nesting_enabled = allow_nested;
1187 base_access = extract_index(base);
1188 index = extract_affine(idx);
1190 nesting_enabled = save_nesting;
1192 access = subscript(base_access, index);
1194 return access;
1197 /* Construct a name for a member access by concatenating the name
1198 * of the array of structures and the member, separated by an underscore.
1200 * The caller is responsible for freeing the result.
1202 static char *member_access_name(isl_ctx *ctx, const char *base,
1203 const char *field)
1205 int len;
1206 char *name;
1208 len = strlen(base) + 1 + strlen(field);
1209 name = isl_alloc_array(ctx, char, len + 1);
1210 if (!name)
1211 return NULL;
1212 snprintf(name, len + 1, "%s_%s", base, field);
1214 return name;
1217 /* Given an index expression "base" for an element of an array of structures
1218 * and an expression "field" for the field member being accessed, construct
1219 * an index expression for an access to that member of the given structure.
1220 * In particular, take the range product of "base" and "field" and
1221 * attach a name to the result.
1223 static __isl_give isl_multi_pw_aff *member(__isl_take isl_multi_pw_aff *base,
1224 __isl_take isl_multi_pw_aff *field)
1226 isl_ctx *ctx;
1227 isl_multi_pw_aff *access;
1228 const char *base_name, *field_name;
1229 char *name;
1231 ctx = isl_multi_pw_aff_get_ctx(base);
1233 base_name = isl_multi_pw_aff_get_tuple_name(base, isl_dim_out);
1234 field_name = isl_multi_pw_aff_get_tuple_name(field, isl_dim_out);
1235 name = member_access_name(ctx, base_name, field_name);
1237 access = isl_multi_pw_aff_range_product(base, field);
1239 access = isl_multi_pw_aff_set_tuple_name(access, isl_dim_out, name);
1240 free(name);
1242 return access;
1245 /* Extract an index expression from a member expression.
1247 * If the base access (to the structure containing the member)
1248 * is of the form
1250 * [] -> A[..]
1252 * and the member is called "f", then the member access is of
1253 * the form
1255 * [] -> A_f[A[..] -> f[]]
1257 * If the member access is to an anonymous struct, then simply return
1259 * [] -> A[..]
1261 * If the member access in the source code is of the form
1263 * A->f
1265 * then it is treated as
1267 * A[0].f
1269 __isl_give isl_multi_pw_aff *PetScan::extract_index(MemberExpr *expr)
1271 Expr *base = expr->getBase();
1272 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
1273 isl_multi_pw_aff *base_access, *field_access;
1274 isl_id *id;
1275 isl_space *space;
1277 base_access = extract_index(base);
1279 if (expr->isArrow()) {
1280 isl_space *space = isl_space_params_alloc(ctx, 0);
1281 isl_local_space *ls = isl_local_space_from_space(space);
1282 isl_aff *aff = isl_aff_zero_on_domain(ls);
1283 isl_pw_aff *index = isl_pw_aff_from_aff(aff);
1284 base_access = subscript(base_access, index);
1287 if (field->isAnonymousStructOrUnion())
1288 return base_access;
1290 id = isl_id_alloc(ctx, field->getName().str().c_str(), field);
1291 space = isl_multi_pw_aff_get_domain_space(base_access);
1292 space = isl_space_from_domain(space);
1293 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1294 field_access = isl_multi_pw_aff_zero(space);
1296 return member(base_access, field_access);
1299 /* Check if "expr" calls function "minmax" with two arguments and if so
1300 * make lhs and rhs refer to these two arguments.
1302 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1304 CallExpr *call;
1305 FunctionDecl *fd;
1306 string name;
1308 if (expr->getStmtClass() != Stmt::CallExprClass)
1309 return false;
1311 call = cast<CallExpr>(expr);
1312 fd = call->getDirectCallee();
1313 if (!fd)
1314 return false;
1316 if (call->getNumArgs() != 2)
1317 return false;
1319 name = fd->getDeclName().getAsString();
1320 if (name != minmax)
1321 return false;
1323 lhs = call->getArg(0);
1324 rhs = call->getArg(1);
1326 return true;
1329 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1330 * lhs and rhs refer to the two arguments.
1332 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1334 return is_minmax(expr, "min", lhs, rhs);
1337 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1338 * lhs and rhs refer to the two arguments.
1340 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1342 return is_minmax(expr, "max", lhs, rhs);
1345 /* Return "lhs && rhs", defined on the shared definition domain.
1347 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1348 __isl_take isl_pw_aff *rhs)
1350 isl_set *cond;
1351 isl_set *dom;
1353 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1354 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1355 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1356 isl_pw_aff_non_zero_set(rhs));
1357 return indicator_function(cond, dom);
1360 /* Return "lhs && rhs", with shortcut semantics.
1361 * That is, if lhs is false, then the result is defined even if rhs is not.
1362 * In practice, we compute lhs ? rhs : lhs.
1364 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1365 __isl_take isl_pw_aff *rhs)
1367 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1370 /* Return "lhs || rhs", with shortcut semantics.
1371 * That is, if lhs is true, then the result is defined even if rhs is not.
1372 * In practice, we compute lhs ? lhs : rhs.
1374 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1375 __isl_take isl_pw_aff *rhs)
1377 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1380 /* Extract an affine expressions representing the comparison "LHS op RHS"
1381 * "comp" is the original statement that "LHS op RHS" is derived from
1382 * and is used for diagnostics.
1384 * If the comparison is of the form
1386 * a <= min(b,c)
1388 * then the expression is constructed as the conjunction of
1389 * the comparisons
1391 * a <= b and a <= c
1393 * A similar optimization is performed for max(a,b) <= c.
1394 * We do this because that will lead to simpler representations
1395 * of the expression.
1396 * If isl is ever enhanced to explicitly deal with min and max expressions,
1397 * this optimization can be removed.
1399 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1400 Expr *LHS, Expr *RHS, Stmt *comp)
1402 isl_pw_aff *lhs;
1403 isl_pw_aff *rhs;
1404 isl_pw_aff *res;
1405 isl_set *cond;
1406 isl_set *dom;
1408 if (op == BO_GT)
1409 return extract_comparison(BO_LT, RHS, LHS, comp);
1410 if (op == BO_GE)
1411 return extract_comparison(BO_LE, RHS, LHS, comp);
1413 if (op == BO_LT || op == BO_LE) {
1414 Expr *expr1, *expr2;
1415 if (is_min(RHS, expr1, expr2)) {
1416 lhs = extract_comparison(op, LHS, expr1, comp);
1417 rhs = extract_comparison(op, LHS, expr2, comp);
1418 return pw_aff_and(lhs, rhs);
1420 if (is_max(LHS, expr1, expr2)) {
1421 lhs = extract_comparison(op, expr1, RHS, comp);
1422 rhs = extract_comparison(op, expr2, RHS, comp);
1423 return pw_aff_and(lhs, rhs);
1427 lhs = extract_affine(LHS);
1428 rhs = extract_affine(RHS);
1430 dom = isl_pw_aff_domain(isl_pw_aff_copy(lhs));
1431 dom = isl_set_intersect(dom, isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1433 switch (op) {
1434 case BO_LT:
1435 cond = isl_pw_aff_lt_set(lhs, rhs);
1436 break;
1437 case BO_LE:
1438 cond = isl_pw_aff_le_set(lhs, rhs);
1439 break;
1440 case BO_EQ:
1441 cond = isl_pw_aff_eq_set(lhs, rhs);
1442 break;
1443 case BO_NE:
1444 cond = isl_pw_aff_ne_set(lhs, rhs);
1445 break;
1446 default:
1447 isl_pw_aff_free(lhs);
1448 isl_pw_aff_free(rhs);
1449 isl_set_free(dom);
1450 unsupported(comp);
1451 return NULL;
1454 cond = isl_set_coalesce(cond);
1455 res = indicator_function(cond, dom);
1457 return res;
1460 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1462 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1463 comp->getRHS(), comp);
1466 /* Extract an affine expression representing the negation (logical not)
1467 * of a subexpression.
1469 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1471 isl_set *set_cond, *dom;
1472 isl_pw_aff *cond, *res;
1474 cond = extract_condition(op->getSubExpr());
1476 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1478 set_cond = isl_pw_aff_zero_set(cond);
1480 res = indicator_function(set_cond, dom);
1482 return res;
1485 /* Extract an affine expression representing the disjunction (logical or)
1486 * or conjunction (logical and) of two subexpressions.
1488 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1490 isl_pw_aff *lhs, *rhs;
1492 lhs = extract_condition(comp->getLHS());
1493 rhs = extract_condition(comp->getRHS());
1495 switch (comp->getOpcode()) {
1496 case BO_LAnd:
1497 return pw_aff_and_then(lhs, rhs);
1498 case BO_LOr:
1499 return pw_aff_or_else(lhs, rhs);
1500 default:
1501 isl_pw_aff_free(lhs);
1502 isl_pw_aff_free(rhs);
1505 unsupported(comp);
1506 return NULL;
1509 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1511 switch (expr->getOpcode()) {
1512 case UO_LNot:
1513 return extract_boolean(expr);
1514 default:
1515 unsupported(expr);
1516 return NULL;
1520 /* Extract the affine expression "expr != 0 ? 1 : 0".
1522 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1524 isl_pw_aff *res;
1525 isl_set *set, *dom;
1527 res = extract_affine(expr);
1529 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1530 set = isl_pw_aff_non_zero_set(res);
1532 res = indicator_function(set, dom);
1534 return res;
1537 /* Extract an affine expression from a boolean expression.
1538 * In particular, return the expression "expr ? 1 : 0".
1540 * If the expression doesn't look like a condition, we assume it
1541 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1543 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1545 BinaryOperator *comp;
1547 if (!expr) {
1548 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1549 return indicator_function(u, isl_set_copy(u));
1552 if (expr->getStmtClass() == Stmt::ParenExprClass)
1553 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1555 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1556 return extract_condition(cast<UnaryOperator>(expr));
1558 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1559 return extract_implicit_condition(expr);
1561 comp = cast<BinaryOperator>(expr);
1562 switch (comp->getOpcode()) {
1563 case BO_LT:
1564 case BO_LE:
1565 case BO_GT:
1566 case BO_GE:
1567 case BO_EQ:
1568 case BO_NE:
1569 return extract_comparison(comp);
1570 case BO_LAnd:
1571 case BO_LOr:
1572 return extract_boolean(comp);
1573 default:
1574 return extract_implicit_condition(expr);
1578 /* Construct a pet_expr representing a unary operator expression.
1580 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1582 pet_expr *arg;
1583 enum pet_op_type op;
1585 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1586 if (op == pet_op_last) {
1587 unsupported(expr);
1588 return NULL;
1591 arg = extract_expr(expr->getSubExpr());
1593 if (expr->isIncrementDecrementOp() &&
1594 pet_expr_get_type(arg) == pet_expr_access) {
1595 arg = mark_write(arg);
1596 arg = pet_expr_access_set_read(arg, 1);
1599 return pet_expr_new_unary(op, arg);
1602 /* Mark the given access pet_expr as a write.
1603 * If a scalar is being accessed, then mark its value
1604 * as unknown in assigned_value.
1606 __isl_give pet_expr *PetScan::mark_write(__isl_take pet_expr *access)
1608 isl_id *id;
1609 ValueDecl *decl;
1611 access = pet_expr_access_set_write(access, 1);
1612 access = pet_expr_access_set_read(access, 0);
1614 if (!access || !pet_expr_is_scalar_access(access))
1615 return access;
1617 id = pet_expr_access_get_id(access);
1618 decl = (ValueDecl *) isl_id_get_user(id);
1619 clear_assignment(assigned_value, decl);
1620 isl_id_free(id);
1622 return access;
1625 /* Assign "rhs" to "lhs".
1627 * In particular, if "lhs" is a scalar variable, then mark
1628 * the variable as having been assigned. If, furthermore, "rhs"
1629 * is an affine expression, then keep track of this value in assigned_value
1630 * so that we can plug it in when we later come across the same variable.
1632 void PetScan::assign(__isl_keep pet_expr *lhs, Expr *rhs)
1634 isl_id *id;
1635 ValueDecl *decl;
1636 isl_pw_aff *pa;
1638 if (!lhs)
1639 return;
1640 if (!pet_expr_is_scalar_access(lhs))
1641 return;
1643 id = pet_expr_access_get_id(lhs);
1644 decl = (ValueDecl *) isl_id_get_user(id);
1645 isl_id_free(id);
1647 pa = try_extract_affine(rhs);
1648 clear_assignment(assigned_value, decl);
1649 if (!pa)
1650 return;
1651 assigned_value[decl] = pa;
1652 insert_expression(pa);
1655 /* Construct a pet_expr representing a binary operator expression.
1657 * If the top level operator is an assignment and the LHS is an access,
1658 * then we mark that access as a write. If the operator is a compound
1659 * assignment, the access is marked as both a read and a write.
1661 * If "expr" assigns something to a scalar variable, then we mark
1662 * the variable as having been assigned. If, furthermore, the expression
1663 * is affine, then keep track of this value in assigned_value
1664 * so that we can plug it in when we later come across the same variable.
1666 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1668 pet_expr *lhs, *rhs;
1669 enum pet_op_type op;
1671 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1672 if (op == pet_op_last) {
1673 unsupported(expr);
1674 return NULL;
1677 lhs = extract_expr(expr->getLHS());
1678 rhs = extract_expr(expr->getRHS());
1680 if (expr->isAssignmentOp() &&
1681 pet_expr_get_type(lhs) == pet_expr_access) {
1682 lhs = mark_write(lhs);
1683 if (expr->isCompoundAssignmentOp())
1684 lhs = pet_expr_access_set_read(lhs, 1);
1687 if (expr->getOpcode() == BO_Assign)
1688 assign(lhs, expr->getRHS());
1690 return pet_expr_new_binary(op, lhs, rhs);
1693 /* Construct a pet_scop with a single statement killing the entire
1694 * array "array".
1696 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1698 isl_id *id;
1699 isl_space *space;
1700 isl_multi_pw_aff *index;
1701 isl_map *access;
1702 pet_expr *expr;
1704 if (!array)
1705 return NULL;
1706 access = isl_map_from_range(isl_set_copy(array->extent));
1707 id = isl_set_get_tuple_id(array->extent);
1708 space = isl_space_alloc(ctx, 0, 0, 0);
1709 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1710 index = isl_multi_pw_aff_zero(space);
1711 expr = pet_expr_kill_from_access_and_index(access, index);
1712 return extract(stmt, expr);
1715 /* Construct a pet_scop for a (single) variable declaration.
1717 * The scop contains the variable being declared (as an array)
1718 * and a statement killing the array.
1720 * If the variable is initialized in the AST, then the scop
1721 * also contains an assignment to the variable.
1723 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1725 Decl *decl;
1726 VarDecl *vd;
1727 pet_expr *lhs, *rhs, *pe;
1728 struct pet_scop *scop_decl, *scop;
1729 struct pet_array *array;
1731 if (!stmt->isSingleDecl()) {
1732 unsupported(stmt);
1733 return NULL;
1736 decl = stmt->getSingleDecl();
1737 vd = cast<VarDecl>(decl);
1739 array = extract_array(ctx, vd, NULL);
1740 if (array)
1741 array->declared = 1;
1742 scop_decl = kill(stmt, array);
1743 scop_decl = pet_scop_add_array(scop_decl, array);
1745 if (!vd->getInit())
1746 return scop_decl;
1748 lhs = extract_access_expr(vd);
1749 rhs = extract_expr(vd->getInit());
1751 lhs = mark_write(lhs);
1752 assign(lhs, vd->getInit());
1754 pe = pet_expr_new_binary(pet_op_assign, lhs, rhs);
1755 scop = extract(stmt, pe);
1757 scop_decl = pet_scop_prefix(scop_decl, 0);
1758 scop = pet_scop_prefix(scop, 1);
1760 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1762 return scop;
1765 /* Construct a pet_expr representing a conditional operation.
1767 * We first try to extract the condition as an affine expression.
1768 * If that fails, we construct a pet_expr tree representing the condition.
1770 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1772 pet_expr *cond, *lhs, *rhs;
1773 isl_pw_aff *pa;
1775 pa = try_extract_affine(expr->getCond());
1776 if (pa) {
1777 isl_multi_pw_aff *test = isl_multi_pw_aff_from_pw_aff(pa);
1778 test = isl_multi_pw_aff_from_range(test);
1779 cond = pet_expr_from_index(test);
1780 } else
1781 cond = extract_expr(expr->getCond());
1782 lhs = extract_expr(expr->getTrueExpr());
1783 rhs = extract_expr(expr->getFalseExpr());
1785 return pet_expr_new_ternary(cond, lhs, rhs);
1788 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1790 return extract_expr(expr->getSubExpr());
1793 /* Construct a pet_expr representing a floating point value.
1795 * If the floating point literal does not appear in a macro,
1796 * then we use the original representation in the source code
1797 * as the string representation. Otherwise, we use the pretty
1798 * printer to produce a string representation.
1800 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1802 double d;
1803 string s;
1804 const LangOptions &LO = PP.getLangOpts();
1805 SourceLocation loc = expr->getLocation();
1807 if (!loc.isMacroID()) {
1808 SourceManager &SM = PP.getSourceManager();
1809 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1810 s = string(SM.getCharacterData(loc), len);
1811 } else {
1812 llvm::raw_string_ostream S(s);
1813 expr->printPretty(S, 0, PrintingPolicy(LO));
1814 S.str();
1816 d = expr->getValueAsApproximateDouble();
1817 return pet_expr_new_double(ctx, d, s.c_str());
1820 /* Extract an index expression from "expr" and then convert it into
1821 * an access pet_expr.
1823 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
1825 isl_multi_pw_aff *index;
1826 pet_expr *pe;
1827 int depth;
1829 index = extract_index(expr);
1830 depth = extract_depth(index);
1832 pe = pet_expr_from_index_and_depth(index, depth);
1834 return pe;
1837 /* Extract an index expression from "decl" and then convert it into
1838 * an access pet_expr.
1840 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1842 isl_multi_pw_aff *index;
1843 pet_expr *pe;
1844 int depth;
1846 index = extract_index(decl);
1847 depth = extract_depth(index);
1849 pe = pet_expr_from_index_and_depth(index, depth);
1851 return pe;
1854 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
1856 return extract_expr(expr->getSubExpr());
1859 /* Extract an assume statement from the argument "expr"
1860 * of a __pencil_assume statement.
1862 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
1864 isl_pw_aff *cond;
1865 pet_expr *res;
1867 cond = try_extract_affine_condition(expr);
1868 if (!cond) {
1869 res = extract_expr(expr);
1870 } else {
1871 isl_multi_pw_aff *index;
1872 index = isl_multi_pw_aff_from_pw_aff(cond);
1873 index = isl_multi_pw_aff_from_range(index);
1874 res = pet_expr_from_index(index);
1876 return pet_expr_new_unary(pet_op_assume, res);
1879 /* Construct a pet_expr corresponding to the function call argument "expr".
1880 * The argument appears in position "pos" of a call to function "fd".
1882 * If we are passing along a pointer to an array element
1883 * or an entire row or even higher dimensional slice of an array,
1884 * then the function being called may write into the array.
1886 * We assume here that if the function is declared to take a pointer
1887 * to a const type, then the function will perform a read
1888 * and that otherwise, it will perform a write.
1890 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
1891 Expr *expr)
1893 pet_expr *res;
1894 int is_addr = 0, is_partial = 0;
1895 Stmt::StmtClass sc;
1897 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
1898 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
1899 expr = ice->getSubExpr();
1901 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
1902 UnaryOperator *op = cast<UnaryOperator>(expr);
1903 if (op->getOpcode() == UO_AddrOf) {
1904 is_addr = 1;
1905 expr = op->getSubExpr();
1908 res = extract_expr(expr);
1909 if (!res)
1910 return NULL;
1911 sc = expr->getStmtClass();
1912 if ((sc == Stmt::ArraySubscriptExprClass ||
1913 sc == Stmt::MemberExprClass) &&
1914 array_depth(expr->getType().getTypePtr()) > 0)
1915 is_partial = 1;
1916 if ((is_addr || is_partial) &&
1917 pet_expr_get_type(res) == pet_expr_access) {
1918 ParmVarDecl *parm;
1919 if (!fd->hasPrototype()) {
1920 report_prototype_required(expr);
1921 return pet_expr_free(res);
1923 parm = fd->getParamDecl(pos);
1924 if (!const_base(parm->getType()))
1925 res = mark_write(res);
1928 if (is_addr)
1929 res = pet_expr_new_unary(pet_op_address_of, res);
1930 return res;
1933 /* Construct a pet_expr representing a function call.
1935 * In the special case of a "call" to __pencil_assume,
1936 * construct an assume expression instead.
1938 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1940 pet_expr *res = NULL;
1941 FunctionDecl *fd;
1942 string name;
1943 unsigned n_arg;
1945 fd = expr->getDirectCallee();
1946 if (!fd) {
1947 unsupported(expr);
1948 return NULL;
1951 name = fd->getDeclName().getAsString();
1952 n_arg = expr->getNumArgs();
1954 if (n_arg == 1 && name == "__pencil_assume")
1955 return extract_assume(expr->getArg(0));
1957 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1958 if (!res)
1959 return NULL;
1961 for (int i = 0; i < n_arg; ++i) {
1962 Expr *arg = expr->getArg(i);
1963 res = pet_expr_set_arg(res, i,
1964 PetScan::extract_argument(fd, i, arg));
1967 return res;
1970 /* Construct a pet_expr representing a (C style) cast.
1972 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1974 pet_expr *arg;
1975 QualType type;
1977 arg = extract_expr(expr->getSubExpr());
1978 if (!arg)
1979 return NULL;
1981 type = expr->getTypeAsWritten();
1982 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1985 /* Construct a pet_expr representing an integer.
1987 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1989 return pet_expr_new_int(extract_int(expr));
1992 /* Try and construct a pet_expr representing "expr".
1994 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1996 switch (expr->getStmtClass()) {
1997 case Stmt::UnaryOperatorClass:
1998 return extract_expr(cast<UnaryOperator>(expr));
1999 case Stmt::CompoundAssignOperatorClass:
2000 case Stmt::BinaryOperatorClass:
2001 return extract_expr(cast<BinaryOperator>(expr));
2002 case Stmt::ImplicitCastExprClass:
2003 return extract_expr(cast<ImplicitCastExpr>(expr));
2004 case Stmt::ArraySubscriptExprClass:
2005 case Stmt::DeclRefExprClass:
2006 case Stmt::MemberExprClass:
2007 return extract_access_expr(expr);
2008 case Stmt::IntegerLiteralClass:
2009 return extract_expr(cast<IntegerLiteral>(expr));
2010 case Stmt::FloatingLiteralClass:
2011 return extract_expr(cast<FloatingLiteral>(expr));
2012 case Stmt::ParenExprClass:
2013 return extract_expr(cast<ParenExpr>(expr));
2014 case Stmt::ConditionalOperatorClass:
2015 return extract_expr(cast<ConditionalOperator>(expr));
2016 case Stmt::CallExprClass:
2017 return extract_expr(cast<CallExpr>(expr));
2018 case Stmt::CStyleCastExprClass:
2019 return extract_expr(cast<CStyleCastExpr>(expr));
2020 default:
2021 unsupported(expr);
2023 return NULL;
2026 /* Check if the given initialization statement is an assignment.
2027 * If so, return that assignment. Otherwise return NULL.
2029 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
2031 BinaryOperator *ass;
2033 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
2034 return NULL;
2036 ass = cast<BinaryOperator>(init);
2037 if (ass->getOpcode() != BO_Assign)
2038 return NULL;
2040 return ass;
2043 /* Check if the given initialization statement is a declaration
2044 * of a single variable.
2045 * If so, return that declaration. Otherwise return NULL.
2047 Decl *PetScan::initialization_declaration(Stmt *init)
2049 DeclStmt *decl;
2051 if (init->getStmtClass() != Stmt::DeclStmtClass)
2052 return NULL;
2054 decl = cast<DeclStmt>(init);
2056 if (!decl->isSingleDecl())
2057 return NULL;
2059 return decl->getSingleDecl();
2062 /* Given the assignment operator in the initialization of a for loop,
2063 * extract the induction variable, i.e., the (integer)variable being
2064 * assigned.
2066 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
2068 Expr *lhs;
2069 DeclRefExpr *ref;
2070 ValueDecl *decl;
2071 const Type *type;
2073 lhs = init->getLHS();
2074 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2075 unsupported(init);
2076 return NULL;
2079 ref = cast<DeclRefExpr>(lhs);
2080 decl = ref->getDecl();
2081 type = decl->getType().getTypePtr();
2083 if (!type->isIntegerType()) {
2084 unsupported(lhs);
2085 return NULL;
2088 return decl;
2091 /* Given the initialization statement of a for loop and the single
2092 * declaration in this initialization statement,
2093 * extract the induction variable, i.e., the (integer) variable being
2094 * declared.
2096 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
2098 VarDecl *vd;
2100 vd = cast<VarDecl>(decl);
2102 const QualType type = vd->getType();
2103 if (!type->isIntegerType()) {
2104 unsupported(init);
2105 return NULL;
2108 if (!vd->getInit()) {
2109 unsupported(init);
2110 return NULL;
2113 return vd;
2116 /* Check that op is of the form iv++ or iv--.
2117 * Return an affine expression "1" or "-1" accordingly.
2119 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
2120 clang::UnaryOperator *op, clang::ValueDecl *iv)
2122 Expr *sub;
2123 DeclRefExpr *ref;
2124 isl_space *space;
2125 isl_aff *aff;
2127 if (!op->isIncrementDecrementOp()) {
2128 unsupported(op);
2129 return NULL;
2132 sub = op->getSubExpr();
2133 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
2134 unsupported(op);
2135 return NULL;
2138 ref = cast<DeclRefExpr>(sub);
2139 if (ref->getDecl() != iv) {
2140 unsupported(op);
2141 return NULL;
2144 space = isl_space_params_alloc(ctx, 0);
2145 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2147 if (op->isIncrementOp())
2148 aff = isl_aff_add_constant_si(aff, 1);
2149 else
2150 aff = isl_aff_add_constant_si(aff, -1);
2152 return isl_pw_aff_from_aff(aff);
2155 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
2156 * has a single constant expression, then put this constant in *user.
2157 * The caller is assumed to have checked that this function will
2158 * be called exactly once.
2160 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
2161 void *user)
2163 isl_val **inc = (isl_val **)user;
2164 int res = 0;
2166 if (isl_aff_is_cst(aff))
2167 *inc = isl_aff_get_constant_val(aff);
2168 else
2169 res = -1;
2171 isl_set_free(set);
2172 isl_aff_free(aff);
2174 return res;
2177 /* Check if op is of the form
2179 * iv = iv + inc
2181 * and return inc as an affine expression.
2183 * We extract an affine expression from the RHS, subtract iv and return
2184 * the result.
2186 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
2187 clang::ValueDecl *iv)
2189 Expr *lhs;
2190 DeclRefExpr *ref;
2191 isl_id *id;
2192 isl_space *dim;
2193 isl_aff *aff;
2194 isl_pw_aff *val;
2196 if (op->getOpcode() != BO_Assign) {
2197 unsupported(op);
2198 return NULL;
2201 lhs = op->getLHS();
2202 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2203 unsupported(op);
2204 return NULL;
2207 ref = cast<DeclRefExpr>(lhs);
2208 if (ref->getDecl() != iv) {
2209 unsupported(op);
2210 return NULL;
2213 val = extract_affine(op->getRHS());
2215 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2217 dim = isl_space_params_alloc(ctx, 1);
2218 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2219 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2220 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2222 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
2224 return val;
2227 /* Check that op is of the form iv += cst or iv -= cst
2228 * and return an affine expression corresponding oto cst or -cst accordingly.
2230 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
2231 CompoundAssignOperator *op, clang::ValueDecl *iv)
2233 Expr *lhs;
2234 DeclRefExpr *ref;
2235 bool neg = false;
2236 isl_pw_aff *val;
2237 BinaryOperatorKind opcode;
2239 opcode = op->getOpcode();
2240 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
2241 unsupported(op);
2242 return NULL;
2244 if (opcode == BO_SubAssign)
2245 neg = true;
2247 lhs = op->getLHS();
2248 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2249 unsupported(op);
2250 return NULL;
2253 ref = cast<DeclRefExpr>(lhs);
2254 if (ref->getDecl() != iv) {
2255 unsupported(op);
2256 return NULL;
2259 val = extract_affine(op->getRHS());
2260 if (neg)
2261 val = isl_pw_aff_neg(val);
2263 return val;
2266 /* Check that the increment of the given for loop increments
2267 * (or decrements) the induction variable "iv" and return
2268 * the increment as an affine expression if successful.
2270 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
2271 ValueDecl *iv)
2273 Stmt *inc = stmt->getInc();
2275 if (!inc) {
2276 report_missing_increment(stmt);
2277 return NULL;
2280 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
2281 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
2282 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
2283 return extract_compound_increment(
2284 cast<CompoundAssignOperator>(inc), iv);
2285 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
2286 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
2288 unsupported(inc);
2289 return NULL;
2292 /* Embed the given iteration domain in an extra outer loop
2293 * with induction variable "var".
2294 * If this variable appeared as a parameter in the constraints,
2295 * it is replaced by the new outermost dimension.
2297 static __isl_give isl_set *embed(__isl_take isl_set *set,
2298 __isl_take isl_id *var)
2300 int pos;
2302 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
2303 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
2304 if (pos >= 0) {
2305 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
2306 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2309 isl_id_free(var);
2310 return set;
2313 /* Return those elements in the space of "cond" that come after
2314 * (based on "sign") an element in "cond".
2316 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
2318 isl_map *previous_to_this;
2320 if (sign > 0)
2321 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
2322 else
2323 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
2325 cond = isl_set_apply(cond, previous_to_this);
2327 return cond;
2330 /* Create the infinite iteration domain
2332 * { [id] : id >= 0 }
2334 * If "scop" has an affine skip of type pet_skip_later,
2335 * then remove those iterations i that have an earlier iteration
2336 * where the skip condition is satisfied, meaning that iteration i
2337 * is not executed.
2338 * Since we are dealing with a loop without loop iterator,
2339 * the skip condition cannot refer to the current loop iterator and
2340 * so effectively, the returned set is of the form
2342 * { [0]; [id] : id >= 1 and not skip }
2344 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
2345 struct pet_scop *scop)
2347 isl_ctx *ctx = isl_id_get_ctx(id);
2348 isl_set *domain;
2349 isl_set *skip;
2351 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
2352 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
2354 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
2355 return domain;
2357 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2358 skip = embed(skip, isl_id_copy(id));
2359 skip = isl_set_intersect(skip , isl_set_copy(domain));
2360 domain = isl_set_subtract(domain, after(skip, 1));
2362 return domain;
2365 /* Create an identity affine expression on the space containing "domain",
2366 * which is assumed to be one-dimensional.
2368 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
2370 isl_local_space *ls;
2372 ls = isl_local_space_from_space(isl_set_get_space(domain));
2373 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
2376 /* Create an affine expression that maps elements
2377 * of a single-dimensional array "id_test" to the previous element
2378 * (according to "inc"), provided this element belongs to "domain".
2379 * That is, create the affine expression
2381 * { id[x] -> id[x - inc] : x - inc in domain }
2383 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
2384 __isl_take isl_set *domain, __isl_take isl_val *inc)
2386 isl_space *space;
2387 isl_local_space *ls;
2388 isl_aff *aff;
2389 isl_multi_pw_aff *prev;
2391 space = isl_set_get_space(domain);
2392 ls = isl_local_space_from_space(space);
2393 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2394 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
2395 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
2396 domain = isl_set_preimage_multi_pw_aff(domain,
2397 isl_multi_pw_aff_copy(prev));
2398 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
2399 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
2401 return prev;
2404 /* Add an implication to "scop" expressing that if an element of
2405 * virtual array "id_test" has value "satisfied" then all previous elements
2406 * of this array also have that value. The set of previous elements
2407 * is bounded by "domain". If "sign" is negative then the iterator
2408 * is decreasing and we express that all subsequent array elements
2409 * (but still defined previously) have the same value.
2411 static struct pet_scop *add_implication(struct pet_scop *scop,
2412 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
2413 int satisfied)
2415 isl_space *space;
2416 isl_map *map;
2418 domain = isl_set_set_tuple_id(domain, id_test);
2419 space = isl_set_get_space(domain);
2420 if (sign > 0)
2421 map = isl_map_lex_ge(space);
2422 else
2423 map = isl_map_lex_le(space);
2424 map = isl_map_intersect_range(map, domain);
2425 scop = pet_scop_add_implication(scop, map, satisfied);
2427 return scop;
2430 /* Add a filter to "scop" that imposes that it is only executed
2431 * when the variable identified by "id_test" has a zero value
2432 * for all previous iterations of "domain".
2434 * In particular, add a filter that imposes that the array
2435 * has a zero value at the previous iteration of domain and
2436 * add an implication that implies that it then has that
2437 * value for all previous iterations.
2439 static struct pet_scop *scop_add_break(struct pet_scop *scop,
2440 __isl_take isl_id *id_test, __isl_take isl_set *domain,
2441 __isl_take isl_val *inc)
2443 isl_multi_pw_aff *prev;
2444 int sign = isl_val_sgn(inc);
2446 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2447 scop = add_implication(scop, id_test, domain, sign, 0);
2448 scop = pet_scop_filter(scop, prev, 0);
2450 return scop;
2453 /* Construct a pet_scop for an infinite loop around the given body.
2455 * We extract a pet_scop for the body and then embed it in a loop with
2456 * iteration domain
2458 * { [t] : t >= 0 }
2460 * and schedule
2462 * { [t] -> [t] }
2464 * If the body contains any break, then it is taken into
2465 * account in infinite_domain (if the skip condition is affine)
2466 * or in scop_add_break (if the skip condition is not affine).
2468 * If we were only able to extract part of the body, then simply
2469 * return that part.
2471 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2473 isl_id *id, *id_test;
2474 isl_set *domain;
2475 isl_aff *ident;
2476 struct pet_scop *scop;
2477 bool has_var_break;
2479 scop = extract(body);
2480 if (!scop)
2481 return NULL;
2482 if (partial)
2483 return scop;
2485 id = isl_id_alloc(ctx, "t", NULL);
2486 domain = infinite_domain(isl_id_copy(id), scop);
2487 ident = identity_aff(domain);
2489 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2490 if (has_var_break)
2491 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
2493 scop = pet_scop_embed(scop, isl_set_copy(domain),
2494 isl_aff_copy(ident), ident, id);
2495 if (has_var_break)
2496 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
2497 else
2498 isl_set_free(domain);
2500 return scop;
2503 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2505 * for (;;)
2506 * body
2509 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2511 clear_assignments clear(assigned_value);
2512 clear.TraverseStmt(stmt->getBody());
2514 return extract_infinite_loop(stmt->getBody());
2517 /* Create an index expression for an access to a virtual array
2518 * representing the result of a condition.
2519 * Unlike other accessed data, the id of the array is NULL as
2520 * there is no ValueDecl in the program corresponding to the virtual
2521 * array.
2522 * The array starts out as a scalar, but grows along with the
2523 * statement writing to the array in pet_scop_embed.
2525 static __isl_give isl_multi_pw_aff *create_test_index(isl_ctx *ctx, int test_nr)
2527 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2528 isl_id *id;
2529 char name[50];
2531 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2532 id = isl_id_alloc(ctx, name, NULL);
2533 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2534 return isl_multi_pw_aff_zero(dim);
2537 /* Add an array with the given extent (range of "index") to the list
2538 * of arrays in "scop" and return the extended pet_scop.
2539 * The array is marked as attaining values 0 and 1 only and
2540 * as each element being assigned at most once.
2542 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2543 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
2545 isl_ctx *ctx = isl_multi_pw_aff_get_ctx(index);
2546 isl_space *dim;
2547 struct pet_array *array;
2548 isl_map *access;
2550 if (!scop)
2551 return NULL;
2552 if (!ctx)
2553 goto error;
2555 array = isl_calloc_type(ctx, struct pet_array);
2556 if (!array)
2557 goto error;
2559 access = isl_map_from_multi_pw_aff(isl_multi_pw_aff_copy(index));
2560 array->extent = isl_map_range(access);
2561 dim = isl_space_params_alloc(ctx, 0);
2562 array->context = isl_set_universe(dim);
2563 dim = isl_space_set_alloc(ctx, 0, 1);
2564 array->value_bounds = isl_set_universe(dim);
2565 array->value_bounds = isl_set_lower_bound_si(array->value_bounds,
2566 isl_dim_set, 0, 0);
2567 array->value_bounds = isl_set_upper_bound_si(array->value_bounds,
2568 isl_dim_set, 0, 1);
2569 array->element_type = strdup("int");
2570 array->element_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2571 array->uniquely_defined = 1;
2573 if (!array->extent || !array->context)
2574 array = pet_array_free(array);
2576 scop = pet_scop_add_array(scop, array);
2578 return scop;
2579 error:
2580 pet_scop_free(scop);
2581 return NULL;
2584 /* Construct a pet_scop for a while loop of the form
2586 * while (pa)
2587 * body
2589 * In particular, construct a scop for an infinite loop around body and
2590 * intersect the domain with the affine expression.
2591 * Note that this intersection may result in an empty loop.
2593 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2594 Stmt *body)
2596 struct pet_scop *scop;
2597 isl_set *dom;
2598 isl_set *valid;
2600 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2601 dom = isl_pw_aff_non_zero_set(pa);
2602 scop = extract_infinite_loop(body);
2603 scop = pet_scop_restrict(scop, dom);
2604 scop = pet_scop_restrict_context(scop, valid);
2606 return scop;
2609 /* Construct a scop for a while, given the scops for the condition
2610 * and the body, the filter identifier and the iteration domain of
2611 * the while loop.
2613 * In particular, the scop for the condition is filtered to depend
2614 * on "id_test" evaluating to true for all previous iterations
2615 * of the loop, while the scop for the body is filtered to depend
2616 * on "id_test" evaluating to true for all iterations up to the
2617 * current iteration.
2618 * The actual filter only imposes that this virtual array has
2619 * value one on the previous or the current iteration.
2620 * The fact that this condition also applies to the previous
2621 * iterations is enforced by an implication.
2623 * These filtered scops are then combined into a single scop.
2625 * "sign" is positive if the iterator increases and negative
2626 * if it decreases.
2628 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2629 struct pet_scop *scop_body, __isl_take isl_id *id_test,
2630 __isl_take isl_set *domain, __isl_take isl_val *inc)
2632 isl_ctx *ctx = isl_set_get_ctx(domain);
2633 isl_space *space;
2634 isl_multi_pw_aff *test_index;
2635 isl_multi_pw_aff *prev;
2636 int sign = isl_val_sgn(inc);
2637 struct pet_scop *scop;
2639 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2640 scop_cond = pet_scop_filter(scop_cond, prev, 1);
2642 space = isl_space_map_from_set(isl_set_get_space(domain));
2643 test_index = isl_multi_pw_aff_identity(space);
2644 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
2645 isl_id_copy(id_test));
2646 scop_body = pet_scop_filter(scop_body, test_index, 1);
2648 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
2649 scop = add_implication(scop, id_test, domain, sign, 1);
2651 return scop;
2654 /* Check if the while loop is of the form
2656 * while (affine expression)
2657 * body
2659 * If so, call extract_affine_while to construct a scop.
2661 * Otherwise, construct a generic while scop, with iteration domain
2662 * { [t] : t >= 0 }. The scop consists of two parts, one for
2663 * evaluating the condition and one for the body.
2664 * The schedule is adjusted to reflect that the condition is evaluated
2665 * before the body is executed and the body is filtered to depend
2666 * on the result of the condition evaluating to true on all iterations
2667 * up to the current iteration, while the evaluation of the condition itself
2668 * is filtered to depend on the result of the condition evaluating to true
2669 * on all previous iterations.
2670 * The context of the scop representing the body is dropped
2671 * because we don't know how many times the body will be executed,
2672 * if at all.
2674 * If the body contains any break, then it is taken into
2675 * account in infinite_domain (if the skip condition is affine)
2676 * or in scop_add_break (if the skip condition is not affine).
2678 * If we were only able to extract part of the body, then simply
2679 * return that part.
2681 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2683 Expr *cond;
2684 int test_nr, stmt_nr;
2685 isl_id *id, *id_test, *id_break_test;
2686 isl_multi_pw_aff *test_index;
2687 isl_set *domain;
2688 isl_aff *ident;
2689 isl_pw_aff *pa;
2690 struct pet_scop *scop, *scop_body;
2691 bool has_var_break;
2693 cond = stmt->getCond();
2694 if (!cond) {
2695 unsupported(stmt);
2696 return NULL;
2699 clear_assignments clear(assigned_value);
2700 clear.TraverseStmt(stmt->getBody());
2702 pa = try_extract_affine_condition(cond);
2703 if (pa)
2704 return extract_affine_while(pa, stmt->getBody());
2706 if (!allow_nested) {
2707 unsupported(stmt);
2708 return NULL;
2711 test_nr = n_test++;
2712 stmt_nr = n_stmt++;
2713 scop_body = extract(stmt->getBody());
2714 if (partial)
2715 return scop_body;
2717 test_index = create_test_index(ctx, test_nr);
2718 scop = extract_non_affine_condition(cond, stmt_nr,
2719 isl_multi_pw_aff_copy(test_index));
2720 scop = scop_add_array(scop, test_index, ast_context);
2721 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2722 isl_multi_pw_aff_free(test_index);
2724 id = isl_id_alloc(ctx, "t", NULL);
2725 domain = infinite_domain(isl_id_copy(id), scop_body);
2726 ident = identity_aff(domain);
2728 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2729 if (has_var_break)
2730 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2732 scop = pet_scop_prefix(scop, 0);
2733 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_aff_copy(ident),
2734 isl_aff_copy(ident), isl_id_copy(id));
2735 scop_body = pet_scop_reset_context(scop_body);
2736 scop_body = pet_scop_prefix(scop_body, 1);
2737 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2738 isl_aff_copy(ident), ident, id);
2740 if (has_var_break) {
2741 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2742 isl_set_copy(domain), isl_val_one(ctx));
2743 scop_body = scop_add_break(scop_body, id_break_test,
2744 isl_set_copy(domain), isl_val_one(ctx));
2746 scop = scop_add_while(scop, scop_body, id_test, domain,
2747 isl_val_one(ctx));
2749 return scop;
2752 /* Check whether "cond" expresses a simple loop bound
2753 * on the only set dimension.
2754 * In particular, if "up" is set then "cond" should contain only
2755 * upper bounds on the set dimension.
2756 * Otherwise, it should contain only lower bounds.
2758 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2760 if (isl_val_is_pos(inc))
2761 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2762 else
2763 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2766 /* Extend a condition on a given iteration of a loop to one that
2767 * imposes the same condition on all previous iterations.
2768 * "domain" expresses the lower [upper] bound on the iterations
2769 * when inc is positive [negative].
2771 * In particular, we construct the condition (when inc is positive)
2773 * forall i' : (domain(i') and i' <= i) => cond(i')
2775 * which is equivalent to
2777 * not exists i' : domain(i') and i' <= i and not cond(i')
2779 * We construct this set by negating cond, applying a map
2781 * { [i'] -> [i] : domain(i') and i' <= i }
2783 * and then negating the result again.
2785 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2786 __isl_take isl_set *domain, __isl_take isl_val *inc)
2788 isl_map *previous_to_this;
2790 if (isl_val_is_pos(inc))
2791 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2792 else
2793 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2795 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2797 cond = isl_set_complement(cond);
2798 cond = isl_set_apply(cond, previous_to_this);
2799 cond = isl_set_complement(cond);
2801 isl_val_free(inc);
2803 return cond;
2806 /* Construct a domain of the form
2808 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2810 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2811 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2813 isl_aff *aff;
2814 isl_space *dim;
2815 isl_set *set;
2817 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2818 dim = isl_pw_aff_get_domain_space(init);
2819 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2820 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2821 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2823 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2824 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2825 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2826 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2828 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2830 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2832 return isl_set_params(set);
2835 /* Assuming "cond" represents a bound on a loop where the loop
2836 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2837 * is possible.
2839 * Under the given assumptions, wrapping is only possible if "cond" allows
2840 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2841 * increasing iterator and 0 in case of a decreasing iterator.
2843 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2844 __isl_keep isl_val *inc)
2846 bool cw;
2847 isl_ctx *ctx;
2848 isl_val *limit;
2849 isl_set *test;
2851 test = isl_set_copy(cond);
2853 ctx = isl_set_get_ctx(test);
2854 if (isl_val_is_neg(inc))
2855 limit = isl_val_zero(ctx);
2856 else {
2857 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2858 limit = isl_val_2exp(limit);
2859 limit = isl_val_sub_ui(limit, 1);
2862 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2863 cw = !isl_set_is_empty(test);
2864 isl_set_free(test);
2866 return cw;
2869 /* Given a one-dimensional space, construct the following affine expression
2870 * on this space
2872 * { [v] -> [v mod 2^width] }
2874 * where width is the number of bits used to represent the values
2875 * of the unsigned variable "iv".
2877 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2878 ValueDecl *iv)
2880 isl_ctx *ctx;
2881 isl_val *mod;
2882 isl_aff *aff;
2884 ctx = isl_space_get_ctx(dim);
2885 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2886 mod = isl_val_2exp(mod);
2888 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2889 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2890 aff = isl_aff_mod_val(aff, mod);
2892 return aff;
2895 /* Project out the parameter "id" from "set".
2897 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2898 __isl_keep isl_id *id)
2900 int pos;
2902 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2903 if (pos >= 0)
2904 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2906 return set;
2909 /* Compute the set of parameters for which "set1" is a subset of "set2".
2911 * set1 is a subset of set2 if
2913 * forall i in set1 : i in set2
2915 * or
2917 * not exists i in set1 and i not in set2
2919 * i.e.,
2921 * not exists i in set1 \ set2
2923 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2924 __isl_take isl_set *set2)
2926 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2929 /* Compute the set of parameter values for which "cond" holds
2930 * on the next iteration for each element of "dom".
2932 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2933 * and then compute the set of parameters for which the result is a subset
2934 * of "cond".
2936 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2937 __isl_take isl_set *dom, __isl_take isl_val *inc)
2939 isl_space *space;
2940 isl_aff *aff;
2941 isl_map *next;
2943 space = isl_set_get_space(dom);
2944 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2945 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2946 aff = isl_aff_add_constant_val(aff, inc);
2947 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2949 dom = isl_set_apply(dom, next);
2951 return enforce_subset(dom, cond);
2954 /* Construct a pet_scop for a for statement.
2955 * The for loop is required to be of the form
2957 * for (i = init; condition; ++i)
2959 * or
2961 * for (i = init; condition; --i)
2963 * The initialization of the for loop should either be an assignment
2964 * to an integer variable, or a declaration of such a variable with
2965 * initialization.
2967 * The condition is allowed to contain nested accesses, provided
2968 * they are not being written to inside the body of the loop.
2969 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2970 * essentially treated as a while loop, with iteration domain
2971 * { [i] : i >= init }.
2973 * We extract a pet_scop for the body and then embed it in a loop with
2974 * iteration domain and schedule
2976 * { [i] : i >= init and condition' }
2977 * { [i] -> [i] }
2979 * or
2981 * { [i] : i <= init and condition' }
2982 * { [i] -> [-i] }
2984 * Where condition' is equal to condition if the latter is
2985 * a simple upper [lower] bound and a condition that is extended
2986 * to apply to all previous iterations otherwise.
2988 * If the condition is non-affine, then we drop the condition from the
2989 * iteration domain and instead create a separate statement
2990 * for evaluating the condition. The body is then filtered to depend
2991 * on the result of the condition evaluating to true on all iterations
2992 * up to the current iteration, while the evaluation the condition itself
2993 * is filtered to depend on the result of the condition evaluating to true
2994 * on all previous iterations.
2995 * The context of the scop representing the body is dropped
2996 * because we don't know how many times the body will be executed,
2997 * if at all.
2999 * If the stride of the loop is not 1, then "i >= init" is replaced by
3001 * (exists a: i = init + stride * a and a >= 0)
3003 * If the loop iterator i is unsigned, then wrapping may occur.
3004 * We therefore use a virtual iterator instead that does not wrap.
3005 * However, the condition in the code applies
3006 * to the wrapped value, so we need to change condition(i)
3007 * into condition([i % 2^width]). Similarly, we replace all accesses
3008 * to the original iterator by the wrapping of the virtual iterator.
3009 * Note that there may be no need to perform this final wrapping
3010 * if the loop condition (after wrapping) satisfies certain conditions.
3011 * However, the is_simple_bound condition is not enough since it doesn't
3012 * check if there even is an upper bound.
3014 * Wrapping on unsigned iterators can be avoided entirely if
3015 * loop condition is simple, the loop iterator is incremented
3016 * [decremented] by one and the last value before wrapping cannot
3017 * possibly satisfy the loop condition.
3019 * Before extracting a pet_scop from the body we remove all
3020 * assignments in assigned_value to variables that are assigned
3021 * somewhere in the body of the loop.
3023 * Valid parameters for a for loop are those for which the initial
3024 * value itself, the increment on each domain iteration and
3025 * the condition on both the initial value and
3026 * the result of incrementing the iterator for each iteration of the domain
3027 * can be evaluated.
3028 * If the loop condition is non-affine, then we only consider validity
3029 * of the initial value.
3031 * If the body contains any break, then we keep track of it in "skip"
3032 * (if the skip condition is affine) or it is handled in scop_add_break
3033 * (if the skip condition is not affine).
3034 * Note that the affine break condition needs to be considered with
3035 * respect to previous iterations in the virtual domain (if any).
3037 * If we were only able to extract part of the body, then simply
3038 * return that part.
3040 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
3042 BinaryOperator *ass;
3043 Decl *decl;
3044 Stmt *init;
3045 Expr *lhs, *rhs;
3046 ValueDecl *iv;
3047 isl_local_space *ls;
3048 isl_set *domain;
3049 isl_aff *sched;
3050 isl_set *cond = NULL;
3051 isl_set *skip = NULL;
3052 isl_id *id, *id_test = NULL, *id_break_test;
3053 struct pet_scop *scop, *scop_cond = NULL;
3054 assigned_value_cache cache(assigned_value);
3055 isl_val *inc;
3056 bool was_assigned;
3057 bool is_one;
3058 bool is_unsigned;
3059 bool is_simple;
3060 bool is_virtual;
3061 bool has_affine_break;
3062 bool has_var_break;
3063 isl_aff *wrap = NULL;
3064 isl_pw_aff *pa, *pa_inc, *init_val;
3065 isl_set *valid_init;
3066 isl_set *valid_cond;
3067 isl_set *valid_cond_init;
3068 isl_set *valid_cond_next;
3069 isl_set *valid_inc;
3070 int stmt_id;
3072 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
3073 return extract_infinite_for(stmt);
3075 init = stmt->getInit();
3076 if (!init) {
3077 unsupported(stmt);
3078 return NULL;
3080 if ((ass = initialization_assignment(init)) != NULL) {
3081 iv = extract_induction_variable(ass);
3082 if (!iv)
3083 return NULL;
3084 lhs = ass->getLHS();
3085 rhs = ass->getRHS();
3086 } else if ((decl = initialization_declaration(init)) != NULL) {
3087 VarDecl *var = extract_induction_variable(init, decl);
3088 if (!var)
3089 return NULL;
3090 iv = var;
3091 rhs = var->getInit();
3092 lhs = create_DeclRefExpr(var);
3093 } else {
3094 unsupported(stmt->getInit());
3095 return NULL;
3098 assigned_value.erase(iv);
3099 clear_assignments clear(assigned_value);
3100 clear.TraverseStmt(stmt->getBody());
3102 was_assigned = assigned_value.find(iv) != assigned_value.end();
3103 clear_assignment(assigned_value, iv);
3104 init_val = extract_affine(rhs);
3105 if (!was_assigned)
3106 assigned_value.erase(iv);
3107 if (!init_val)
3108 return NULL;
3110 pa_inc = extract_increment(stmt, iv);
3111 if (!pa_inc) {
3112 isl_pw_aff_free(init_val);
3113 return NULL;
3116 inc = NULL;
3117 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
3118 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
3119 isl_pw_aff_free(init_val);
3120 isl_pw_aff_free(pa_inc);
3121 unsupported(stmt->getInc());
3122 isl_val_free(inc);
3123 return NULL;
3126 pa = try_extract_nested_condition(stmt->getCond());
3127 if (allow_nested && (!pa || pet_nested_any_in_pw_aff(pa)))
3128 stmt_id = n_stmt++;
3130 scop = extract(stmt->getBody());
3131 if (partial) {
3132 isl_pw_aff_free(init_val);
3133 isl_pw_aff_free(pa_inc);
3134 isl_pw_aff_free(pa);
3135 isl_val_free(inc);
3136 return scop;
3139 valid_inc = isl_pw_aff_domain(pa_inc);
3141 is_unsigned = iv->getType()->isUnsignedIntegerType();
3143 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
3145 has_affine_break = scop &&
3146 pet_scop_has_affine_skip(scop, pet_skip_later);
3147 if (has_affine_break)
3148 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
3149 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
3150 if (has_var_break)
3151 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
3153 if (pa && !is_nested_allowed(pa, scop)) {
3154 isl_pw_aff_free(pa);
3155 pa = NULL;
3158 if (!allow_nested && !pa)
3159 pa = try_extract_affine_condition(stmt->getCond());
3160 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3161 cond = isl_pw_aff_non_zero_set(pa);
3162 if (allow_nested && !cond) {
3163 isl_multi_pw_aff *test_index;
3164 int save_n_stmt = n_stmt;
3165 test_index = create_test_index(ctx, n_test++);
3166 n_stmt = stmt_id;
3167 scop_cond = extract_non_affine_condition(stmt->getCond(),
3168 n_stmt++, isl_multi_pw_aff_copy(test_index));
3169 n_stmt = save_n_stmt;
3170 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
3171 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
3172 isl_dim_out);
3173 isl_multi_pw_aff_free(test_index);
3174 scop_cond = pet_scop_prefix(scop_cond, 0);
3175 scop = pet_scop_reset_context(scop);
3176 scop = pet_scop_prefix(scop, 1);
3177 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
3180 cond = embed(cond, isl_id_copy(id));
3181 skip = embed(skip, isl_id_copy(id));
3182 valid_cond = isl_set_coalesce(valid_cond);
3183 valid_cond = embed(valid_cond, isl_id_copy(id));
3184 valid_inc = embed(valid_inc, isl_id_copy(id));
3185 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
3186 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
3188 valid_cond_init = enforce_subset(
3189 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
3190 isl_set_copy(valid_cond));
3191 if (is_one && !is_virtual) {
3192 isl_pw_aff_free(init_val);
3193 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
3194 lhs, rhs, init);
3195 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3196 valid_init = set_project_out_by_id(valid_init, id);
3197 domain = isl_pw_aff_non_zero_set(pa);
3198 } else {
3199 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
3200 domain = strided_domain(isl_id_copy(id), init_val,
3201 isl_val_copy(inc));
3204 domain = embed(domain, isl_id_copy(id));
3205 if (is_virtual) {
3206 isl_map *rev_wrap;
3207 wrap = compute_wrapping(isl_set_get_space(cond), iv);
3208 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
3209 rev_wrap = isl_map_reverse(rev_wrap);
3210 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
3211 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
3212 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
3213 valid_inc = isl_set_apply(valid_inc, rev_wrap);
3215 is_simple = is_simple_bound(cond, inc);
3216 if (!is_simple) {
3217 cond = isl_set_gist(cond, isl_set_copy(domain));
3218 is_simple = is_simple_bound(cond, inc);
3220 if (!is_simple)
3221 cond = valid_for_each_iteration(cond,
3222 isl_set_copy(domain), isl_val_copy(inc));
3223 domain = isl_set_intersect(domain, cond);
3224 if (has_affine_break) {
3225 skip = isl_set_intersect(skip , isl_set_copy(domain));
3226 skip = after(skip, isl_val_sgn(inc));
3227 domain = isl_set_subtract(domain, skip);
3229 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
3230 ls = isl_local_space_from_space(isl_set_get_space(domain));
3231 sched = isl_aff_var_on_domain(ls, isl_dim_set, 0);
3232 if (isl_val_is_neg(inc))
3233 sched = isl_aff_neg(sched);
3235 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
3236 isl_val_copy(inc));
3237 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
3239 if (!is_virtual)
3240 wrap = identity_aff(domain);
3242 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
3243 isl_aff_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
3244 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
3245 scop = resolve_nested(scop);
3246 if (has_var_break)
3247 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
3248 isl_val_copy(inc));
3249 if (id_test) {
3250 scop = scop_add_while(scop_cond, scop, id_test, domain,
3251 isl_val_copy(inc));
3252 isl_set_free(valid_inc);
3253 } else {
3254 scop = pet_scop_restrict_context(scop, valid_inc);
3255 scop = pet_scop_restrict_context(scop, valid_cond_next);
3256 scop = pet_scop_restrict_context(scop, valid_cond_init);
3257 isl_set_free(domain);
3259 clear_assignment(assigned_value, iv);
3261 isl_val_free(inc);
3263 scop = pet_scop_restrict_context(scop, valid_init);
3265 return scop;
3268 /* Try and construct a pet_scop corresponding to a compound statement.
3270 * "skip_declarations" is set if we should skip initial declarations
3271 * in the children of the compound statements. This then implies
3272 * that this sequence of children should not be treated as a block
3273 * since the initial statements may be skipped.
3275 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
3277 return extract(stmt->children(), !skip_declarations, skip_declarations);
3280 /* For each nested access parameter in "space",
3281 * construct a corresponding pet_expr, place it in args and
3282 * record its position in "param2pos".
3283 * "n_arg" is the number of elements that are already in args.
3284 * The position recorded in "param2pos" takes this number into account.
3285 * If the pet_expr corresponding to a parameter is identical to
3286 * the pet_expr corresponding to an earlier parameter, then these two
3287 * parameters are made to refer to the same element in args.
3289 * Return the final number of elements in args or -1 if an error has occurred.
3291 int PetScan::extract_nested(__isl_keep isl_space *space,
3292 int n_arg, pet_expr **args, std::map<int,int> &param2pos)
3294 int nparam;
3296 nparam = isl_space_dim(space, isl_dim_param);
3297 for (int i = 0; i < nparam; ++i) {
3298 int j;
3299 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3300 Expr *nested;
3302 if (!pet_nested_in_id(id)) {
3303 isl_id_free(id);
3304 continue;
3307 nested = (Expr *) isl_id_get_user(id);
3308 args[n_arg] = extract_expr(nested);
3309 isl_id_free(id);
3310 if (!args[n_arg])
3311 return -1;
3313 for (j = 0; j < n_arg; ++j)
3314 if (pet_expr_is_equal(args[j], args[n_arg]))
3315 break;
3317 if (j < n_arg) {
3318 pet_expr_free(args[n_arg]);
3319 args[n_arg] = NULL;
3320 param2pos[i] = j;
3321 } else
3322 param2pos[i] = n_arg++;
3325 return n_arg;
3328 /* For each nested access parameter in the access relations in "expr",
3329 * construct a corresponding pet_expr, place it in the arguments of "expr"
3330 * and record its position in "param2pos".
3331 * n is the number of nested access parameters.
3333 __isl_give pet_expr *PetScan::extract_nested(__isl_take pet_expr *expr, int n,
3334 std::map<int,int> &param2pos)
3336 isl_space *space;
3337 int i;
3338 pet_expr **args;
3340 args = isl_calloc_array(ctx, pet_expr *, n);
3341 if (!args)
3342 return pet_expr_free(expr);
3344 space = pet_expr_access_get_parameter_space(expr);
3345 n = extract_nested(space, 0, args, param2pos);
3346 isl_space_free(space);
3348 if (n < 0)
3349 expr = pet_expr_free(expr);
3350 else
3351 expr = pet_expr_set_n_arg(expr, n);
3353 for (i = 0; i < n; ++i)
3354 expr = pet_expr_set_arg(expr, i, args[i]);
3355 free(args);
3357 return expr;
3360 /* Look for parameters in any access relation in "expr" that
3361 * refer to nested accesses. In particular, these are
3362 * parameters with no name.
3364 * If there are any such parameters, then the domain of the index
3365 * expression and the access relation, which is still [] at this point,
3366 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
3367 * (after identifying identical nested accesses).
3369 * This transformation is performed in several steps.
3370 * We first extract the arguments in extract_nested.
3371 * param2pos maps the original parameter position to the position
3372 * of the argument.
3373 * Then we move these parameters to input dimensions.
3374 * t2pos maps the positions of these temporary input dimensions
3375 * to the positions of the corresponding arguments.
3376 * Finally, we express these temporary dimensions in terms of the domain
3377 * [[] -> [t_1,...,t_n]] and precompose index expression and access
3378 * relations with this function.
3380 __isl_give pet_expr *PetScan::resolve_nested(__isl_take pet_expr *expr)
3382 int n;
3383 int nparam;
3384 isl_space *space;
3385 isl_local_space *ls;
3386 isl_aff *aff;
3387 isl_multi_aff *ma;
3388 std::map<int,int> param2pos;
3389 std::map<int,int> t2pos;
3391 if (!expr)
3392 return expr;
3394 n = pet_expr_get_n_arg(expr);
3395 for (int i = 0; i < n; ++i) {
3396 pet_expr *arg;
3397 arg = pet_expr_get_arg(expr, i);
3398 arg = resolve_nested(arg);
3399 expr = pet_expr_set_arg(expr, i, arg);
3402 if (pet_expr_get_type(expr) != pet_expr_access)
3403 return expr;
3405 space = pet_expr_access_get_parameter_space(expr);
3406 n = pet_nested_n_in_space(space);
3407 isl_space_free(space);
3408 if (n == 0)
3409 return expr;
3411 expr = extract_nested(expr, n, param2pos);
3412 if (!expr)
3413 return NULL;
3415 expr = pet_expr_access_align_params(expr);
3416 if (!expr)
3417 return NULL;
3419 n = 0;
3420 space = pet_expr_access_get_parameter_space(expr);
3421 nparam = isl_space_dim(space, isl_dim_param);
3422 for (int i = nparam - 1; i >= 0; --i) {
3423 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3424 if (!pet_nested_in_id(id)) {
3425 isl_id_free(id);
3426 continue;
3429 expr = pet_expr_access_move_dims(expr,
3430 isl_dim_in, n, isl_dim_param, i, 1);
3431 t2pos[n] = param2pos[i];
3432 n++;
3434 isl_id_free(id);
3436 isl_space_free(space);
3438 space = pet_expr_access_get_parameter_space(expr);
3439 space = isl_space_set_from_params(space);
3440 space = isl_space_add_dims(space, isl_dim_set,
3441 pet_expr_get_n_arg(expr));
3442 space = isl_space_wrap(isl_space_from_range(space));
3443 ls = isl_local_space_from_space(isl_space_copy(space));
3444 space = isl_space_from_domain(space);
3445 space = isl_space_add_dims(space, isl_dim_out, n);
3446 ma = isl_multi_aff_zero(space);
3448 for (int i = 0; i < n; ++i) {
3449 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3450 isl_dim_set, t2pos[i]);
3451 ma = isl_multi_aff_set_aff(ma, i, aff);
3453 isl_local_space_free(ls);
3455 expr = pet_expr_access_pullback_multi_aff(expr, ma);
3457 return expr;
3460 /* Return the file offset of the expansion location of "Loc".
3462 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3464 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3467 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3469 /* Return a SourceLocation for the location after the first semicolon
3470 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3471 * call it and also skip trailing spaces and newline.
3473 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3474 const LangOptions &LO)
3476 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3479 #else
3481 /* Return a SourceLocation for the location after the first semicolon
3482 * after "loc". If Lexer::findLocationAfterToken is not available,
3483 * we look in the underlying character data for the first semicolon.
3485 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3486 const LangOptions &LO)
3488 const char *semi;
3489 const char *s = SM.getCharacterData(loc);
3491 semi = strchr(s, ';');
3492 if (!semi)
3493 return SourceLocation();
3494 return loc.getFileLocWithOffset(semi + 1 - s);
3497 #endif
3499 /* If the token at "loc" is the first token on the line, then return
3500 * a location referring to the start of the line.
3501 * Otherwise, return "loc".
3503 * This function is used to extend a scop to the start of the line
3504 * if the first token of the scop is also the first token on the line.
3506 * We look for the first token on the line. If its location is equal to "loc",
3507 * then the latter is the location of the first token on the line.
3509 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3510 SourceManager &SM, const LangOptions &LO)
3512 std::pair<FileID, unsigned> file_offset_pair;
3513 llvm::StringRef file;
3514 const char *pos;
3515 Token tok;
3516 SourceLocation token_loc, line_loc;
3517 int col;
3519 loc = SM.getExpansionLoc(loc);
3520 col = SM.getExpansionColumnNumber(loc);
3521 line_loc = loc.getLocWithOffset(1 - col);
3522 file_offset_pair = SM.getDecomposedLoc(line_loc);
3523 file = SM.getBufferData(file_offset_pair.first, NULL);
3524 pos = file.data() + file_offset_pair.second;
3526 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3527 file.begin(), pos, file.end());
3528 lexer.LexFromRawLexer(tok);
3529 token_loc = tok.getLocation();
3531 if (token_loc == loc)
3532 return line_loc;
3533 else
3534 return loc;
3537 /* Update start and end of "scop" to include the region covered by "range".
3538 * If "skip_semi" is set, then we assume "range" is followed by
3539 * a semicolon and also include this semicolon.
3541 struct pet_scop *PetScan::update_scop_start_end(struct pet_scop *scop,
3542 SourceRange range, bool skip_semi)
3544 SourceLocation loc = range.getBegin();
3545 SourceManager &SM = PP.getSourceManager();
3546 const LangOptions &LO = PP.getLangOpts();
3547 unsigned start, end;
3549 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3550 start = getExpansionOffset(SM, loc);
3551 loc = range.getEnd();
3552 if (skip_semi)
3553 loc = location_after_semi(loc, SM, LO);
3554 else
3555 loc = PP.getLocForEndOfToken(loc);
3556 end = getExpansionOffset(SM, loc);
3558 scop = pet_scop_update_start_end(scop, start, end);
3559 return scop;
3562 /* Convert a top-level pet_expr to a pet_scop with one statement.
3563 * This mainly involves resolving nested expression parameters
3564 * and setting the name of the iteration space.
3565 * The name is given by "label" if it is non-NULL. Otherwise,
3566 * it is of the form S_<n_stmt>.
3567 * start and end of the pet_scop are derived from those of "stmt".
3568 * If "stmt" is an expression statement, then its range does not
3569 * include the semicolon, while it should be included in the pet_scop.
3571 struct pet_scop *PetScan::extract(Stmt *stmt, __isl_take pet_expr *expr,
3572 __isl_take isl_id *label)
3574 struct pet_stmt *ps;
3575 struct pet_scop *scop;
3576 SourceLocation loc = stmt->getLocStart();
3577 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3578 bool skip_semi;
3580 expr = resolve_nested(expr);
3581 ps = pet_stmt_from_pet_expr(line, label, n_stmt++, expr);
3582 scop = pet_scop_from_pet_stmt(ctx, ps);
3584 skip_semi = isa<Expr>(stmt);
3585 scop = update_scop_start_end(scop, stmt->getSourceRange(), skip_semi);
3586 return scop;
3589 /* Check if we can extract an affine expression from "expr".
3590 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3591 * We turn on autodetection so that we won't generate any warnings
3592 * and turn off nesting, so that we won't accept any non-affine constructs.
3594 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3596 isl_pw_aff *pwaff;
3597 int save_autodetect = options->autodetect;
3598 bool save_nesting = nesting_enabled;
3600 options->autodetect = 1;
3601 nesting_enabled = false;
3603 pwaff = extract_affine(expr);
3605 options->autodetect = save_autodetect;
3606 nesting_enabled = save_nesting;
3608 return pwaff;
3611 /* Check if we can extract an affine constraint from "expr".
3612 * Return the constraint as an isl_set if we can and NULL otherwise.
3613 * We turn on autodetection so that we won't generate any warnings
3614 * and turn off nesting, so that we won't accept any non-affine constructs.
3616 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3618 isl_pw_aff *cond;
3619 int save_autodetect = options->autodetect;
3620 bool save_nesting = nesting_enabled;
3622 options->autodetect = 1;
3623 nesting_enabled = false;
3625 cond = extract_condition(expr);
3627 options->autodetect = save_autodetect;
3628 nesting_enabled = save_nesting;
3630 return cond;
3633 /* Check whether "expr" is an affine constraint.
3635 bool PetScan::is_affine_condition(Expr *expr)
3637 isl_pw_aff *cond;
3639 cond = try_extract_affine_condition(expr);
3640 isl_pw_aff_free(cond);
3642 return cond != NULL;
3645 /* Check if we can extract a condition from "expr".
3646 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3647 * If allow_nested is set, then the condition may involve parameters
3648 * corresponding to nested accesses.
3649 * We turn on autodetection so that we won't generate any warnings.
3651 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3653 isl_pw_aff *cond;
3654 int save_autodetect = options->autodetect;
3655 bool save_nesting = nesting_enabled;
3657 options->autodetect = 1;
3658 nesting_enabled = allow_nested;
3659 cond = extract_condition(expr);
3661 options->autodetect = save_autodetect;
3662 nesting_enabled = save_nesting;
3664 return cond;
3667 /* If the top-level expression of "stmt" is an assignment, then
3668 * return that assignment as a BinaryOperator.
3669 * Otherwise return NULL.
3671 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3673 BinaryOperator *ass;
3675 if (!stmt)
3676 return NULL;
3677 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3678 return NULL;
3680 ass = cast<BinaryOperator>(stmt);
3681 if(ass->getOpcode() != BO_Assign)
3682 return NULL;
3684 return ass;
3687 /* Check if the given if statement is a conditional assignement
3688 * with a non-affine condition. If so, construct a pet_scop
3689 * corresponding to this conditional assignment. Otherwise return NULL.
3691 * In particular we check if "stmt" is of the form
3693 * if (condition)
3694 * a = f(...);
3695 * else
3696 * a = g(...);
3698 * where a is some array or scalar access.
3699 * The constructed pet_scop then corresponds to the expression
3701 * a = condition ? f(...) : g(...)
3703 * All access relations in f(...) are intersected with condition
3704 * while all access relation in g(...) are intersected with the complement.
3706 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3708 BinaryOperator *ass_then, *ass_else;
3709 isl_multi_pw_aff *write_then, *write_else;
3710 isl_set *cond, *comp;
3711 isl_multi_pw_aff *index;
3712 isl_pw_aff *pa;
3713 int equal;
3714 pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3715 bool save_nesting = nesting_enabled;
3717 if (!options->detect_conditional_assignment)
3718 return NULL;
3720 ass_then = top_assignment_or_null(stmt->getThen());
3721 ass_else = top_assignment_or_null(stmt->getElse());
3723 if (!ass_then || !ass_else)
3724 return NULL;
3726 if (is_affine_condition(stmt->getCond()))
3727 return NULL;
3729 write_then = extract_index(ass_then->getLHS());
3730 write_else = extract_index(ass_else->getLHS());
3732 equal = isl_multi_pw_aff_plain_is_equal(write_then, write_else);
3733 isl_multi_pw_aff_free(write_else);
3734 if (equal < 0 || !equal) {
3735 isl_multi_pw_aff_free(write_then);
3736 return NULL;
3739 nesting_enabled = allow_nested;
3740 pa = extract_condition(stmt->getCond());
3741 nesting_enabled = save_nesting;
3742 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3743 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3744 index = isl_multi_pw_aff_from_range(isl_multi_pw_aff_from_pw_aff(pa));
3746 pe_cond = pet_expr_from_index(index);
3748 pe_then = extract_expr(ass_then->getRHS());
3749 pe_then = pet_expr_restrict(pe_then, cond);
3750 pe_else = extract_expr(ass_else->getRHS());
3751 pe_else = pet_expr_restrict(pe_else, comp);
3753 pe = pet_expr_new_ternary(pe_cond, pe_then, pe_else);
3754 pe_write = pet_expr_from_index_and_depth(write_then,
3755 extract_depth(write_then));
3756 pe_write = pet_expr_access_set_write(pe_write, 1);
3757 pe_write = pet_expr_access_set_read(pe_write, 0);
3758 pe = pet_expr_new_binary(pet_op_assign, pe_write, pe);
3759 return extract(stmt, pe);
3762 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3763 * evaluating "cond" and writing the result to a virtual scalar,
3764 * as expressed by "index".
3766 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond, int stmt_nr,
3767 __isl_take isl_multi_pw_aff *index)
3769 pet_expr *expr, *write;
3770 struct pet_stmt *ps;
3771 SourceLocation loc = cond->getLocStart();
3772 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3774 write = pet_expr_from_index(index);
3775 write = pet_expr_access_set_write(write, 1);
3776 write = pet_expr_access_set_read(write, 0);
3777 expr = extract_expr(cond);
3778 expr = resolve_nested(expr);
3779 expr = pet_expr_new_binary(pet_op_assign, write, expr);
3780 ps = pet_stmt_from_pet_expr(line, NULL, stmt_nr, expr);
3781 return pet_scop_from_pet_stmt(ctx, ps);
3784 extern "C" {
3785 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr,
3786 void *user);
3789 /* Precompose the access relation and the index expression associated
3790 * to "expr" with the function pointed to by "user",
3791 * thereby embedding the access relation in the domain of this function.
3792 * The initial domain of the access relation and the index expression
3793 * is the zero-dimensional domain.
3795 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr, void *user)
3797 isl_multi_aff *ma = (isl_multi_aff *) user;
3799 return pet_expr_access_pullback_multi_aff(expr, isl_multi_aff_copy(ma));
3802 /* Precompose all access relations in "expr" with "ma", thereby
3803 * embedding them in the domain of "ma".
3805 static __isl_give pet_expr *embed(__isl_take pet_expr *expr,
3806 __isl_keep isl_multi_aff *ma)
3808 return pet_expr_map_access(expr, &embed_access, ma);
3811 /* For each nested access parameter in the domain of "stmt",
3812 * construct a corresponding pet_expr, place it before the original
3813 * elements in stmt->args and record its position in "param2pos".
3814 * n is the number of nested access parameters.
3816 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3817 std::map<int,int> &param2pos)
3819 int i;
3820 isl_space *space;
3821 int n_arg;
3822 pet_expr **args;
3824 n_arg = stmt->n_arg;
3825 args = isl_calloc_array(ctx, pet_expr *, n + n_arg);
3826 if (!args)
3827 goto error;
3829 space = isl_set_get_space(stmt->domain);
3830 n_arg = extract_nested(space, 0, args, param2pos);
3831 isl_space_free(space);
3833 if (n_arg < 0)
3834 goto error;
3836 for (i = 0; i < stmt->n_arg; ++i)
3837 args[n_arg + i] = stmt->args[i];
3838 free(stmt->args);
3839 stmt->args = args;
3840 stmt->n_arg += n_arg;
3842 return stmt;
3843 error:
3844 if (args) {
3845 for (i = 0; i < n; ++i)
3846 pet_expr_free(args[i]);
3847 free(args);
3849 pet_stmt_free(stmt);
3850 return NULL;
3853 /* Check whether any of the arguments i of "stmt" starting at position "n"
3854 * is equal to one of the first "n" arguments j.
3855 * If so, combine the constraints on arguments i and j and remove
3856 * argument i.
3858 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3860 int i, j;
3861 isl_map *map;
3863 if (!stmt)
3864 return NULL;
3865 if (n == 0)
3866 return stmt;
3867 if (n == stmt->n_arg)
3868 return stmt;
3870 map = isl_set_unwrap(stmt->domain);
3872 for (i = stmt->n_arg - 1; i >= n; --i) {
3873 for (j = 0; j < n; ++j)
3874 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3875 break;
3876 if (j >= n)
3877 continue;
3879 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3880 map = isl_map_project_out(map, isl_dim_out, i, 1);
3882 pet_expr_free(stmt->args[i]);
3883 for (j = i; j + 1 < stmt->n_arg; ++j)
3884 stmt->args[j] = stmt->args[j + 1];
3885 stmt->n_arg--;
3888 stmt->domain = isl_map_wrap(map);
3889 if (!stmt->domain)
3890 goto error;
3891 return stmt;
3892 error:
3893 pet_stmt_free(stmt);
3894 return NULL;
3897 /* Look for parameters in the iteration domain of "stmt" that
3898 * refer to nested accesses. In particular, these are
3899 * parameters with no name.
3901 * If there are any such parameters, then as many extra variables
3902 * (after identifying identical nested accesses) are inserted in the
3903 * range of the map wrapped inside the domain, before the original variables.
3904 * If the original domain is not a wrapped map, then a new wrapped
3905 * map is created with zero output dimensions.
3906 * The parameters are then equated to the corresponding output dimensions
3907 * and subsequently projected out, from the iteration domain,
3908 * the schedule and the access relations.
3909 * For each of the output dimensions, a corresponding argument
3910 * expression is inserted. Initially they are created with
3911 * a zero-dimensional domain, so they have to be embedded
3912 * in the current iteration domain.
3913 * param2pos maps the position of the parameter to the position
3914 * of the corresponding output dimension in the wrapped map.
3916 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3918 int n;
3919 int nparam;
3920 unsigned n_arg;
3921 isl_map *map;
3922 isl_space *space;
3923 isl_multi_aff *ma;
3924 std::map<int,int> param2pos;
3926 if (!stmt)
3927 return NULL;
3929 n = pet_nested_n_in_set(stmt->domain);
3930 if (n == 0)
3931 return stmt;
3933 n_arg = stmt->n_arg;
3934 stmt = extract_nested(stmt, n, param2pos);
3935 if (!stmt)
3936 return NULL;
3938 n = stmt->n_arg - n_arg;
3939 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3940 if (isl_set_is_wrapping(stmt->domain))
3941 map = isl_set_unwrap(stmt->domain);
3942 else
3943 map = isl_map_from_domain(stmt->domain);
3944 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3946 for (int i = nparam - 1; i >= 0; --i) {
3947 isl_id *id;
3949 if (!pet_nested_in_map(map, i))
3950 continue;
3952 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
3953 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3954 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3955 param2pos[i]);
3956 map = isl_map_project_out(map, isl_dim_param, i, 1);
3959 stmt->domain = isl_map_wrap(map);
3961 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
3962 space = isl_space_from_domain(isl_space_domain(space));
3963 ma = isl_multi_aff_zero(space);
3964 for (int pos = 0; pos < n; ++pos)
3965 stmt->args[pos] = embed(stmt->args[pos], ma);
3966 isl_multi_aff_free(ma);
3968 stmt = pet_stmt_remove_nested_parameters(stmt);
3969 stmt = remove_duplicate_arguments(stmt, n);
3971 return stmt;
3974 /* For each statement in "scop", move the parameters that correspond
3975 * to nested access into the ranges of the domains and create
3976 * corresponding argument expressions.
3978 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3980 if (!scop)
3981 return NULL;
3983 for (int i = 0; i < scop->n_stmt; ++i) {
3984 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3985 if (!scop->stmts[i])
3986 goto error;
3989 return scop;
3990 error:
3991 pet_scop_free(scop);
3992 return NULL;
3995 /* Given an access expression "expr", is the variable accessed by
3996 * "expr" assigned anywhere inside "scop"?
3998 static bool is_assigned(__isl_keep pet_expr *expr, pet_scop *scop)
4000 bool assigned = false;
4001 isl_id *id;
4003 id = pet_expr_access_get_id(expr);
4004 assigned = pet_scop_writes(scop, id);
4005 isl_id_free(id);
4007 return assigned;
4010 /* Are all nested access parameters in "pa" allowed given "scop".
4011 * In particular, is none of them written by anywhere inside "scop".
4013 * If "scop" has any skip conditions, then no nested access parameters
4014 * are allowed. In particular, if there is any nested access in a guard
4015 * for a piece of code containing a "continue", then we want to introduce
4016 * a separate statement for evaluating this guard so that we can express
4017 * that the result is false for all previous iterations.
4019 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
4021 int nparam;
4023 if (!scop)
4024 return true;
4026 if (!pet_nested_any_in_pw_aff(pa))
4027 return true;
4029 if (pet_scop_has_skip(scop, pet_skip_now))
4030 return false;
4032 nparam = isl_pw_aff_dim(pa, isl_dim_param);
4033 for (int i = 0; i < nparam; ++i) {
4034 Expr *nested;
4035 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
4036 pet_expr *expr;
4037 bool allowed;
4039 if (!pet_nested_in_id(id)) {
4040 isl_id_free(id);
4041 continue;
4044 nested = (Expr *) isl_id_get_user(id);
4045 expr = extract_expr(nested);
4046 allowed = pet_expr_get_type(expr) == pet_expr_access &&
4047 !is_assigned(expr, scop);
4049 pet_expr_free(expr);
4050 isl_id_free(id);
4052 if (!allowed)
4053 return false;
4056 return true;
4059 /* Do we need to construct a skip condition of the given type
4060 * on an if statement, given that the if condition is non-affine?
4062 * pet_scop_filter_skip can only handle the case where the if condition
4063 * holds (the then branch) and the skip condition is universal.
4064 * In any other case, we need to construct a new skip condition.
4066 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
4067 bool have_else, enum pet_skip type)
4069 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
4070 return true;
4071 if (scop_then && pet_scop_has_skip(scop_then, type) &&
4072 !pet_scop_has_universal_skip(scop_then, type))
4073 return true;
4074 return false;
4077 /* Do we need to construct a skip condition of the given type
4078 * on an if statement, given that the if condition is affine?
4080 * There is no need to construct a new skip condition if all
4081 * the skip conditions are affine.
4083 static bool need_skip_aff(struct pet_scop *scop_then,
4084 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
4086 if (scop_then && pet_scop_has_var_skip(scop_then, type))
4087 return true;
4088 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
4089 return true;
4090 return false;
4093 /* Do we need to construct a skip condition of the given type
4094 * on an if statement?
4096 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
4097 bool have_else, enum pet_skip type, bool affine)
4099 if (affine)
4100 return need_skip_aff(scop_then, scop_else, have_else, type);
4101 else
4102 return need_skip(scop_then, scop_else, have_else, type);
4105 /* Construct an affine expression pet_expr that evaluates
4106 * to the constant "val".
4108 static __isl_give pet_expr *universally(isl_ctx *ctx, int val)
4110 isl_local_space *ls;
4111 isl_aff *aff;
4112 isl_multi_pw_aff *mpa;
4114 ls = isl_local_space_from_space(isl_space_set_alloc(ctx, 0, 0));
4115 aff = isl_aff_val_on_domain(ls, isl_val_int_from_si(ctx, val));
4116 mpa = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4118 return pet_expr_from_index(mpa);
4121 /* Construct an affine expression pet_expr that evaluates
4122 * to the constant 1.
4124 static __isl_give pet_expr *universally_true(isl_ctx *ctx)
4126 return universally(ctx, 1);
4129 /* Construct an affine expression pet_expr that evaluates
4130 * to the constant 0.
4132 static __isl_give pet_expr *universally_false(isl_ctx *ctx)
4134 return universally(ctx, 0);
4137 /* Given an index expression "test_index" for the if condition,
4138 * an index expression "skip_index" for the skip condition and
4139 * scops for the then and else branches, construct a scop for
4140 * computing "skip_index".
4142 * The computed scop contains a single statement that essentially does
4144 * skip_index = test_cond ? skip_cond_then : skip_cond_else
4146 * If the skip conditions of the then and/or else branch are not affine,
4147 * then they need to be filtered by test_index.
4148 * If they are missing, then this means the skip condition is false.
4150 * Since we are constructing a skip condition for the if statement,
4151 * the skip conditions on the then and else branches are removed.
4153 static struct pet_scop *extract_skip(PetScan *scan,
4154 __isl_take isl_multi_pw_aff *test_index,
4155 __isl_take isl_multi_pw_aff *skip_index,
4156 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
4157 enum pet_skip type)
4159 pet_expr *expr_then, *expr_else, *expr, *expr_skip;
4160 struct pet_stmt *stmt;
4161 struct pet_scop *scop;
4162 isl_ctx *ctx = scan->ctx;
4164 if (!scop_then)
4165 goto error;
4166 if (have_else && !scop_else)
4167 goto error;
4169 if (pet_scop_has_skip(scop_then, type)) {
4170 expr_then = pet_scop_get_skip_expr(scop_then, type);
4171 pet_scop_reset_skip(scop_then, type);
4172 if (!pet_expr_is_affine(expr_then))
4173 expr_then = pet_expr_filter(expr_then,
4174 isl_multi_pw_aff_copy(test_index), 1);
4175 } else
4176 expr_then = universally_false(ctx);
4178 if (have_else && pet_scop_has_skip(scop_else, type)) {
4179 expr_else = pet_scop_get_skip_expr(scop_else, type);
4180 pet_scop_reset_skip(scop_else, type);
4181 if (!pet_expr_is_affine(expr_else))
4182 expr_else = pet_expr_filter(expr_else,
4183 isl_multi_pw_aff_copy(test_index), 0);
4184 } else
4185 expr_else = universally_false(ctx);
4187 expr = pet_expr_from_index(test_index);
4188 expr = pet_expr_new_ternary(expr, expr_then, expr_else);
4189 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4190 expr_skip = pet_expr_access_set_write(expr_skip, 1);
4191 expr_skip = pet_expr_access_set_read(expr_skip, 0);
4192 expr = pet_expr_new_binary(pet_op_assign, expr_skip, expr);
4193 stmt = pet_stmt_from_pet_expr(-1, NULL, scan->n_stmt++, expr);
4195 scop = pet_scop_from_pet_stmt(ctx, stmt);
4196 scop = scop_add_array(scop, skip_index, scan->ast_context);
4197 isl_multi_pw_aff_free(skip_index);
4199 return scop;
4200 error:
4201 isl_multi_pw_aff_free(test_index);
4202 isl_multi_pw_aff_free(skip_index);
4203 return NULL;
4206 /* Is scop's skip_now condition equal to its skip_later condition?
4207 * In particular, this means that it either has no skip_now condition
4208 * or both a skip_now and a skip_later condition (that are equal to each other).
4210 static bool skip_equals_skip_later(struct pet_scop *scop)
4212 int has_skip_now, has_skip_later;
4213 int equal;
4214 isl_multi_pw_aff *skip_now, *skip_later;
4216 if (!scop)
4217 return false;
4218 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
4219 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
4220 if (has_skip_now != has_skip_later)
4221 return false;
4222 if (!has_skip_now)
4223 return true;
4225 skip_now = pet_scop_get_skip(scop, pet_skip_now);
4226 skip_later = pet_scop_get_skip(scop, pet_skip_later);
4227 equal = isl_multi_pw_aff_is_equal(skip_now, skip_later);
4228 isl_multi_pw_aff_free(skip_now);
4229 isl_multi_pw_aff_free(skip_later);
4231 return equal;
4234 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
4236 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
4238 pet_scop_reset_skip(scop1, pet_skip_later);
4239 pet_scop_reset_skip(scop2, pet_skip_later);
4242 /* Structure that handles the construction of skip conditions.
4244 * scop_then and scop_else represent the then and else branches
4245 * of the if statement
4247 * skip[type] is true if we need to construct a skip condition of that type
4248 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
4249 * are equal to each other
4250 * index[type] is an index expression from a zero-dimension domain
4251 * to the virtual array representing the skip condition
4252 * scop[type] is a scop for computing the skip condition
4254 struct pet_skip_info {
4255 isl_ctx *ctx;
4257 bool skip[2];
4258 bool equal;
4259 isl_multi_pw_aff *index[2];
4260 struct pet_scop *scop[2];
4262 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
4264 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
4267 /* Structure that handles the construction of skip conditions on if statements.
4269 * scop_then and scop_else represent the then and else branches
4270 * of the if statement
4272 struct pet_skip_info_if : public pet_skip_info {
4273 struct pet_scop *scop_then, *scop_else;
4274 bool have_else;
4276 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4277 struct pet_scop *scop_else, bool have_else, bool affine);
4278 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index,
4279 enum pet_skip type);
4280 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index);
4281 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
4282 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4283 int offset);
4284 struct pet_scop *add(struct pet_scop *scop, int offset);
4287 /* Initialize a pet_skip_info_if structure based on the then and else branches
4288 * and based on whether the if condition is affine or not.
4290 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4291 struct pet_scop *scop_else, bool have_else, bool affine) :
4292 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
4293 have_else(have_else)
4295 skip[pet_skip_now] =
4296 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
4297 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
4298 (!have_else || skip_equals_skip_later(scop_else));
4299 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4300 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
4303 /* If we need to construct a skip condition of the given type,
4304 * then do so now.
4306 * "mpa" represents the if condition.
4308 void pet_skip_info_if::extract(PetScan *scan,
4309 __isl_keep isl_multi_pw_aff *mpa, enum pet_skip type)
4311 isl_ctx *ctx;
4313 if (!skip[type])
4314 return;
4316 ctx = isl_multi_pw_aff_get_ctx(mpa);
4317 index[type] = create_test_index(ctx, scan->n_test++);
4318 scop[type] = extract_skip(scan, isl_multi_pw_aff_copy(mpa),
4319 isl_multi_pw_aff_copy(index[type]),
4320 scop_then, scop_else, have_else, type);
4323 /* Construct the required skip conditions, given the if condition "index".
4325 void pet_skip_info_if::extract(PetScan *scan,
4326 __isl_keep isl_multi_pw_aff *index)
4328 extract(scan, index, pet_skip_now);
4329 extract(scan, index, pet_skip_later);
4330 if (equal)
4331 drop_skip_later(scop_then, scop_else);
4334 /* Construct the required skip conditions, given the if condition "cond".
4336 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
4338 isl_multi_pw_aff *test;
4340 if (!skip[pet_skip_now] && !skip[pet_skip_later])
4341 return;
4343 test = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_copy(cond));
4344 test = isl_multi_pw_aff_from_range(test);
4345 extract(scan, test);
4346 isl_multi_pw_aff_free(test);
4349 /* Add the computed skip condition of the give type to "main" and
4350 * add the scop for computing the condition at the given offset.
4352 * If equal is set, then we only computed a skip condition for pet_skip_now,
4353 * but we also need to set it as main's pet_skip_later.
4355 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
4356 enum pet_skip type, int offset)
4358 if (!skip[type])
4359 return main;
4361 scop[type] = pet_scop_prefix(scop[type], offset);
4362 main = pet_scop_add_par(ctx, main, scop[type]);
4363 scop[type] = NULL;
4365 if (equal)
4366 main = pet_scop_set_skip(main, pet_skip_later,
4367 isl_multi_pw_aff_copy(index[type]));
4369 main = pet_scop_set_skip(main, type, index[type]);
4370 index[type] = NULL;
4372 return main;
4375 /* Add the computed skip conditions to "main" and
4376 * add the scops for computing the conditions at the given offset.
4378 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
4380 scop = add(scop, pet_skip_now, offset);
4381 scop = add(scop, pet_skip_later, offset);
4383 return scop;
4386 /* Construct a pet_scop for a non-affine if statement.
4388 * We create a separate statement that writes the result
4389 * of the non-affine condition to a virtual scalar.
4390 * A constraint requiring the value of this virtual scalar to be one
4391 * is added to the iteration domains of the then branch.
4392 * Similarly, a constraint requiring the value of this virtual scalar
4393 * to be zero is added to the iteration domains of the else branch, if any.
4394 * We adjust the schedules to ensure that the virtual scalar is written
4395 * before it is read.
4397 * If there are any breaks or continues in the then and/or else
4398 * branches, then we may have to compute a new skip condition.
4399 * This is handled using a pet_skip_info_if object.
4400 * On initialization, the object checks if skip conditions need
4401 * to be computed. If so, it does so in "extract" and adds them in "add".
4403 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
4404 struct pet_scop *scop_then, struct pet_scop *scop_else,
4405 bool have_else, int stmt_id)
4407 struct pet_scop *scop;
4408 isl_multi_pw_aff *test_index;
4409 int save_n_stmt = n_stmt;
4411 test_index = create_test_index(ctx, n_test++);
4412 n_stmt = stmt_id;
4413 scop = extract_non_affine_condition(cond, n_stmt++,
4414 isl_multi_pw_aff_copy(test_index));
4415 n_stmt = save_n_stmt;
4416 scop = scop_add_array(scop, test_index, ast_context);
4418 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
4419 skip.extract(this, test_index);
4421 scop = pet_scop_prefix(scop, 0);
4422 scop_then = pet_scop_prefix(scop_then, 1);
4423 scop_then = pet_scop_filter(scop_then,
4424 isl_multi_pw_aff_copy(test_index), 1);
4425 if (have_else) {
4426 scop_else = pet_scop_prefix(scop_else, 1);
4427 scop_else = pet_scop_filter(scop_else, test_index, 0);
4428 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
4429 } else
4430 isl_multi_pw_aff_free(test_index);
4432 scop = pet_scop_add_seq(ctx, scop, scop_then);
4434 scop = skip.add(scop, 2);
4436 return scop;
4439 /* Construct a pet_scop for an if statement.
4441 * If the condition fits the pattern of a conditional assignment,
4442 * then it is handled by extract_conditional_assignment.
4443 * Otherwise, we do the following.
4445 * If the condition is affine, then the condition is added
4446 * to the iteration domains of the then branch, while the
4447 * opposite of the condition in added to the iteration domains
4448 * of the else branch, if any.
4449 * We allow the condition to be dynamic, i.e., to refer to
4450 * scalars or array elements that may be written to outside
4451 * of the given if statement. These nested accesses are then represented
4452 * as output dimensions in the wrapping iteration domain.
4453 * If it is also written _inside_ the then or else branch, then
4454 * we treat the condition as non-affine.
4455 * As explained in extract_non_affine_if, this will introduce
4456 * an extra statement.
4457 * For aesthetic reasons, we want this statement to have a statement
4458 * number that is lower than those of the then and else branches.
4459 * In order to evaluate if we will need such a statement, however, we
4460 * first construct scops for the then and else branches.
4461 * We therefore reserve a statement number if we might have to
4462 * introduce such an extra statement.
4464 * If the condition is not affine, then the scop is created in
4465 * extract_non_affine_if.
4467 * If there are any breaks or continues in the then and/or else
4468 * branches, then we may have to compute a new skip condition.
4469 * This is handled using a pet_skip_info_if object.
4470 * On initialization, the object checks if skip conditions need
4471 * to be computed. If so, it does so in "extract" and adds them in "add".
4473 struct pet_scop *PetScan::extract(IfStmt *stmt)
4475 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4476 isl_pw_aff *cond;
4477 int stmt_id;
4478 isl_set *set;
4479 isl_set *valid;
4481 clear_assignments clear(assigned_value);
4482 clear.TraverseStmt(stmt->getThen());
4483 if (stmt->getElse())
4484 clear.TraverseStmt(stmt->getElse());
4486 scop = extract_conditional_assignment(stmt);
4487 if (scop)
4488 return scop;
4490 cond = try_extract_nested_condition(stmt->getCond());
4491 if (allow_nested && (!cond || pet_nested_any_in_pw_aff(cond)))
4492 stmt_id = n_stmt++;
4495 assigned_value_cache cache(assigned_value);
4496 scop_then = extract(stmt->getThen());
4499 if (stmt->getElse()) {
4500 assigned_value_cache cache(assigned_value);
4501 scop_else = extract(stmt->getElse());
4502 if (options->autodetect) {
4503 if (scop_then && !scop_else) {
4504 partial = true;
4505 isl_pw_aff_free(cond);
4506 return scop_then;
4508 if (!scop_then && scop_else) {
4509 partial = true;
4510 isl_pw_aff_free(cond);
4511 return scop_else;
4516 if (cond &&
4517 (!is_nested_allowed(cond, scop_then) ||
4518 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4519 isl_pw_aff_free(cond);
4520 cond = NULL;
4522 if (allow_nested && !cond)
4523 return extract_non_affine_if(stmt->getCond(), scop_then,
4524 scop_else, stmt->getElse(), stmt_id);
4526 if (!cond)
4527 cond = extract_condition(stmt->getCond());
4529 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4530 skip.extract(this, cond);
4532 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4533 set = isl_pw_aff_non_zero_set(cond);
4534 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4536 if (stmt->getElse()) {
4537 set = isl_set_subtract(isl_set_copy(valid), set);
4538 scop_else = pet_scop_restrict(scop_else, set);
4539 scop = pet_scop_add_par(ctx, scop, scop_else);
4540 } else
4541 isl_set_free(set);
4542 scop = resolve_nested(scop);
4543 scop = pet_scop_restrict_context(scop, valid);
4545 if (skip)
4546 scop = pet_scop_prefix(scop, 0);
4547 scop = skip.add(scop, 1);
4549 return scop;
4552 /* Try and construct a pet_scop for a label statement.
4553 * We currently only allow labels on expression statements.
4555 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4557 isl_id *label;
4558 Stmt *sub;
4560 sub = stmt->getSubStmt();
4561 if (!isa<Expr>(sub)) {
4562 unsupported(stmt);
4563 return NULL;
4566 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4568 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4571 /* Return a one-dimensional multi piecewise affine expression that is equal
4572 * to the constant 1 and is defined over a zero-dimensional domain.
4574 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
4576 isl_space *space;
4577 isl_local_space *ls;
4578 isl_aff *aff;
4580 space = isl_space_set_alloc(ctx, 0, 0);
4581 ls = isl_local_space_from_space(space);
4582 aff = isl_aff_zero_on_domain(ls);
4583 aff = isl_aff_set_constant_si(aff, 1);
4585 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4588 /* Construct a pet_scop for a continue statement.
4590 * We simply create an empty scop with a universal pet_skip_now
4591 * skip condition. This skip condition will then be taken into
4592 * account by the enclosing loop construct, possibly after
4593 * being incorporated into outer skip conditions.
4595 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4597 pet_scop *scop;
4599 scop = pet_scop_empty(ctx);
4600 if (!scop)
4601 return NULL;
4603 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
4605 return scop;
4608 /* Construct a pet_scop for a break statement.
4610 * We simply create an empty scop with both a universal pet_skip_now
4611 * skip condition and a universal pet_skip_later skip condition.
4612 * These skip conditions will then be taken into
4613 * account by the enclosing loop construct, possibly after
4614 * being incorporated into outer skip conditions.
4616 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4618 pet_scop *scop;
4619 isl_multi_pw_aff *skip;
4621 scop = pet_scop_empty(ctx);
4622 if (!scop)
4623 return NULL;
4625 skip = one_mpa(ctx);
4626 scop = pet_scop_set_skip(scop, pet_skip_now,
4627 isl_multi_pw_aff_copy(skip));
4628 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
4630 return scop;
4633 /* Try and construct a pet_scop corresponding to "stmt".
4635 * If "stmt" is a compound statement, then "skip_declarations"
4636 * indicates whether we should skip initial declarations in the
4637 * compound statement.
4639 * If the constructed pet_scop is not a (possibly) partial representation
4640 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4641 * In particular, if skip_declarations is set, then we may have skipped
4642 * declarations inside "stmt" and so the pet_scop may not represent
4643 * the entire "stmt".
4644 * Note that this function may be called with "stmt" referring to the entire
4645 * body of the function, including the outer braces. In such cases,
4646 * skip_declarations will be set and the braces will not be taken into
4647 * account in scop->start and scop->end.
4649 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
4651 struct pet_scop *scop;
4653 if (isa<Expr>(stmt))
4654 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4656 switch (stmt->getStmtClass()) {
4657 case Stmt::WhileStmtClass:
4658 scop = extract(cast<WhileStmt>(stmt));
4659 break;
4660 case Stmt::ForStmtClass:
4661 scop = extract_for(cast<ForStmt>(stmt));
4662 break;
4663 case Stmt::IfStmtClass:
4664 scop = extract(cast<IfStmt>(stmt));
4665 break;
4666 case Stmt::CompoundStmtClass:
4667 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
4668 break;
4669 case Stmt::LabelStmtClass:
4670 scop = extract(cast<LabelStmt>(stmt));
4671 break;
4672 case Stmt::ContinueStmtClass:
4673 scop = extract(cast<ContinueStmt>(stmt));
4674 break;
4675 case Stmt::BreakStmtClass:
4676 scop = extract(cast<BreakStmt>(stmt));
4677 break;
4678 case Stmt::DeclStmtClass:
4679 scop = extract(cast<DeclStmt>(stmt));
4680 break;
4681 default:
4682 unsupported(stmt);
4683 return NULL;
4686 if (partial || skip_declarations)
4687 return scop;
4689 scop = update_scop_start_end(scop, stmt->getSourceRange(), false);
4691 return scop;
4694 /* Do we need to construct a skip condition of the given type
4695 * on a sequence of statements?
4697 * There is no need to construct a new skip condition if only
4698 * only of the two statements has a skip condition or if both
4699 * of their skip conditions are affine.
4701 * In principle we also don't need a new continuation variable if
4702 * the continuation of scop2 is affine, but then we would need
4703 * to allow more complicated forms of continuations.
4705 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4706 enum pet_skip type)
4708 if (!scop1 || !pet_scop_has_skip(scop1, type))
4709 return false;
4710 if (!scop2 || !pet_scop_has_skip(scop2, type))
4711 return false;
4712 if (pet_scop_has_affine_skip(scop1, type) &&
4713 pet_scop_has_affine_skip(scop2, type))
4714 return false;
4715 return true;
4718 /* Construct a scop for computing the skip condition of the given type and
4719 * with index expression "skip_index" for a sequence of two scops "scop1"
4720 * and "scop2".
4722 * The computed scop contains a single statement that essentially does
4724 * skip_index = skip_cond_1 ? 1 : skip_cond_2
4726 * or, in other words, skip_cond1 || skip_cond2.
4727 * In this expression, skip_cond_2 is filtered to reflect that it is
4728 * only evaluated when skip_cond_1 is false.
4730 * The skip condition on scop1 is not removed because it still needs
4731 * to be applied to scop2 when these two scops are combined.
4733 static struct pet_scop *extract_skip_seq(PetScan *ps,
4734 __isl_take isl_multi_pw_aff *skip_index,
4735 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4737 pet_expr *expr1, *expr2, *expr, *expr_skip;
4738 struct pet_stmt *stmt;
4739 struct pet_scop *scop;
4740 isl_ctx *ctx = ps->ctx;
4742 if (!scop1 || !scop2)
4743 goto error;
4745 expr1 = pet_scop_get_skip_expr(scop1, type);
4746 expr2 = pet_scop_get_skip_expr(scop2, type);
4747 pet_scop_reset_skip(scop2, type);
4749 expr2 = pet_expr_filter(expr2, pet_expr_access_get_index(expr1), 0);
4751 expr = universally_true(ctx);
4752 expr = pet_expr_new_ternary(expr1, expr, expr2);
4753 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4754 expr_skip = pet_expr_access_set_write(expr_skip, 1);
4755 expr_skip = pet_expr_access_set_read(expr_skip, 0);
4756 expr = pet_expr_new_binary(pet_op_assign, expr_skip, expr);
4757 stmt = pet_stmt_from_pet_expr(-1, NULL, ps->n_stmt++, expr);
4759 scop = pet_scop_from_pet_stmt(ctx, stmt);
4760 scop = scop_add_array(scop, skip_index, ps->ast_context);
4761 isl_multi_pw_aff_free(skip_index);
4763 return scop;
4764 error:
4765 isl_multi_pw_aff_free(skip_index);
4766 return NULL;
4769 /* Structure that handles the construction of skip conditions
4770 * on sequences of statements.
4772 * scop1 and scop2 represent the two statements that are combined
4774 struct pet_skip_info_seq : public pet_skip_info {
4775 struct pet_scop *scop1, *scop2;
4777 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4778 struct pet_scop *scop2);
4779 void extract(PetScan *scan, enum pet_skip type);
4780 void extract(PetScan *scan);
4781 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4782 int offset);
4783 struct pet_scop *add(struct pet_scop *scop, int offset);
4786 /* Initialize a pet_skip_info_seq structure based on
4787 * on the two statements that are going to be combined.
4789 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4790 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
4792 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
4793 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
4794 skip_equals_skip_later(scop2);
4795 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4796 need_skip_seq(scop1, scop2, pet_skip_later);
4799 /* If we need to construct a skip condition of the given type,
4800 * then do so now.
4802 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
4804 if (!skip[type])
4805 return;
4807 index[type] = create_test_index(ctx, scan->n_test++);
4808 scop[type] = extract_skip_seq(scan, isl_multi_pw_aff_copy(index[type]),
4809 scop1, scop2, type);
4812 /* Construct the required skip conditions.
4814 void pet_skip_info_seq::extract(PetScan *scan)
4816 extract(scan, pet_skip_now);
4817 extract(scan, pet_skip_later);
4818 if (equal)
4819 drop_skip_later(scop1, scop2);
4822 /* Add the computed skip condition of the given type to "main" and
4823 * add the scop for computing the condition at the given offset (the statement
4824 * number). Within this offset, the condition is computed at position 1
4825 * to ensure that it is computed after the corresponding statement.
4827 * If equal is set, then we only computed a skip condition for pet_skip_now,
4828 * but we also need to set it as main's pet_skip_later.
4830 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
4831 enum pet_skip type, int offset)
4833 if (!skip[type])
4834 return main;
4836 scop[type] = pet_scop_prefix(scop[type], 1);
4837 scop[type] = pet_scop_prefix(scop[type], offset);
4838 main = pet_scop_add_par(ctx, main, scop[type]);
4839 scop[type] = NULL;
4841 if (equal)
4842 main = pet_scop_set_skip(main, pet_skip_later,
4843 isl_multi_pw_aff_copy(index[type]));
4845 main = pet_scop_set_skip(main, type, index[type]);
4846 index[type] = NULL;
4848 return main;
4851 /* Add the computed skip conditions to "main" and
4852 * add the scops for computing the conditions at the given offset.
4854 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
4856 scop = add(scop, pet_skip_now, offset);
4857 scop = add(scop, pet_skip_later, offset);
4859 return scop;
4862 /* Extract a clone of the kill statement in "scop".
4863 * "scop" is expected to have been created from a DeclStmt
4864 * and should have the kill as its first statement.
4866 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
4868 pet_expr *kill;
4869 struct pet_stmt *stmt;
4870 isl_multi_pw_aff *index;
4871 isl_map *access;
4872 pet_expr *arg;
4874 if (!scop)
4875 return NULL;
4876 if (scop->n_stmt < 1)
4877 isl_die(ctx, isl_error_internal,
4878 "expecting at least one statement", return NULL);
4879 stmt = scop->stmts[0];
4880 if (!pet_stmt_is_kill(stmt))
4881 isl_die(ctx, isl_error_internal,
4882 "expecting kill statement", return NULL);
4884 arg = pet_expr_get_arg(stmt->body, 0);
4885 index = pet_expr_access_get_index(arg);
4886 access = pet_expr_access_get_access(arg);
4887 pet_expr_free(arg);
4888 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
4889 access = isl_map_reset_tuple_id(access, isl_dim_in);
4890 kill = pet_expr_kill_from_access_and_index(access, index);
4891 return pet_stmt_from_pet_expr(stmt->line, NULL, n_stmt++, kill);
4894 /* Mark all arrays in "scop" as being exposed.
4896 static struct pet_scop *mark_exposed(struct pet_scop *scop)
4898 if (!scop)
4899 return NULL;
4900 for (int i = 0; i < scop->n_array; ++i)
4901 scop->arrays[i]->exposed = 1;
4902 return scop;
4905 /* Try and construct a pet_scop corresponding to (part of)
4906 * a sequence of statements.
4908 * "block" is set if the sequence respresents the children of
4909 * a compound statement.
4910 * "skip_declarations" is set if we should skip initial declarations
4911 * in the sequence of statements.
4913 * If there are any breaks or continues in the individual statements,
4914 * then we may have to compute a new skip condition.
4915 * This is handled using a pet_skip_info_seq object.
4916 * On initialization, the object checks if skip conditions need
4917 * to be computed. If so, it does so in "extract" and adds them in "add".
4919 * If "block" is set, then we need to insert kill statements at
4920 * the end of the block for any array that has been declared by
4921 * one of the statements in the sequence. Each of these declarations
4922 * results in the construction of a kill statement at the place
4923 * of the declaration, so we simply collect duplicates of
4924 * those kill statements and append these duplicates to the constructed scop.
4926 * If "block" is not set, then any array declared by one of the statements
4927 * in the sequence is marked as being exposed.
4929 * If autodetect is set, then we allow the extraction of only a subrange
4930 * of the sequence of statements. However, if there is at least one statement
4931 * for which we could not construct a scop and the final range contains
4932 * either no statements or at least one kill, then we discard the entire
4933 * range.
4935 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
4936 bool skip_declarations)
4938 pet_scop *scop;
4939 StmtIterator i;
4940 int j;
4941 bool partial_range = false;
4942 set<struct pet_stmt *> kills;
4943 set<struct pet_stmt *>::iterator it;
4945 scop = pet_scop_empty(ctx);
4946 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4947 Stmt *child = *i;
4948 struct pet_scop *scop_i;
4950 if (scop->n_stmt == 0 && skip_declarations &&
4951 child->getStmtClass() == Stmt::DeclStmtClass)
4952 continue;
4954 scop_i = extract(child);
4955 if (scop->n_stmt != 0 && partial) {
4956 pet_scop_free(scop_i);
4957 break;
4959 pet_skip_info_seq skip(ctx, scop, scop_i);
4960 skip.extract(this);
4961 if (skip)
4962 scop_i = pet_scop_prefix(scop_i, 0);
4963 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4964 if (block)
4965 kills.insert(extract_kill(scop_i));
4966 else
4967 scop_i = mark_exposed(scop_i);
4969 scop_i = pet_scop_prefix(scop_i, j);
4970 if (options->autodetect) {
4971 if (scop_i)
4972 scop = pet_scop_add_seq(ctx, scop, scop_i);
4973 else
4974 partial_range = true;
4975 if (scop->n_stmt != 0 && !scop_i)
4976 partial = true;
4977 } else {
4978 scop = pet_scop_add_seq(ctx, scop, scop_i);
4981 scop = skip.add(scop, j);
4983 if (partial || !scop)
4984 break;
4987 for (it = kills.begin(); it != kills.end(); ++it) {
4988 pet_scop *scop_j;
4989 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4990 scop_j = pet_scop_prefix(scop_j, j);
4991 scop = pet_scop_add_seq(ctx, scop, scop_j);
4994 if (scop && partial_range) {
4995 if (scop->n_stmt == 0 || kills.size() != 0) {
4996 pet_scop_free(scop);
4997 return NULL;
4999 partial = true;
5002 return scop;
5005 /* Check if the scop marked by the user is exactly this Stmt
5006 * or part of this Stmt.
5007 * If so, return a pet_scop corresponding to the marked region.
5008 * Otherwise, return NULL.
5010 struct pet_scop *PetScan::scan(Stmt *stmt)
5012 SourceManager &SM = PP.getSourceManager();
5013 unsigned start_off, end_off;
5015 start_off = getExpansionOffset(SM, stmt->getLocStart());
5016 end_off = getExpansionOffset(SM, stmt->getLocEnd());
5018 if (start_off > loc.end)
5019 return NULL;
5020 if (end_off < loc.start)
5021 return NULL;
5022 if (start_off >= loc.start && end_off <= loc.end) {
5023 return extract(stmt);
5026 StmtIterator start;
5027 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
5028 Stmt *child = *start;
5029 if (!child)
5030 continue;
5031 start_off = getExpansionOffset(SM, child->getLocStart());
5032 end_off = getExpansionOffset(SM, child->getLocEnd());
5033 if (start_off < loc.start && end_off >= loc.end)
5034 return scan(child);
5035 if (start_off >= loc.start)
5036 break;
5039 StmtIterator end;
5040 for (end = start; end != stmt->child_end(); ++end) {
5041 Stmt *child = *end;
5042 start_off = SM.getFileOffset(child->getLocStart());
5043 if (start_off >= loc.end)
5044 break;
5047 return extract(StmtRange(start, end), false, false);
5050 /* Set the size of index "pos" of "array" to "size".
5051 * In particular, add a constraint of the form
5053 * i_pos < size
5055 * to array->extent and a constraint of the form
5057 * size >= 0
5059 * to array->context.
5061 static struct pet_array *update_size(struct pet_array *array, int pos,
5062 __isl_take isl_pw_aff *size)
5064 isl_set *valid;
5065 isl_set *univ;
5066 isl_set *bound;
5067 isl_space *dim;
5068 isl_aff *aff;
5069 isl_pw_aff *index;
5070 isl_id *id;
5072 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
5073 array->context = isl_set_intersect(array->context, valid);
5075 dim = isl_set_get_space(array->extent);
5076 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
5077 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
5078 univ = isl_set_universe(isl_aff_get_domain_space(aff));
5079 index = isl_pw_aff_alloc(univ, aff);
5081 size = isl_pw_aff_add_dims(size, isl_dim_in,
5082 isl_set_dim(array->extent, isl_dim_set));
5083 id = isl_set_get_tuple_id(array->extent);
5084 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
5085 bound = isl_pw_aff_lt_set(index, size);
5087 array->extent = isl_set_intersect(array->extent, bound);
5089 if (!array->context || !array->extent)
5090 goto error;
5092 return array;
5093 error:
5094 pet_array_free(array);
5095 return NULL;
5098 /* Figure out the size of the array at position "pos" and all
5099 * subsequent positions from "type" and update "array" accordingly.
5101 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
5102 const Type *type, int pos)
5104 const ArrayType *atype;
5105 isl_pw_aff *size;
5107 if (!array)
5108 return NULL;
5110 if (type->isPointerType()) {
5111 type = type->getPointeeType().getTypePtr();
5112 return set_upper_bounds(array, type, pos + 1);
5114 if (!type->isArrayType())
5115 return array;
5117 type = type->getCanonicalTypeInternal().getTypePtr();
5118 atype = cast<ArrayType>(type);
5120 if (type->isConstantArrayType()) {
5121 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
5122 size = extract_affine(ca->getSize());
5123 array = update_size(array, pos, size);
5124 } else if (type->isVariableArrayType()) {
5125 const VariableArrayType *vla = cast<VariableArrayType>(atype);
5126 size = extract_affine(vla->getSizeExpr());
5127 array = update_size(array, pos, size);
5130 type = atype->getElementType().getTypePtr();
5132 return set_upper_bounds(array, type, pos + 1);
5135 /* Is "T" the type of a variable length array with static size?
5137 static bool is_vla_with_static_size(QualType T)
5139 const VariableArrayType *vlatype;
5141 if (!T->isVariableArrayType())
5142 return false;
5143 vlatype = cast<VariableArrayType>(T);
5144 return vlatype->getSizeModifier() == VariableArrayType::Static;
5147 /* Return the type of "decl" as an array.
5149 * In particular, if "decl" is a parameter declaration that
5150 * is a variable length array with a static size, then
5151 * return the original type (i.e., the variable length array).
5152 * Otherwise, return the type of decl.
5154 static QualType get_array_type(ValueDecl *decl)
5156 ParmVarDecl *parm;
5157 QualType T;
5159 parm = dyn_cast<ParmVarDecl>(decl);
5160 if (!parm)
5161 return decl->getType();
5163 T = parm->getOriginalType();
5164 if (!is_vla_with_static_size(T))
5165 return decl->getType();
5166 return T;
5169 /* Does "decl" have definition that we can keep track of in a pet_type?
5171 static bool has_printable_definition(RecordDecl *decl)
5173 if (!decl->getDeclName())
5174 return false;
5175 return decl->getLexicalDeclContext() == decl->getDeclContext();
5178 /* Construct and return a pet_array corresponding to the variable "decl".
5179 * In particular, initialize array->extent to
5181 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
5183 * and then call set_upper_bounds to set the upper bounds on the indices
5184 * based on the type of the variable.
5186 * If the base type is that of a record with a top-level definition and
5187 * if "types" is not null, then the RecordDecl corresponding to the type
5188 * is added to "types".
5190 * If the base type is that of a record with no top-level definition,
5191 * then we replace it by "<subfield>".
5193 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
5194 lex_recorddecl_set *types)
5196 struct pet_array *array;
5197 QualType qt = get_array_type(decl);
5198 const Type *type = qt.getTypePtr();
5199 int depth = array_depth(type);
5200 QualType base = pet_clang_base_type(qt);
5201 string name;
5202 isl_id *id;
5203 isl_space *dim;
5205 array = isl_calloc_type(ctx, struct pet_array);
5206 if (!array)
5207 return NULL;
5209 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
5210 dim = isl_space_set_alloc(ctx, 0, depth);
5211 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
5213 array->extent = isl_set_nat_universe(dim);
5215 dim = isl_space_params_alloc(ctx, 0);
5216 array->context = isl_set_universe(dim);
5218 array = set_upper_bounds(array, type, 0);
5219 if (!array)
5220 return NULL;
5222 name = base.getAsString();
5224 if (types && base->isRecordType()) {
5225 RecordDecl *decl = pet_clang_record_decl(base);
5226 if (has_printable_definition(decl))
5227 types->insert(decl);
5228 else
5229 name = "<subfield>";
5232 array->element_type = strdup(name.c_str());
5233 array->element_is_record = base->isRecordType();
5234 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
5236 return array;
5239 /* Construct and return a pet_array corresponding to the sequence
5240 * of declarations "decls".
5241 * If the sequence contains a single declaration, then it corresponds
5242 * to a simple array access. Otherwise, it corresponds to a member access,
5243 * with the declaration for the substructure following that of the containing
5244 * structure in the sequence of declarations.
5245 * We start with the outermost substructure and then combine it with
5246 * information from the inner structures.
5248 * Additionally, keep track of all required types in "types".
5250 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
5251 vector<ValueDecl *> decls, lex_recorddecl_set *types)
5253 struct pet_array *array;
5254 vector<ValueDecl *>::iterator it;
5256 it = decls.begin();
5258 array = extract_array(ctx, *it, types);
5260 for (++it; it != decls.end(); ++it) {
5261 struct pet_array *parent;
5262 const char *base_name, *field_name;
5263 char *product_name;
5265 parent = array;
5266 array = extract_array(ctx, *it, types);
5267 if (!array)
5268 return pet_array_free(parent);
5270 base_name = isl_set_get_tuple_name(parent->extent);
5271 field_name = isl_set_get_tuple_name(array->extent);
5272 product_name = member_access_name(ctx, base_name, field_name);
5274 array->extent = isl_set_product(isl_set_copy(parent->extent),
5275 array->extent);
5276 if (product_name)
5277 array->extent = isl_set_set_tuple_name(array->extent,
5278 product_name);
5279 array->context = isl_set_intersect(array->context,
5280 isl_set_copy(parent->context));
5282 pet_array_free(parent);
5283 free(product_name);
5285 if (!array->extent || !array->context || !product_name)
5286 return pet_array_free(array);
5289 return array;
5292 /* Add a pet_type corresponding to "decl" to "scop, provided
5293 * it is a member of "types" and it has not been added before
5294 * (i.e., it is not a member of "types_done".
5296 * Since we want the user to be able to print the types
5297 * in the order in which they appear in the scop, we need to
5298 * make sure that types of fields in a structure appear before
5299 * that structure. We therefore call ourselves recursively
5300 * on the types of all record subfields.
5302 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
5303 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
5304 lex_recorddecl_set &types_done)
5306 string s;
5307 llvm::raw_string_ostream S(s);
5308 RecordDecl::field_iterator it;
5310 if (types.find(decl) == types.end())
5311 return scop;
5312 if (types_done.find(decl) != types_done.end())
5313 return scop;
5315 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
5316 RecordDecl *record;
5317 QualType type = it->getType();
5319 if (!type->isRecordType())
5320 continue;
5321 record = pet_clang_record_decl(type);
5322 scop = add_type(ctx, scop, record, PP, types, types_done);
5325 if (strlen(decl->getName().str().c_str()) == 0)
5326 return scop;
5328 decl->print(S, PrintingPolicy(PP.getLangOpts()));
5329 S.str();
5331 scop->types[scop->n_type] = pet_type_alloc(ctx,
5332 decl->getName().str().c_str(), s.c_str());
5333 if (!scop->types[scop->n_type])
5334 return pet_scop_free(scop);
5336 types_done.insert(decl);
5338 scop->n_type++;
5340 return scop;
5343 /* Construct a list of pet_arrays, one for each array (or scalar)
5344 * accessed inside "scop", add this list to "scop" and return the result.
5346 * The context of "scop" is updated with the intersection of
5347 * the contexts of all arrays, i.e., constraints on the parameters
5348 * that ensure that the arrays have a valid (non-negative) size.
5350 * If the any of the extracted arrays refers to a member access,
5351 * then also add the required types to "scop".
5353 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
5355 int i;
5356 array_desc_set arrays;
5357 array_desc_set::iterator it;
5358 lex_recorddecl_set types;
5359 lex_recorddecl_set types_done;
5360 lex_recorddecl_set::iterator types_it;
5361 int n_array;
5362 struct pet_array **scop_arrays;
5364 if (!scop)
5365 return NULL;
5367 pet_scop_collect_arrays(scop, arrays);
5368 if (arrays.size() == 0)
5369 return scop;
5371 n_array = scop->n_array;
5373 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
5374 n_array + arrays.size());
5375 if (!scop_arrays)
5376 goto error;
5377 scop->arrays = scop_arrays;
5379 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
5380 struct pet_array *array;
5381 array = extract_array(ctx, *it, &types);
5382 scop->arrays[n_array + i] = array;
5383 if (!scop->arrays[n_array + i])
5384 goto error;
5385 scop->n_array++;
5386 scop->context = isl_set_intersect(scop->context,
5387 isl_set_copy(array->context));
5388 if (!scop->context)
5389 goto error;
5392 if (types.size() == 0)
5393 return scop;
5395 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
5396 if (!scop->types)
5397 goto error;
5399 for (types_it = types.begin(); types_it != types.end(); ++types_it)
5400 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
5402 return scop;
5403 error:
5404 pet_scop_free(scop);
5405 return NULL;
5408 /* Bound all parameters in scop->context to the possible values
5409 * of the corresponding C variable.
5411 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
5413 int n;
5415 if (!scop)
5416 return NULL;
5418 n = isl_set_dim(scop->context, isl_dim_param);
5419 for (int i = 0; i < n; ++i) {
5420 isl_id *id;
5421 ValueDecl *decl;
5423 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
5424 if (pet_nested_in_id(id)) {
5425 isl_id_free(id);
5426 isl_die(isl_set_get_ctx(scop->context),
5427 isl_error_internal,
5428 "unresolved nested parameter", goto error);
5430 decl = (ValueDecl *) isl_id_get_user(id);
5431 isl_id_free(id);
5433 scop->context = set_parameter_bounds(scop->context, i, decl);
5435 if (!scop->context)
5436 goto error;
5439 return scop;
5440 error:
5441 pet_scop_free(scop);
5442 return NULL;
5445 /* Construct a pet_scop from the given function.
5447 * If the scop was delimited by scop and endscop pragmas, then we override
5448 * the file offsets by those derived from the pragmas.
5450 struct pet_scop *PetScan::scan(FunctionDecl *fd)
5452 pet_scop *scop;
5453 Stmt *stmt;
5455 stmt = fd->getBody();
5457 if (options->autodetect)
5458 scop = extract(stmt, true);
5459 else {
5460 scop = scan(stmt);
5461 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
5463 scop = pet_scop_detect_parameter_accesses(scop);
5464 scop = scan_arrays(scop);
5465 scop = add_parameter_bounds(scop);
5466 scop = pet_scop_gist(scop, value_bounds);
5468 return scop;