extract out pet_scop_add_boolean_array
[pet.git] / scan.cc
blobbb956c30bf0ec2d7916b7948ed841eafc446c890
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2014 Ecole Normale Superieure. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
32 * Leiden University.
33 */
35 #include <string.h>
36 #include <set>
37 #include <map>
38 #include <iostream>
39 #include <llvm/Support/raw_ostream.h>
40 #include <clang/AST/ASTContext.h>
41 #include <clang/AST/ASTDiagnostic.h>
42 #include <clang/AST/Expr.h>
43 #include <clang/AST/RecursiveASTVisitor.h>
45 #include <isl/id.h>
46 #include <isl/space.h>
47 #include <isl/aff.h>
48 #include <isl/set.h>
50 #include "aff.h"
51 #include "clang.h"
52 #include "expr.h"
53 #include "nest.h"
54 #include "options.h"
55 #include "scan.h"
56 #include "scop.h"
57 #include "scop_plus.h"
59 #include "config.h"
61 using namespace std;
62 using namespace clang;
64 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
66 switch (kind) {
67 case UO_Minus:
68 return pet_op_minus;
69 case UO_Not:
70 return pet_op_not;
71 case UO_LNot:
72 return pet_op_lnot;
73 case UO_PostInc:
74 return pet_op_post_inc;
75 case UO_PostDec:
76 return pet_op_post_dec;
77 case UO_PreInc:
78 return pet_op_pre_inc;
79 case UO_PreDec:
80 return pet_op_pre_dec;
81 default:
82 return pet_op_last;
86 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
88 switch (kind) {
89 case BO_AddAssign:
90 return pet_op_add_assign;
91 case BO_SubAssign:
92 return pet_op_sub_assign;
93 case BO_MulAssign:
94 return pet_op_mul_assign;
95 case BO_DivAssign:
96 return pet_op_div_assign;
97 case BO_Assign:
98 return pet_op_assign;
99 case BO_Add:
100 return pet_op_add;
101 case BO_Sub:
102 return pet_op_sub;
103 case BO_Mul:
104 return pet_op_mul;
105 case BO_Div:
106 return pet_op_div;
107 case BO_Rem:
108 return pet_op_mod;
109 case BO_Shl:
110 return pet_op_shl;
111 case BO_Shr:
112 return pet_op_shr;
113 case BO_EQ:
114 return pet_op_eq;
115 case BO_NE:
116 return pet_op_ne;
117 case BO_LE:
118 return pet_op_le;
119 case BO_GE:
120 return pet_op_ge;
121 case BO_LT:
122 return pet_op_lt;
123 case BO_GT:
124 return pet_op_gt;
125 case BO_And:
126 return pet_op_and;
127 case BO_Xor:
128 return pet_op_xor;
129 case BO_Or:
130 return pet_op_or;
131 case BO_LAnd:
132 return pet_op_land;
133 case BO_LOr:
134 return pet_op_lor;
135 default:
136 return pet_op_last;
140 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
141 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
143 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
144 SourceLocation(), var, false, var->getInnerLocStart(),
145 var->getType(), VK_LValue);
147 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
148 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
150 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
151 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
152 VK_LValue);
154 #else
155 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
157 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
158 var, var->getInnerLocStart(), var->getType(), VK_LValue);
160 #endif
162 /* Check if the element type corresponding to the given array type
163 * has a const qualifier.
165 static bool const_base(QualType qt)
167 const Type *type = qt.getTypePtr();
169 if (type->isPointerType())
170 return const_base(type->getPointeeType());
171 if (type->isArrayType()) {
172 const ArrayType *atype;
173 type = type->getCanonicalTypeInternal().getTypePtr();
174 atype = cast<ArrayType>(type);
175 return const_base(atype->getElementType());
178 return qt.isConstQualified();
181 /* Mark "decl" as having an unknown value in "assigned_value".
183 * If no (known or unknown) value was assigned to "decl" before,
184 * then it may have been treated as a parameter before and may
185 * therefore appear in a value assigned to another variable.
186 * If so, this assignment needs to be turned into an unknown value too.
188 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
189 ValueDecl *decl)
191 map<ValueDecl *, isl_pw_aff *>::iterator it;
193 it = assigned_value.find(decl);
195 assigned_value[decl] = NULL;
197 if (it != assigned_value.end())
198 return;
200 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
201 isl_pw_aff *pa = it->second;
202 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
204 for (int i = 0; i < nparam; ++i) {
205 isl_id *id;
207 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
208 continue;
209 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
210 if (isl_id_get_user(id) == decl)
211 it->second = NULL;
212 isl_id_free(id);
217 /* Look for any assignments to scalar variables in part of the parse
218 * tree and set assigned_value to NULL for each of them.
219 * Also reset assigned_value if the address of a scalar variable
220 * is being taken. As an exception, if the address is passed to a function
221 * that is declared to receive a const pointer, then assigned_value is
222 * not reset.
224 * This ensures that we won't use any previously stored value
225 * in the current subtree and its parents.
227 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
228 map<ValueDecl *, isl_pw_aff *> &assigned_value;
229 set<UnaryOperator *> skip;
231 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
232 assigned_value(assigned_value) {}
234 /* Check for "address of" operators whose value is passed
235 * to a const pointer argument and add them to "skip", so that
236 * we can skip them in VisitUnaryOperator.
238 bool VisitCallExpr(CallExpr *expr) {
239 FunctionDecl *fd;
240 fd = expr->getDirectCallee();
241 if (!fd)
242 return true;
243 for (int i = 0; i < expr->getNumArgs(); ++i) {
244 Expr *arg = expr->getArg(i);
245 UnaryOperator *op;
246 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
247 ImplicitCastExpr *ice;
248 ice = cast<ImplicitCastExpr>(arg);
249 arg = ice->getSubExpr();
251 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
252 continue;
253 op = cast<UnaryOperator>(arg);
254 if (op->getOpcode() != UO_AddrOf)
255 continue;
256 if (const_base(fd->getParamDecl(i)->getType()))
257 skip.insert(op);
259 return true;
262 bool VisitUnaryOperator(UnaryOperator *expr) {
263 Expr *arg;
264 DeclRefExpr *ref;
265 ValueDecl *decl;
267 switch (expr->getOpcode()) {
268 case UO_AddrOf:
269 case UO_PostInc:
270 case UO_PostDec:
271 case UO_PreInc:
272 case UO_PreDec:
273 break;
274 default:
275 return true;
277 if (skip.find(expr) != skip.end())
278 return true;
280 arg = expr->getSubExpr();
281 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
282 return true;
283 ref = cast<DeclRefExpr>(arg);
284 decl = ref->getDecl();
285 clear_assignment(assigned_value, decl);
286 return true;
289 bool VisitBinaryOperator(BinaryOperator *expr) {
290 Expr *lhs;
291 DeclRefExpr *ref;
292 ValueDecl *decl;
294 if (!expr->isAssignmentOp())
295 return true;
296 lhs = expr->getLHS();
297 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
298 return true;
299 ref = cast<DeclRefExpr>(lhs);
300 decl = ref->getDecl();
301 clear_assignment(assigned_value, decl);
302 return true;
306 /* Keep a copy of the currently assigned values.
308 * Any variable that is assigned a value inside the current scope
309 * is removed again when we leave the scope (either because it wasn't
310 * stored in the cache or because it has a different value in the cache).
312 struct assigned_value_cache {
313 map<ValueDecl *, isl_pw_aff *> &assigned_value;
314 map<ValueDecl *, isl_pw_aff *> cache;
316 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
317 assigned_value(assigned_value), cache(assigned_value) {}
318 ~assigned_value_cache() {
319 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
320 for (it = assigned_value.begin(); it != assigned_value.end();
321 ++it) {
322 if (!it->second ||
323 (cache.find(it->first) != cache.end() &&
324 cache[it->first] != it->second))
325 cache[it->first] = NULL;
327 assigned_value = cache;
331 /* Insert an expression into the collection of expressions,
332 * provided it is not already in there.
333 * The isl_pw_affs are freed in the destructor.
335 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
337 std::set<isl_pw_aff *>::iterator it;
339 if (expressions.find(expr) == expressions.end())
340 expressions.insert(expr);
341 else
342 isl_pw_aff_free(expr);
345 PetScan::~PetScan()
347 std::set<isl_pw_aff *>::iterator it;
349 for (it = expressions.begin(); it != expressions.end(); ++it)
350 isl_pw_aff_free(*it);
352 isl_union_map_free(value_bounds);
355 /* Report a diagnostic, unless autodetect is set.
357 void PetScan::report(Stmt *stmt, unsigned id)
359 if (options->autodetect)
360 return;
362 SourceLocation loc = stmt->getLocStart();
363 DiagnosticsEngine &diag = PP.getDiagnostics();
364 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
367 /* Called if we found something we (currently) cannot handle.
368 * We'll provide more informative warnings later.
370 * We only actually complain if autodetect is false.
372 void PetScan::unsupported(Stmt *stmt)
374 DiagnosticsEngine &diag = PP.getDiagnostics();
375 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
376 "unsupported");
377 report(stmt, id);
380 /* Report a missing prototype, unless autodetect is set.
382 void PetScan::report_prototype_required(Stmt *stmt)
384 DiagnosticsEngine &diag = PP.getDiagnostics();
385 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
386 "prototype required");
387 report(stmt, id);
390 /* Report a missing increment, unless autodetect is set.
392 void PetScan::report_missing_increment(Stmt *stmt)
394 DiagnosticsEngine &diag = PP.getDiagnostics();
395 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
396 "missing increment");
397 report(stmt, id);
400 /* Extract an integer from "expr".
402 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
404 const Type *type = expr->getType().getTypePtr();
405 int is_signed = type->hasSignedIntegerRepresentation();
406 llvm::APInt val = expr->getValue();
407 int is_negative = is_signed && val.isNegative();
408 isl_val *v;
410 if (is_negative)
411 val = -val;
413 v = extract_unsigned(ctx, val);
415 if (is_negative)
416 v = isl_val_neg(v);
417 return v;
420 /* Extract an integer from "val", which is assumed to be non-negative.
422 __isl_give isl_val *PetScan::extract_unsigned(isl_ctx *ctx,
423 const llvm::APInt &val)
425 unsigned n;
426 const uint64_t *data;
428 data = val.getRawData();
429 n = val.getNumWords();
430 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
433 /* Extract an integer from "expr".
434 * Return NULL if "expr" does not (obviously) represent an integer.
436 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
438 return extract_int(expr->getSubExpr());
441 /* Extract an integer from "expr".
442 * Return NULL if "expr" does not (obviously) represent an integer.
444 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
446 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
447 return extract_int(ctx, cast<IntegerLiteral>(expr));
448 if (expr->getStmtClass() == Stmt::ParenExprClass)
449 return extract_int(cast<ParenExpr>(expr));
451 unsupported(expr);
452 return NULL;
455 /* Extract an affine expression from the IntegerLiteral "expr".
457 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
459 isl_space *dim = isl_space_params_alloc(ctx, 0);
460 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
461 isl_aff *aff = isl_aff_zero_on_domain(ls);
462 isl_set *dom = isl_set_universe(dim);
463 isl_val *v;
465 v = extract_int(expr);
466 aff = isl_aff_add_constant_val(aff, v);
468 return isl_pw_aff_alloc(dom, aff);
471 /* Extract an affine expression from the APInt "val", which is assumed
472 * to be non-negative.
474 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
476 isl_space *dim = isl_space_params_alloc(ctx, 0);
477 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
478 isl_aff *aff = isl_aff_zero_on_domain(ls);
479 isl_set *dom = isl_set_universe(dim);
480 isl_val *v;
482 v = extract_unsigned(ctx, val);
483 aff = isl_aff_add_constant_val(aff, v);
485 return isl_pw_aff_alloc(dom, aff);
488 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
490 return extract_affine(expr->getSubExpr());
493 /* Return the number of bits needed to represent the type "qt",
494 * if it is an integer type. Otherwise return 0.
495 * If qt is signed then return the opposite of the number of bits.
497 static int get_type_size(QualType qt, ASTContext &ast_context)
499 int size;
501 if (!qt->isIntegerType())
502 return 0;
504 size = ast_context.getIntWidth(qt);
505 if (!qt->isUnsignedIntegerType())
506 size = -size;
508 return size;
511 /* Return the number of bits needed to represent the type of "decl",
512 * if it is an integer type. Otherwise return 0.
513 * If qt is signed then return the opposite of the number of bits.
515 static int get_type_size(ValueDecl *decl)
517 return get_type_size(decl->getType(), decl->getASTContext());
520 /* Bound parameter "pos" of "set" to the possible values of "decl".
522 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
523 unsigned pos, ValueDecl *decl)
525 int type_size;
526 isl_ctx *ctx;
527 isl_val *bound;
529 ctx = isl_set_get_ctx(set);
530 type_size = get_type_size(decl);
531 if (type_size == 0)
532 isl_die(ctx, isl_error_invalid, "not an integer type",
533 return isl_set_free(set));
534 if (type_size > 0) {
535 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
536 bound = isl_val_int_from_ui(ctx, type_size);
537 bound = isl_val_2exp(bound);
538 bound = isl_val_sub_ui(bound, 1);
539 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
540 } else {
541 bound = isl_val_int_from_ui(ctx, -type_size - 1);
542 bound = isl_val_2exp(bound);
543 bound = isl_val_sub_ui(bound, 1);
544 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
545 isl_val_copy(bound));
546 bound = isl_val_neg(bound);
547 bound = isl_val_sub_ui(bound, 1);
548 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
551 return set;
554 /* Extract an affine expression from the DeclRefExpr "expr".
556 * If the variable has been assigned a value, then we check whether
557 * we know what (affine) value was assigned.
558 * If so, we return this value. Otherwise we convert "expr"
559 * to an extra parameter (provided nesting_enabled is set).
561 * Otherwise, we simply return an expression that is equal
562 * to a parameter corresponding to the referenced variable.
564 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
566 ValueDecl *decl = expr->getDecl();
567 const Type *type = decl->getType().getTypePtr();
568 isl_id *id;
569 isl_space *dim;
570 isl_aff *aff;
571 isl_set *dom;
573 if (!type->isIntegerType()) {
574 unsupported(expr);
575 return NULL;
578 if (assigned_value.find(decl) != assigned_value.end()) {
579 if (assigned_value[decl])
580 return isl_pw_aff_copy(assigned_value[decl]);
581 else
582 return nested_access(expr);
585 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
586 dim = isl_space_params_alloc(ctx, 1);
588 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
590 dom = isl_set_universe(isl_space_copy(dim));
591 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
592 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
594 return isl_pw_aff_alloc(dom, aff);
597 /* Extract an affine expression from an integer division operation.
598 * In particular, if "expr" is lhs/rhs, then return
600 * 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_div(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_q(lhs, rhs);
623 /* Extract an affine expression from a modulo operation.
624 * In particular, if "expr" is lhs/rhs, then return
626 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
628 * The second argument (rhs) is required to be a (positive) integer constant.
630 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
632 int is_cst;
633 isl_pw_aff *rhs, *lhs;
635 rhs = extract_affine(expr->getRHS());
636 is_cst = isl_pw_aff_is_cst(rhs);
637 if (is_cst < 0 || !is_cst) {
638 isl_pw_aff_free(rhs);
639 if (!is_cst)
640 unsupported(expr);
641 return NULL;
644 lhs = extract_affine(expr->getLHS());
646 return isl_pw_aff_tdiv_r(lhs, rhs);
649 /* Extract an affine expression from a multiplication operation.
650 * This is only allowed if at least one of the two arguments
651 * is a (piecewise) constant.
653 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
655 isl_pw_aff *lhs;
656 isl_pw_aff *rhs;
658 lhs = extract_affine(expr->getLHS());
659 rhs = extract_affine(expr->getRHS());
661 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
662 isl_pw_aff_free(lhs);
663 isl_pw_aff_free(rhs);
664 unsupported(expr);
665 return NULL;
668 return isl_pw_aff_mul(lhs, rhs);
671 /* Extract an affine expression from an addition or subtraction operation.
673 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
675 isl_pw_aff *lhs;
676 isl_pw_aff *rhs;
678 lhs = extract_affine(expr->getLHS());
679 rhs = extract_affine(expr->getRHS());
681 switch (expr->getOpcode()) {
682 case BO_Add:
683 return isl_pw_aff_add(lhs, rhs);
684 case BO_Sub:
685 return isl_pw_aff_sub(lhs, rhs);
686 default:
687 isl_pw_aff_free(lhs);
688 isl_pw_aff_free(rhs);
689 return NULL;
694 /* Compute
696 * pwaff mod 2^width
698 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
699 unsigned width)
701 isl_ctx *ctx;
702 isl_val *mod;
704 ctx = isl_pw_aff_get_ctx(pwaff);
705 mod = isl_val_int_from_ui(ctx, width);
706 mod = isl_val_2exp(mod);
708 pwaff = isl_pw_aff_mod_val(pwaff, mod);
710 return pwaff;
713 /* Limit the domain of "pwaff" to those elements where the function
714 * value satisfies
716 * 2^{width-1} <= pwaff < 2^{width-1}
718 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
719 unsigned width)
721 isl_ctx *ctx;
722 isl_val *v;
723 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
724 isl_local_space *ls = isl_local_space_from_space(space);
725 isl_aff *bound;
726 isl_set *dom;
727 isl_pw_aff *b;
729 ctx = isl_pw_aff_get_ctx(pwaff);
730 v = isl_val_int_from_ui(ctx, width - 1);
731 v = isl_val_2exp(v);
733 bound = isl_aff_zero_on_domain(ls);
734 bound = isl_aff_add_constant_val(bound, v);
735 b = isl_pw_aff_from_aff(bound);
737 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
738 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
740 b = isl_pw_aff_neg(b);
741 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
742 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
744 return pwaff;
747 /* Handle potential overflows on signed computations.
749 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
750 * the we adjust the domain of "pa" to avoid overflows.
752 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
753 unsigned width)
755 if (options->signed_overflow == PET_OVERFLOW_AVOID)
756 pa = avoid_overflow(pa, width);
758 return pa;
761 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
763 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
764 __isl_take isl_set *dom)
766 isl_pw_aff *pa;
767 pa = isl_set_indicator_function(set);
768 pa = isl_pw_aff_intersect_domain(pa, isl_set_coalesce(dom));
769 return pa;
772 /* Extract an affine expression from some binary operations.
773 * If the result of the expression is unsigned, then we wrap it
774 * based on the size of the type. Otherwise, we ensure that
775 * no overflow occurs.
777 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
779 isl_pw_aff *res;
780 unsigned width;
782 switch (expr->getOpcode()) {
783 case BO_Add:
784 case BO_Sub:
785 res = extract_affine_add(expr);
786 break;
787 case BO_Div:
788 res = extract_affine_div(expr);
789 break;
790 case BO_Rem:
791 res = extract_affine_mod(expr);
792 break;
793 case BO_Mul:
794 res = extract_affine_mul(expr);
795 break;
796 case BO_LT:
797 case BO_LE:
798 case BO_GT:
799 case BO_GE:
800 case BO_EQ:
801 case BO_NE:
802 case BO_LAnd:
803 case BO_LOr:
804 return extract_condition(expr);
805 default:
806 unsupported(expr);
807 return NULL;
810 width = ast_context.getIntWidth(expr->getType());
811 if (expr->getType()->isUnsignedIntegerType())
812 res = wrap(res, width);
813 else
814 res = signed_overflow(res, width);
816 return res;
819 /* Extract an affine expression from a negation operation.
821 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
823 if (expr->getOpcode() == UO_Minus)
824 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
825 if (expr->getOpcode() == UO_LNot)
826 return extract_condition(expr);
828 unsupported(expr);
829 return NULL;
832 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
834 return extract_affine(expr->getSubExpr());
837 /* Extract an affine expression from some special function calls.
838 * In particular, we handle "min", "max", "ceild", "floord",
839 * "intMod", "intFloor" and "intCeil".
840 * In case of the latter five, the second argument needs to be
841 * a (positive) integer constant.
843 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
845 FunctionDecl *fd;
846 string name;
847 isl_pw_aff *aff1, *aff2;
849 fd = expr->getDirectCallee();
850 if (!fd) {
851 unsupported(expr);
852 return NULL;
855 name = fd->getDeclName().getAsString();
856 if (!(expr->getNumArgs() == 2 && name == "min") &&
857 !(expr->getNumArgs() == 2 && name == "max") &&
858 !(expr->getNumArgs() == 2 && name == "intMod") &&
859 !(expr->getNumArgs() == 2 && name == "intFloor") &&
860 !(expr->getNumArgs() == 2 && name == "intCeil") &&
861 !(expr->getNumArgs() == 2 && name == "floord") &&
862 !(expr->getNumArgs() == 2 && name == "ceild")) {
863 unsupported(expr);
864 return NULL;
867 if (name == "min" || name == "max") {
868 aff1 = extract_affine(expr->getArg(0));
869 aff2 = extract_affine(expr->getArg(1));
871 if (name == "min")
872 aff1 = isl_pw_aff_min(aff1, aff2);
873 else
874 aff1 = isl_pw_aff_max(aff1, aff2);
875 } else if (name == "intMod") {
876 isl_val *v;
877 Expr *arg2 = expr->getArg(1);
879 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
880 unsupported(expr);
881 return NULL;
883 aff1 = extract_affine(expr->getArg(0));
884 v = extract_int(cast<IntegerLiteral>(arg2));
885 aff1 = isl_pw_aff_mod_val(aff1, v);
886 } else if (name == "floord" || name == "ceild" ||
887 name == "intFloor" || name == "intCeil") {
888 isl_val *v;
889 Expr *arg2 = expr->getArg(1);
891 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
892 unsupported(expr);
893 return NULL;
895 aff1 = extract_affine(expr->getArg(0));
896 v = extract_int(cast<IntegerLiteral>(arg2));
897 aff1 = isl_pw_aff_scale_down_val(aff1, v);
898 if (name == "floord" || name == "intFloor")
899 aff1 = isl_pw_aff_floor(aff1);
900 else
901 aff1 = isl_pw_aff_ceil(aff1);
902 } else {
903 unsupported(expr);
904 return NULL;
907 return aff1;
910 /* This method is called when we come across an access that is
911 * nested in what is supposed to be an affine expression.
912 * If nesting is allowed, we return a new parameter that corresponds
913 * to this nested access. Otherwise, we simply complain.
915 * Note that we currently don't allow nested accesses themselves
916 * to contain any nested accesses, so we check if we can extract
917 * the access without any nesting and complain if we can't.
919 * The new parameter is resolved in resolve_nested.
921 isl_pw_aff *PetScan::nested_access(Expr *expr)
923 isl_id *id;
924 isl_space *dim;
925 isl_aff *aff;
926 isl_set *dom;
927 isl_multi_pw_aff *index;
929 if (!nesting_enabled) {
930 unsupported(expr);
931 return NULL;
934 allow_nested = false;
935 index = extract_index(expr);
936 allow_nested = true;
937 if (!index) {
938 unsupported(expr);
939 return NULL;
941 isl_multi_pw_aff_free(index);
943 id = pet_nested_clang_expr(ctx, expr);
944 dim = isl_space_params_alloc(ctx, 1);
946 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
948 dom = isl_set_universe(isl_space_copy(dim));
949 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
950 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
952 return isl_pw_aff_alloc(dom, aff);
955 /* Affine expressions are not supposed to contain array accesses,
956 * but if nesting is allowed, we return a parameter corresponding
957 * to the array access.
959 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
961 return nested_access(expr);
964 /* Affine expressions are not supposed to contain member accesses,
965 * but if nesting is allowed, we return a parameter corresponding
966 * to the member access.
968 __isl_give isl_pw_aff *PetScan::extract_affine(MemberExpr *expr)
970 return nested_access(expr);
973 /* Extract an affine expression from a conditional operation.
975 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
977 isl_pw_aff *cond, *lhs, *rhs;
979 cond = extract_condition(expr->getCond());
980 lhs = extract_affine(expr->getTrueExpr());
981 rhs = extract_affine(expr->getFalseExpr());
983 return isl_pw_aff_cond(cond, lhs, rhs);
986 /* Extract an affine expression, if possible, from "expr".
987 * Otherwise return NULL.
989 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
991 switch (expr->getStmtClass()) {
992 case Stmt::ImplicitCastExprClass:
993 return extract_affine(cast<ImplicitCastExpr>(expr));
994 case Stmt::IntegerLiteralClass:
995 return extract_affine(cast<IntegerLiteral>(expr));
996 case Stmt::DeclRefExprClass:
997 return extract_affine(cast<DeclRefExpr>(expr));
998 case Stmt::BinaryOperatorClass:
999 return extract_affine(cast<BinaryOperator>(expr));
1000 case Stmt::UnaryOperatorClass:
1001 return extract_affine(cast<UnaryOperator>(expr));
1002 case Stmt::ParenExprClass:
1003 return extract_affine(cast<ParenExpr>(expr));
1004 case Stmt::CallExprClass:
1005 return extract_affine(cast<CallExpr>(expr));
1006 case Stmt::ArraySubscriptExprClass:
1007 return extract_affine(cast<ArraySubscriptExpr>(expr));
1008 case Stmt::MemberExprClass:
1009 return extract_affine(cast<MemberExpr>(expr));
1010 case Stmt::ConditionalOperatorClass:
1011 return extract_affine(cast<ConditionalOperator>(expr));
1012 default:
1013 unsupported(expr);
1015 return NULL;
1018 __isl_give isl_multi_pw_aff *PetScan::extract_index(ImplicitCastExpr *expr)
1020 return extract_index(expr->getSubExpr());
1023 /* Return the depth of an array of the given type.
1025 static int array_depth(const Type *type)
1027 if (type->isPointerType())
1028 return 1 + array_depth(type->getPointeeType().getTypePtr());
1029 if (type->isArrayType()) {
1030 const ArrayType *atype;
1031 type = type->getCanonicalTypeInternal().getTypePtr();
1032 atype = cast<ArrayType>(type);
1033 return 1 + array_depth(atype->getElementType().getTypePtr());
1035 return 0;
1038 /* Return the depth of the array accessed by the index expression "index".
1039 * If "index" is an affine expression, i.e., if it does not access
1040 * any array, then return 1.
1041 * If "index" represent a member access, i.e., if its range is a wrapped
1042 * relation, then return the sum of the depth of the array of structures
1043 * and that of the member inside the structure.
1045 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
1047 isl_id *id;
1048 ValueDecl *decl;
1050 if (!index)
1051 return -1;
1053 if (isl_multi_pw_aff_range_is_wrapping(index)) {
1054 int domain_depth, range_depth;
1055 isl_multi_pw_aff *domain, *range;
1057 domain = isl_multi_pw_aff_copy(index);
1058 domain = isl_multi_pw_aff_range_factor_domain(domain);
1059 domain_depth = extract_depth(domain);
1060 isl_multi_pw_aff_free(domain);
1061 range = isl_multi_pw_aff_copy(index);
1062 range = isl_multi_pw_aff_range_factor_range(range);
1063 range_depth = extract_depth(range);
1064 isl_multi_pw_aff_free(range);
1066 return domain_depth + range_depth;
1069 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
1070 return 1;
1072 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
1073 if (!id)
1074 return -1;
1075 decl = (ValueDecl *) isl_id_get_user(id);
1076 isl_id_free(id);
1078 return array_depth(decl->getType().getTypePtr());
1081 /* Extract an index expression from a reference to a variable.
1082 * If the variable has name "A", then the returned index expression
1083 * is of the form
1085 * { [] -> A[] }
1087 __isl_give isl_multi_pw_aff *PetScan::extract_index(DeclRefExpr *expr)
1089 return extract_index(expr->getDecl());
1092 /* Extract an index expression from a variable.
1093 * If the variable has name "A", then the returned index expression
1094 * is of the form
1096 * { [] -> A[] }
1098 __isl_give isl_multi_pw_aff *PetScan::extract_index(ValueDecl *decl)
1100 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
1101 isl_space *space = isl_space_alloc(ctx, 0, 0, 0);
1103 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1105 return isl_multi_pw_aff_zero(space);
1108 /* Extract an index expression from an integer contant.
1109 * If the value of the constant is "v", then the returned access relation
1110 * is
1112 * { [] -> [v] }
1114 __isl_give isl_multi_pw_aff *PetScan::extract_index(IntegerLiteral *expr)
1116 isl_multi_pw_aff *mpa;
1118 mpa = isl_multi_pw_aff_from_pw_aff(extract_affine(expr));
1119 mpa = isl_multi_pw_aff_from_range(mpa);
1120 return mpa;
1123 /* Try and extract an index expression from the given Expr.
1124 * Return NULL if it doesn't work out.
1126 __isl_give isl_multi_pw_aff *PetScan::extract_index(Expr *expr)
1128 switch (expr->getStmtClass()) {
1129 case Stmt::ImplicitCastExprClass:
1130 return extract_index(cast<ImplicitCastExpr>(expr));
1131 case Stmt::DeclRefExprClass:
1132 return extract_index(cast<DeclRefExpr>(expr));
1133 case Stmt::ArraySubscriptExprClass:
1134 return extract_index(cast<ArraySubscriptExpr>(expr));
1135 case Stmt::IntegerLiteralClass:
1136 return extract_index(cast<IntegerLiteral>(expr));
1137 case Stmt::MemberExprClass:
1138 return extract_index(cast<MemberExpr>(expr));
1139 default:
1140 unsupported(expr);
1142 return NULL;
1145 /* Given a partial index expression "base" and an extra index "index",
1146 * append the extra index to "base" and return the result.
1147 * Additionally, add the constraints that the extra index is non-negative.
1148 * If "index" represent a member access, i.e., if its range is a wrapped
1149 * relation, then we recursively extend the range of this nested relation.
1151 static __isl_give isl_multi_pw_aff *subscript(__isl_take isl_multi_pw_aff *base,
1152 __isl_take isl_pw_aff *index)
1154 isl_id *id;
1155 isl_set *domain;
1156 isl_multi_pw_aff *access;
1157 int member_access;
1159 member_access = isl_multi_pw_aff_range_is_wrapping(base);
1160 if (member_access < 0)
1161 goto error;
1162 if (member_access) {
1163 isl_multi_pw_aff *domain, *range;
1164 isl_id *id;
1166 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_out);
1167 domain = isl_multi_pw_aff_copy(base);
1168 domain = isl_multi_pw_aff_range_factor_domain(domain);
1169 range = isl_multi_pw_aff_range_factor_range(base);
1170 range = subscript(range, index);
1171 access = isl_multi_pw_aff_range_product(domain, range);
1172 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_out, id);
1173 return access;
1176 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_set);
1177 index = isl_pw_aff_from_range(index);
1178 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
1179 index = isl_pw_aff_intersect_domain(index, domain);
1180 access = isl_multi_pw_aff_from_pw_aff(index);
1181 access = isl_multi_pw_aff_flat_range_product(base, access);
1182 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_set, id);
1184 return access;
1185 error:
1186 isl_multi_pw_aff_free(base);
1187 isl_pw_aff_free(index);
1188 return NULL;
1191 /* Extract an index expression from the given array subscript expression.
1192 * If nesting is allowed in general, then we turn it on while
1193 * examining the index expression.
1195 * We first extract an index expression from the base.
1196 * This will result in an index expression with a range that corresponds
1197 * to the earlier indices.
1198 * We then extract the current index, restrict its domain
1199 * to those values that result in a non-negative index and
1200 * append the index to the base index expression.
1202 __isl_give isl_multi_pw_aff *PetScan::extract_index(ArraySubscriptExpr *expr)
1204 Expr *base = expr->getBase();
1205 Expr *idx = expr->getIdx();
1206 isl_pw_aff *index;
1207 isl_multi_pw_aff *base_access;
1208 isl_multi_pw_aff *access;
1209 bool save_nesting = nesting_enabled;
1211 nesting_enabled = allow_nested;
1213 base_access = extract_index(base);
1214 index = extract_affine(idx);
1216 nesting_enabled = save_nesting;
1218 access = subscript(base_access, index);
1220 return access;
1223 /* Construct a name for a member access by concatenating the name
1224 * of the array of structures and the member, separated by an underscore.
1226 * The caller is responsible for freeing the result.
1228 static char *member_access_name(isl_ctx *ctx, const char *base,
1229 const char *field)
1231 int len;
1232 char *name;
1234 len = strlen(base) + 1 + strlen(field);
1235 name = isl_alloc_array(ctx, char, len + 1);
1236 if (!name)
1237 return NULL;
1238 snprintf(name, len + 1, "%s_%s", base, field);
1240 return name;
1243 /* Given an index expression "base" for an element of an array of structures
1244 * and an expression "field" for the field member being accessed, construct
1245 * an index expression for an access to that member of the given structure.
1246 * In particular, take the range product of "base" and "field" and
1247 * attach a name to the result.
1249 static __isl_give isl_multi_pw_aff *member(__isl_take isl_multi_pw_aff *base,
1250 __isl_take isl_multi_pw_aff *field)
1252 isl_ctx *ctx;
1253 isl_multi_pw_aff *access;
1254 const char *base_name, *field_name;
1255 char *name;
1257 ctx = isl_multi_pw_aff_get_ctx(base);
1259 base_name = isl_multi_pw_aff_get_tuple_name(base, isl_dim_out);
1260 field_name = isl_multi_pw_aff_get_tuple_name(field, isl_dim_out);
1261 name = member_access_name(ctx, base_name, field_name);
1263 access = isl_multi_pw_aff_range_product(base, field);
1265 access = isl_multi_pw_aff_set_tuple_name(access, isl_dim_out, name);
1266 free(name);
1268 return access;
1271 /* Extract an index expression from a member expression.
1273 * If the base access (to the structure containing the member)
1274 * is of the form
1276 * [] -> A[..]
1278 * and the member is called "f", then the member access is of
1279 * the form
1281 * [] -> A_f[A[..] -> f[]]
1283 * If the member access is to an anonymous struct, then simply return
1285 * [] -> A[..]
1287 * If the member access in the source code is of the form
1289 * A->f
1291 * then it is treated as
1293 * A[0].f
1295 __isl_give isl_multi_pw_aff *PetScan::extract_index(MemberExpr *expr)
1297 Expr *base = expr->getBase();
1298 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
1299 isl_multi_pw_aff *base_access, *field_access;
1300 isl_id *id;
1301 isl_space *space;
1303 base_access = extract_index(base);
1305 if (expr->isArrow()) {
1306 isl_space *space = isl_space_params_alloc(ctx, 0);
1307 isl_local_space *ls = isl_local_space_from_space(space);
1308 isl_aff *aff = isl_aff_zero_on_domain(ls);
1309 isl_pw_aff *index = isl_pw_aff_from_aff(aff);
1310 base_access = subscript(base_access, index);
1313 if (field->isAnonymousStructOrUnion())
1314 return base_access;
1316 id = isl_id_alloc(ctx, field->getName().str().c_str(), field);
1317 space = isl_multi_pw_aff_get_domain_space(base_access);
1318 space = isl_space_from_domain(space);
1319 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1320 field_access = isl_multi_pw_aff_zero(space);
1322 return member(base_access, field_access);
1325 /* Check if "expr" calls function "minmax" with two arguments and if so
1326 * make lhs and rhs refer to these two arguments.
1328 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1330 CallExpr *call;
1331 FunctionDecl *fd;
1332 string name;
1334 if (expr->getStmtClass() != Stmt::CallExprClass)
1335 return false;
1337 call = cast<CallExpr>(expr);
1338 fd = call->getDirectCallee();
1339 if (!fd)
1340 return false;
1342 if (call->getNumArgs() != 2)
1343 return false;
1345 name = fd->getDeclName().getAsString();
1346 if (name != minmax)
1347 return false;
1349 lhs = call->getArg(0);
1350 rhs = call->getArg(1);
1352 return true;
1355 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1356 * lhs and rhs refer to the two arguments.
1358 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1360 return is_minmax(expr, "min", lhs, rhs);
1363 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1364 * lhs and rhs refer to the two arguments.
1366 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1368 return is_minmax(expr, "max", lhs, rhs);
1371 /* Return "lhs && rhs", defined on the shared definition domain.
1373 static __isl_give isl_pw_aff *pw_aff_and(__isl_take isl_pw_aff *lhs,
1374 __isl_take isl_pw_aff *rhs)
1376 isl_set *cond;
1377 isl_set *dom;
1379 dom = isl_set_intersect(isl_pw_aff_domain(isl_pw_aff_copy(lhs)),
1380 isl_pw_aff_domain(isl_pw_aff_copy(rhs)));
1381 cond = isl_set_intersect(isl_pw_aff_non_zero_set(lhs),
1382 isl_pw_aff_non_zero_set(rhs));
1383 return indicator_function(cond, dom);
1386 /* Return "lhs && rhs", with shortcut semantics.
1387 * That is, if lhs is false, then the result is defined even if rhs is not.
1388 * In practice, we compute lhs ? rhs : lhs.
1390 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1391 __isl_take isl_pw_aff *rhs)
1393 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1396 /* Return "lhs || rhs", with shortcut semantics.
1397 * That is, if lhs is true, then the result is defined even if rhs is not.
1398 * In practice, we compute lhs ? lhs : rhs.
1400 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1401 __isl_take isl_pw_aff *rhs)
1403 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1406 /* Extract an affine expressions representing the comparison "LHS op RHS"
1407 * "comp" is the original statement that "LHS op RHS" is derived from
1408 * and is used for diagnostics.
1410 * If the comparison is of the form
1412 * a <= min(b,c)
1414 * then the expression is constructed as the conjunction of
1415 * the comparisons
1417 * a <= b and a <= c
1419 * A similar optimization is performed for max(a,b) <= c.
1420 * We do this because that will lead to simpler representations
1421 * of the expression.
1422 * If isl is ever enhanced to explicitly deal with min and max expressions,
1423 * this optimization can be removed.
1425 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1426 Expr *LHS, Expr *RHS, Stmt *comp)
1428 isl_pw_aff *lhs;
1429 isl_pw_aff *rhs;
1430 isl_pw_aff *res;
1431 isl_set *cond;
1432 isl_set *dom;
1433 enum pet_op_type type;
1435 if (op == BO_GT)
1436 return extract_comparison(BO_LT, RHS, LHS, comp);
1437 if (op == BO_GE)
1438 return extract_comparison(BO_LE, RHS, LHS, comp);
1440 if (op == BO_LT || op == BO_LE) {
1441 Expr *expr1, *expr2;
1442 if (is_min(RHS, expr1, expr2)) {
1443 lhs = extract_comparison(op, LHS, expr1, comp);
1444 rhs = extract_comparison(op, LHS, expr2, comp);
1445 return pw_aff_and(lhs, rhs);
1447 if (is_max(LHS, expr1, expr2)) {
1448 lhs = extract_comparison(op, expr1, RHS, comp);
1449 rhs = extract_comparison(op, expr2, RHS, comp);
1450 return pw_aff_and(lhs, rhs);
1454 lhs = extract_affine(LHS);
1455 rhs = extract_affine(RHS);
1457 type = BinaryOperatorKind2pet_op_type(op);
1458 return pet_comparison(type, lhs, rhs);
1461 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1463 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1464 comp->getRHS(), comp);
1467 /* Extract an affine expression representing the negation (logical not)
1468 * of a subexpression.
1470 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1472 isl_set *set_cond, *dom;
1473 isl_pw_aff *cond, *res;
1475 cond = extract_condition(op->getSubExpr());
1477 dom = isl_pw_aff_domain(isl_pw_aff_copy(cond));
1479 set_cond = isl_pw_aff_zero_set(cond);
1481 res = indicator_function(set_cond, dom);
1483 return res;
1486 /* Extract an affine expression representing the disjunction (logical or)
1487 * or conjunction (logical and) of two subexpressions.
1489 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1491 isl_pw_aff *lhs, *rhs;
1493 lhs = extract_condition(comp->getLHS());
1494 rhs = extract_condition(comp->getRHS());
1496 switch (comp->getOpcode()) {
1497 case BO_LAnd:
1498 return pw_aff_and_then(lhs, rhs);
1499 case BO_LOr:
1500 return pw_aff_or_else(lhs, rhs);
1501 default:
1502 isl_pw_aff_free(lhs);
1503 isl_pw_aff_free(rhs);
1506 unsupported(comp);
1507 return NULL;
1510 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1512 switch (expr->getOpcode()) {
1513 case UO_LNot:
1514 return extract_boolean(expr);
1515 default:
1516 unsupported(expr);
1517 return NULL;
1521 /* Extract the affine expression "expr != 0 ? 1 : 0".
1523 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1525 isl_pw_aff *res;
1526 isl_set *set, *dom;
1528 res = extract_affine(expr);
1530 dom = isl_pw_aff_domain(isl_pw_aff_copy(res));
1531 set = isl_pw_aff_non_zero_set(res);
1533 res = indicator_function(set, dom);
1535 return res;
1538 /* Extract an affine expression from a boolean expression.
1539 * In particular, return the expression "expr ? 1 : 0".
1541 * If the expression doesn't look like a condition, we assume it
1542 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1544 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1546 BinaryOperator *comp;
1548 if (!expr) {
1549 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1550 return indicator_function(u, isl_set_copy(u));
1553 if (expr->getStmtClass() == Stmt::ParenExprClass)
1554 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1556 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1557 return extract_condition(cast<UnaryOperator>(expr));
1559 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1560 return extract_implicit_condition(expr);
1562 comp = cast<BinaryOperator>(expr);
1563 switch (comp->getOpcode()) {
1564 case BO_LT:
1565 case BO_LE:
1566 case BO_GT:
1567 case BO_GE:
1568 case BO_EQ:
1569 case BO_NE:
1570 return extract_comparison(comp);
1571 case BO_LAnd:
1572 case BO_LOr:
1573 return extract_boolean(comp);
1574 default:
1575 return extract_implicit_condition(expr);
1579 /* Construct a pet_expr representing a unary operator expression.
1581 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1583 pet_expr *arg;
1584 enum pet_op_type op;
1586 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1587 if (op == pet_op_last) {
1588 unsupported(expr);
1589 return NULL;
1592 arg = extract_expr(expr->getSubExpr());
1594 if (expr->isIncrementDecrementOp() &&
1595 pet_expr_get_type(arg) == pet_expr_access) {
1596 arg = mark_write(arg);
1597 arg = pet_expr_access_set_read(arg, 1);
1600 return pet_expr_new_unary(op, arg);
1603 /* Mark the given access pet_expr as a write.
1604 * If a scalar is being accessed, then mark its value
1605 * as unknown in assigned_value.
1607 __isl_give pet_expr *PetScan::mark_write(__isl_take pet_expr *access)
1609 isl_id *id;
1610 ValueDecl *decl;
1612 access = pet_expr_access_set_write(access, 1);
1613 access = pet_expr_access_set_read(access, 0);
1615 if (!access || !pet_expr_is_scalar_access(access))
1616 return access;
1618 id = pet_expr_access_get_id(access);
1619 decl = (ValueDecl *) isl_id_get_user(id);
1620 clear_assignment(assigned_value, decl);
1621 isl_id_free(id);
1623 return access;
1626 /* Assign "rhs" to "lhs".
1628 * In particular, if "lhs" is a scalar variable, then mark
1629 * the variable as having been assigned. If, furthermore, "rhs"
1630 * is an affine expression, then keep track of this value in assigned_value
1631 * so that we can plug it in when we later come across the same variable.
1633 void PetScan::assign(__isl_keep pet_expr *lhs, Expr *rhs)
1635 isl_id *id;
1636 ValueDecl *decl;
1637 isl_pw_aff *pa;
1639 if (!lhs)
1640 return;
1641 if (!pet_expr_is_scalar_access(lhs))
1642 return;
1644 id = pet_expr_access_get_id(lhs);
1645 decl = (ValueDecl *) isl_id_get_user(id);
1646 isl_id_free(id);
1648 pa = try_extract_affine(rhs);
1649 clear_assignment(assigned_value, decl);
1650 if (!pa)
1651 return;
1652 assigned_value[decl] = pa;
1653 insert_expression(pa);
1656 /* Construct a pet_expr representing a binary operator expression.
1658 * If the top level operator is an assignment and the LHS is an access,
1659 * then we mark that access as a write. If the operator is a compound
1660 * assignment, the access is marked as both a read and a write.
1662 * If "expr" assigns something to a scalar variable, then we mark
1663 * the variable as having been assigned. If, furthermore, the expression
1664 * is affine, then keep track of this value in assigned_value
1665 * so that we can plug it in when we later come across the same variable.
1667 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1669 int type_size;
1670 pet_expr *lhs, *rhs;
1671 enum pet_op_type op;
1673 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1674 if (op == pet_op_last) {
1675 unsupported(expr);
1676 return NULL;
1679 lhs = extract_expr(expr->getLHS());
1680 rhs = extract_expr(expr->getRHS());
1682 if (expr->isAssignmentOp() &&
1683 pet_expr_get_type(lhs) == pet_expr_access) {
1684 lhs = mark_write(lhs);
1685 if (expr->isCompoundAssignmentOp())
1686 lhs = pet_expr_access_set_read(lhs, 1);
1689 if (expr->getOpcode() == BO_Assign)
1690 assign(lhs, expr->getRHS());
1692 type_size = get_type_size(expr->getType(), ast_context);
1693 return pet_expr_new_binary(type_size, op, lhs, rhs);
1696 /* Construct a pet_scop with a single statement killing the entire
1697 * array "array".
1699 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1701 isl_id *id;
1702 isl_space *space;
1703 isl_multi_pw_aff *index;
1704 isl_map *access;
1705 pet_expr *expr;
1707 if (!array)
1708 return NULL;
1709 access = isl_map_from_range(isl_set_copy(array->extent));
1710 id = isl_set_get_tuple_id(array->extent);
1711 space = isl_space_alloc(ctx, 0, 0, 0);
1712 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1713 index = isl_multi_pw_aff_zero(space);
1714 expr = pet_expr_kill_from_access_and_index(access, index);
1715 return extract(stmt, expr);
1718 /* Construct a pet_scop for a (single) variable declaration.
1720 * The scop contains the variable being declared (as an array)
1721 * and a statement killing the array.
1723 * If the variable is initialized in the AST, then the scop
1724 * also contains an assignment to the variable.
1726 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1728 int type_size;
1729 Decl *decl;
1730 VarDecl *vd;
1731 pet_expr *lhs, *rhs, *pe;
1732 struct pet_scop *scop_decl, *scop;
1733 struct pet_array *array;
1735 if (!stmt->isSingleDecl()) {
1736 unsupported(stmt);
1737 return NULL;
1740 decl = stmt->getSingleDecl();
1741 vd = cast<VarDecl>(decl);
1743 array = extract_array(ctx, vd, NULL);
1744 if (array)
1745 array->declared = 1;
1746 scop_decl = kill(stmt, array);
1747 scop_decl = pet_scop_add_array(scop_decl, array);
1749 if (!vd->getInit())
1750 return scop_decl;
1752 lhs = extract_access_expr(vd);
1753 rhs = extract_expr(vd->getInit());
1755 lhs = mark_write(lhs);
1756 assign(lhs, vd->getInit());
1758 type_size = get_type_size(vd->getType(), ast_context);
1759 pe = pet_expr_new_binary(type_size, pet_op_assign, lhs, rhs);
1760 scop = extract(stmt, pe);
1762 scop_decl = pet_scop_prefix(scop_decl, 0);
1763 scop = pet_scop_prefix(scop, 1);
1765 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1767 return scop;
1770 /* Construct a pet_expr representing a conditional operation.
1772 * We first try to extract the condition as an affine expression.
1773 * If that fails, we construct a pet_expr tree representing the condition.
1775 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1777 pet_expr *cond, *lhs, *rhs;
1778 isl_pw_aff *pa;
1780 pa = try_extract_affine(expr->getCond());
1781 if (pa) {
1782 isl_multi_pw_aff *test = isl_multi_pw_aff_from_pw_aff(pa);
1783 test = isl_multi_pw_aff_from_range(test);
1784 cond = pet_expr_from_index(test);
1785 } else
1786 cond = extract_expr(expr->getCond());
1787 lhs = extract_expr(expr->getTrueExpr());
1788 rhs = extract_expr(expr->getFalseExpr());
1790 return pet_expr_new_ternary(cond, lhs, rhs);
1793 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1795 return extract_expr(expr->getSubExpr());
1798 /* Construct a pet_expr representing a floating point value.
1800 * If the floating point literal does not appear in a macro,
1801 * then we use the original representation in the source code
1802 * as the string representation. Otherwise, we use the pretty
1803 * printer to produce a string representation.
1805 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1807 double d;
1808 string s;
1809 const LangOptions &LO = PP.getLangOpts();
1810 SourceLocation loc = expr->getLocation();
1812 if (!loc.isMacroID()) {
1813 SourceManager &SM = PP.getSourceManager();
1814 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1815 s = string(SM.getCharacterData(loc), len);
1816 } else {
1817 llvm::raw_string_ostream S(s);
1818 expr->printPretty(S, 0, PrintingPolicy(LO));
1819 S.str();
1821 d = expr->getValueAsApproximateDouble();
1822 return pet_expr_new_double(ctx, d, s.c_str());
1825 /* Convert the index expression "index" into an access pet_expr of type "qt".
1827 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
1828 __isl_take isl_multi_pw_aff *index)
1830 pet_expr *pe;
1831 int depth;
1832 int type_size;
1834 depth = extract_depth(index);
1835 type_size = get_type_size(qt, ast_context);
1837 pe = pet_expr_from_index_and_depth(type_size, index, depth);
1839 return pe;
1842 /* Extract an index expression from "expr" and then convert it into
1843 * an access pet_expr.
1845 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
1847 return extract_access_expr(expr->getType(), extract_index(expr));
1850 /* Extract an index expression from "decl" and then convert it into
1851 * an access pet_expr.
1853 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1855 return extract_access_expr(decl->getType(), extract_index(decl));
1858 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
1860 return extract_expr(expr->getSubExpr());
1863 /* Extract an assume statement from the argument "expr"
1864 * of a __pencil_assume statement.
1866 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
1868 isl_pw_aff *cond;
1869 pet_expr *res;
1871 cond = try_extract_affine_condition(expr);
1872 if (!cond) {
1873 res = extract_expr(expr);
1874 } else {
1875 isl_multi_pw_aff *index;
1876 index = isl_multi_pw_aff_from_pw_aff(cond);
1877 index = isl_multi_pw_aff_from_range(index);
1878 res = pet_expr_from_index(index);
1880 return pet_expr_new_unary(pet_op_assume, res);
1883 /* Construct a pet_expr corresponding to the function call argument "expr".
1884 * The argument appears in position "pos" of a call to function "fd".
1886 * If we are passing along a pointer to an array element
1887 * or an entire row or even higher dimensional slice of an array,
1888 * then the function being called may write into the array.
1890 * We assume here that if the function is declared to take a pointer
1891 * to a const type, then the function will perform a read
1892 * and that otherwise, it will perform a write.
1894 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
1895 Expr *expr)
1897 pet_expr *res;
1898 int is_addr = 0, is_partial = 0;
1899 Stmt::StmtClass sc;
1901 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
1902 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
1903 expr = ice->getSubExpr();
1905 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
1906 UnaryOperator *op = cast<UnaryOperator>(expr);
1907 if (op->getOpcode() == UO_AddrOf) {
1908 is_addr = 1;
1909 expr = op->getSubExpr();
1912 res = extract_expr(expr);
1913 if (!res)
1914 return NULL;
1915 sc = expr->getStmtClass();
1916 if ((sc == Stmt::ArraySubscriptExprClass ||
1917 sc == Stmt::MemberExprClass) &&
1918 array_depth(expr->getType().getTypePtr()) > 0)
1919 is_partial = 1;
1920 if ((is_addr || is_partial) &&
1921 pet_expr_get_type(res) == pet_expr_access) {
1922 ParmVarDecl *parm;
1923 if (!fd->hasPrototype()) {
1924 report_prototype_required(expr);
1925 return pet_expr_free(res);
1927 parm = fd->getParamDecl(pos);
1928 if (!const_base(parm->getType()))
1929 res = mark_write(res);
1932 if (is_addr)
1933 res = pet_expr_new_unary(pet_op_address_of, res);
1934 return res;
1937 /* Construct a pet_expr representing a function call.
1939 * In the special case of a "call" to __pencil_assume,
1940 * construct an assume expression instead.
1942 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1944 pet_expr *res = NULL;
1945 FunctionDecl *fd;
1946 string name;
1947 unsigned n_arg;
1949 fd = expr->getDirectCallee();
1950 if (!fd) {
1951 unsupported(expr);
1952 return NULL;
1955 name = fd->getDeclName().getAsString();
1956 n_arg = expr->getNumArgs();
1958 if (n_arg == 1 && name == "__pencil_assume")
1959 return extract_assume(expr->getArg(0));
1961 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1962 if (!res)
1963 return NULL;
1965 for (int i = 0; i < n_arg; ++i) {
1966 Expr *arg = expr->getArg(i);
1967 res = pet_expr_set_arg(res, i,
1968 PetScan::extract_argument(fd, i, arg));
1971 return res;
1974 /* Construct a pet_expr representing a (C style) cast.
1976 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1978 pet_expr *arg;
1979 QualType type;
1981 arg = extract_expr(expr->getSubExpr());
1982 if (!arg)
1983 return NULL;
1985 type = expr->getTypeAsWritten();
1986 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1989 /* Construct a pet_expr representing an integer.
1991 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1993 return pet_expr_new_int(extract_int(expr));
1996 /* Try and construct a pet_expr representing "expr".
1998 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
2000 switch (expr->getStmtClass()) {
2001 case Stmt::UnaryOperatorClass:
2002 return extract_expr(cast<UnaryOperator>(expr));
2003 case Stmt::CompoundAssignOperatorClass:
2004 case Stmt::BinaryOperatorClass:
2005 return extract_expr(cast<BinaryOperator>(expr));
2006 case Stmt::ImplicitCastExprClass:
2007 return extract_expr(cast<ImplicitCastExpr>(expr));
2008 case Stmt::ArraySubscriptExprClass:
2009 case Stmt::DeclRefExprClass:
2010 case Stmt::MemberExprClass:
2011 return extract_access_expr(expr);
2012 case Stmt::IntegerLiteralClass:
2013 return extract_expr(cast<IntegerLiteral>(expr));
2014 case Stmt::FloatingLiteralClass:
2015 return extract_expr(cast<FloatingLiteral>(expr));
2016 case Stmt::ParenExprClass:
2017 return extract_expr(cast<ParenExpr>(expr));
2018 case Stmt::ConditionalOperatorClass:
2019 return extract_expr(cast<ConditionalOperator>(expr));
2020 case Stmt::CallExprClass:
2021 return extract_expr(cast<CallExpr>(expr));
2022 case Stmt::CStyleCastExprClass:
2023 return extract_expr(cast<CStyleCastExpr>(expr));
2024 default:
2025 unsupported(expr);
2027 return NULL;
2030 /* Check if the given initialization statement is an assignment.
2031 * If so, return that assignment. Otherwise return NULL.
2033 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
2035 BinaryOperator *ass;
2037 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
2038 return NULL;
2040 ass = cast<BinaryOperator>(init);
2041 if (ass->getOpcode() != BO_Assign)
2042 return NULL;
2044 return ass;
2047 /* Check if the given initialization statement is a declaration
2048 * of a single variable.
2049 * If so, return that declaration. Otherwise return NULL.
2051 Decl *PetScan::initialization_declaration(Stmt *init)
2053 DeclStmt *decl;
2055 if (init->getStmtClass() != Stmt::DeclStmtClass)
2056 return NULL;
2058 decl = cast<DeclStmt>(init);
2060 if (!decl->isSingleDecl())
2061 return NULL;
2063 return decl->getSingleDecl();
2066 /* Given the assignment operator in the initialization of a for loop,
2067 * extract the induction variable, i.e., the (integer)variable being
2068 * assigned.
2070 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
2072 Expr *lhs;
2073 DeclRefExpr *ref;
2074 ValueDecl *decl;
2075 const Type *type;
2077 lhs = init->getLHS();
2078 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2079 unsupported(init);
2080 return NULL;
2083 ref = cast<DeclRefExpr>(lhs);
2084 decl = ref->getDecl();
2085 type = decl->getType().getTypePtr();
2087 if (!type->isIntegerType()) {
2088 unsupported(lhs);
2089 return NULL;
2092 return decl;
2095 /* Given the initialization statement of a for loop and the single
2096 * declaration in this initialization statement,
2097 * extract the induction variable, i.e., the (integer) variable being
2098 * declared.
2100 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
2102 VarDecl *vd;
2104 vd = cast<VarDecl>(decl);
2106 const QualType type = vd->getType();
2107 if (!type->isIntegerType()) {
2108 unsupported(init);
2109 return NULL;
2112 if (!vd->getInit()) {
2113 unsupported(init);
2114 return NULL;
2117 return vd;
2120 /* Check that op is of the form iv++ or iv--.
2121 * Return an affine expression "1" or "-1" accordingly.
2123 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
2124 clang::UnaryOperator *op, clang::ValueDecl *iv)
2126 Expr *sub;
2127 DeclRefExpr *ref;
2128 isl_space *space;
2129 isl_aff *aff;
2131 if (!op->isIncrementDecrementOp()) {
2132 unsupported(op);
2133 return NULL;
2136 sub = op->getSubExpr();
2137 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
2138 unsupported(op);
2139 return NULL;
2142 ref = cast<DeclRefExpr>(sub);
2143 if (ref->getDecl() != iv) {
2144 unsupported(op);
2145 return NULL;
2148 space = isl_space_params_alloc(ctx, 0);
2149 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2151 if (op->isIncrementOp())
2152 aff = isl_aff_add_constant_si(aff, 1);
2153 else
2154 aff = isl_aff_add_constant_si(aff, -1);
2156 return isl_pw_aff_from_aff(aff);
2159 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
2160 * has a single constant expression, then put this constant in *user.
2161 * The caller is assumed to have checked that this function will
2162 * be called exactly once.
2164 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
2165 void *user)
2167 isl_val **inc = (isl_val **)user;
2168 int res = 0;
2170 if (isl_aff_is_cst(aff))
2171 *inc = isl_aff_get_constant_val(aff);
2172 else
2173 res = -1;
2175 isl_set_free(set);
2176 isl_aff_free(aff);
2178 return res;
2181 /* Check if op is of the form
2183 * iv = iv + inc
2185 * and return inc as an affine expression.
2187 * We extract an affine expression from the RHS, subtract iv and return
2188 * the result.
2190 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
2191 clang::ValueDecl *iv)
2193 Expr *lhs;
2194 DeclRefExpr *ref;
2195 isl_id *id;
2196 isl_space *dim;
2197 isl_aff *aff;
2198 isl_pw_aff *val;
2200 if (op->getOpcode() != BO_Assign) {
2201 unsupported(op);
2202 return NULL;
2205 lhs = op->getLHS();
2206 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2207 unsupported(op);
2208 return NULL;
2211 ref = cast<DeclRefExpr>(lhs);
2212 if (ref->getDecl() != iv) {
2213 unsupported(op);
2214 return NULL;
2217 val = extract_affine(op->getRHS());
2219 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2221 dim = isl_space_params_alloc(ctx, 1);
2222 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2223 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2224 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2226 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
2228 return val;
2231 /* Check that op is of the form iv += cst or iv -= cst
2232 * and return an affine expression corresponding oto cst or -cst accordingly.
2234 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
2235 CompoundAssignOperator *op, clang::ValueDecl *iv)
2237 Expr *lhs;
2238 DeclRefExpr *ref;
2239 bool neg = false;
2240 isl_pw_aff *val;
2241 BinaryOperatorKind opcode;
2243 opcode = op->getOpcode();
2244 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
2245 unsupported(op);
2246 return NULL;
2248 if (opcode == BO_SubAssign)
2249 neg = true;
2251 lhs = op->getLHS();
2252 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2253 unsupported(op);
2254 return NULL;
2257 ref = cast<DeclRefExpr>(lhs);
2258 if (ref->getDecl() != iv) {
2259 unsupported(op);
2260 return NULL;
2263 val = extract_affine(op->getRHS());
2264 if (neg)
2265 val = isl_pw_aff_neg(val);
2267 return val;
2270 /* Check that the increment of the given for loop increments
2271 * (or decrements) the induction variable "iv" and return
2272 * the increment as an affine expression if successful.
2274 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
2275 ValueDecl *iv)
2277 Stmt *inc = stmt->getInc();
2279 if (!inc) {
2280 report_missing_increment(stmt);
2281 return NULL;
2284 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
2285 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
2286 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
2287 return extract_compound_increment(
2288 cast<CompoundAssignOperator>(inc), iv);
2289 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
2290 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
2292 unsupported(inc);
2293 return NULL;
2296 /* Embed the given iteration domain in an extra outer loop
2297 * with induction variable "var".
2298 * If this variable appeared as a parameter in the constraints,
2299 * it is replaced by the new outermost dimension.
2301 static __isl_give isl_set *embed(__isl_take isl_set *set,
2302 __isl_take isl_id *var)
2304 int pos;
2306 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
2307 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
2308 if (pos >= 0) {
2309 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
2310 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2313 isl_id_free(var);
2314 return set;
2317 /* Return those elements in the space of "cond" that come after
2318 * (based on "sign") an element in "cond".
2320 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
2322 isl_map *previous_to_this;
2324 if (sign > 0)
2325 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
2326 else
2327 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
2329 cond = isl_set_apply(cond, previous_to_this);
2331 return cond;
2334 /* Create the infinite iteration domain
2336 * { [id] : id >= 0 }
2338 * If "scop" has an affine skip of type pet_skip_later,
2339 * then remove those iterations i that have an earlier iteration
2340 * where the skip condition is satisfied, meaning that iteration i
2341 * is not executed.
2342 * Since we are dealing with a loop without loop iterator,
2343 * the skip condition cannot refer to the current loop iterator and
2344 * so effectively, the returned set is of the form
2346 * { [0]; [id] : id >= 1 and not skip }
2348 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
2349 struct pet_scop *scop)
2351 isl_ctx *ctx = isl_id_get_ctx(id);
2352 isl_set *domain;
2353 isl_set *skip;
2355 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
2356 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
2358 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
2359 return domain;
2361 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2362 skip = embed(skip, isl_id_copy(id));
2363 skip = isl_set_intersect(skip , isl_set_copy(domain));
2364 domain = isl_set_subtract(domain, after(skip, 1));
2366 return domain;
2369 /* Create an identity affine expression on the space containing "domain",
2370 * which is assumed to be one-dimensional.
2372 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
2374 isl_local_space *ls;
2376 ls = isl_local_space_from_space(isl_set_get_space(domain));
2377 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
2380 /* Create an affine expression that maps elements
2381 * of a single-dimensional array "id_test" to the previous element
2382 * (according to "inc"), provided this element belongs to "domain".
2383 * That is, create the affine expression
2385 * { id[x] -> id[x - inc] : x - inc in domain }
2387 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
2388 __isl_take isl_set *domain, __isl_take isl_val *inc)
2390 isl_space *space;
2391 isl_local_space *ls;
2392 isl_aff *aff;
2393 isl_multi_pw_aff *prev;
2395 space = isl_set_get_space(domain);
2396 ls = isl_local_space_from_space(space);
2397 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2398 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
2399 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
2400 domain = isl_set_preimage_multi_pw_aff(domain,
2401 isl_multi_pw_aff_copy(prev));
2402 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
2403 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
2405 return prev;
2408 /* Add an implication to "scop" expressing that if an element of
2409 * virtual array "id_test" has value "satisfied" then all previous elements
2410 * of this array also have that value. The set of previous elements
2411 * is bounded by "domain". If "sign" is negative then the iterator
2412 * is decreasing and we express that all subsequent array elements
2413 * (but still defined previously) have the same value.
2415 static struct pet_scop *add_implication(struct pet_scop *scop,
2416 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
2417 int satisfied)
2419 isl_space *space;
2420 isl_map *map;
2422 domain = isl_set_set_tuple_id(domain, id_test);
2423 space = isl_set_get_space(domain);
2424 if (sign > 0)
2425 map = isl_map_lex_ge(space);
2426 else
2427 map = isl_map_lex_le(space);
2428 map = isl_map_intersect_range(map, domain);
2429 scop = pet_scop_add_implication(scop, map, satisfied);
2431 return scop;
2434 /* Add a filter to "scop" that imposes that it is only executed
2435 * when the variable identified by "id_test" has a zero value
2436 * for all previous iterations of "domain".
2438 * In particular, add a filter that imposes that the array
2439 * has a zero value at the previous iteration of domain and
2440 * add an implication that implies that it then has that
2441 * value for all previous iterations.
2443 static struct pet_scop *scop_add_break(struct pet_scop *scop,
2444 __isl_take isl_id *id_test, __isl_take isl_set *domain,
2445 __isl_take isl_val *inc)
2447 isl_multi_pw_aff *prev;
2448 int sign = isl_val_sgn(inc);
2450 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2451 scop = add_implication(scop, id_test, domain, sign, 0);
2452 scop = pet_scop_filter(scop, prev, 0);
2454 return scop;
2457 /* Construct a pet_scop for an infinite loop around the given body.
2459 * We extract a pet_scop for the body and then embed it in a loop with
2460 * iteration domain
2462 * { [t] : t >= 0 }
2464 * and schedule
2466 * { [t] -> [t] }
2468 * If the body contains any break, then it is taken into
2469 * account in infinite_domain (if the skip condition is affine)
2470 * or in scop_add_break (if the skip condition is not affine).
2472 * If we were only able to extract part of the body, then simply
2473 * return that part.
2475 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2477 isl_id *id, *id_test;
2478 isl_set *domain;
2479 isl_aff *ident;
2480 struct pet_scop *scop;
2481 bool has_var_break;
2483 scop = extract(body);
2484 if (!scop)
2485 return NULL;
2486 if (partial)
2487 return scop;
2489 id = isl_id_alloc(ctx, "t", NULL);
2490 domain = infinite_domain(isl_id_copy(id), scop);
2491 ident = identity_aff(domain);
2493 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2494 if (has_var_break)
2495 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
2497 scop = pet_scop_embed(scop, isl_set_copy(domain),
2498 isl_aff_copy(ident), ident, id);
2499 if (has_var_break)
2500 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
2501 else
2502 isl_set_free(domain);
2504 return scop;
2507 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2509 * for (;;)
2510 * body
2513 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2515 clear_assignments clear(assigned_value);
2516 clear.TraverseStmt(stmt->getBody());
2518 return extract_infinite_loop(stmt->getBody());
2521 /* Create an index expression for an access to a virtual array
2522 * representing the result of a condition.
2523 * Unlike other accessed data, the id of the array is NULL as
2524 * there is no ValueDecl in the program corresponding to the virtual
2525 * array.
2526 * The array starts out as a scalar, but grows along with the
2527 * statement writing to the array in pet_scop_embed.
2529 static __isl_give isl_multi_pw_aff *create_test_index(isl_ctx *ctx, int test_nr)
2531 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2532 isl_id *id;
2533 char name[50];
2535 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2536 id = isl_id_alloc(ctx, name, NULL);
2537 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2538 return isl_multi_pw_aff_zero(dim);
2541 /* Add an array with the given extent (range of "index") to the list
2542 * of arrays in "scop" and return the extended pet_scop.
2543 * The array is marked as attaining values 0 and 1 only and
2544 * as each element being assigned at most once.
2546 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2547 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
2549 int int_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2551 return pet_scop_add_boolean_array(scop, isl_multi_pw_aff_copy(index),
2552 int_size);
2555 /* Construct a pet_scop for a while loop of the form
2557 * while (pa)
2558 * body
2560 * In particular, construct a scop for an infinite loop around body and
2561 * intersect the domain with the affine expression.
2562 * Note that this intersection may result in an empty loop.
2564 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2565 Stmt *body)
2567 struct pet_scop *scop;
2568 isl_set *dom;
2569 isl_set *valid;
2571 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2572 dom = isl_pw_aff_non_zero_set(pa);
2573 scop = extract_infinite_loop(body);
2574 scop = pet_scop_restrict(scop, dom);
2575 scop = pet_scop_restrict_context(scop, valid);
2577 return scop;
2580 /* Construct a scop for a while, given the scops for the condition
2581 * and the body, the filter identifier and the iteration domain of
2582 * the while loop.
2584 * In particular, the scop for the condition is filtered to depend
2585 * on "id_test" evaluating to true for all previous iterations
2586 * of the loop, while the scop for the body is filtered to depend
2587 * on "id_test" evaluating to true for all iterations up to the
2588 * current iteration.
2589 * The actual filter only imposes that this virtual array has
2590 * value one on the previous or the current iteration.
2591 * The fact that this condition also applies to the previous
2592 * iterations is enforced by an implication.
2594 * These filtered scops are then combined into a single scop.
2596 * "sign" is positive if the iterator increases and negative
2597 * if it decreases.
2599 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2600 struct pet_scop *scop_body, __isl_take isl_id *id_test,
2601 __isl_take isl_set *domain, __isl_take isl_val *inc)
2603 isl_ctx *ctx = isl_set_get_ctx(domain);
2604 isl_space *space;
2605 isl_multi_pw_aff *test_index;
2606 isl_multi_pw_aff *prev;
2607 int sign = isl_val_sgn(inc);
2608 struct pet_scop *scop;
2610 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2611 scop_cond = pet_scop_filter(scop_cond, prev, 1);
2613 space = isl_space_map_from_set(isl_set_get_space(domain));
2614 test_index = isl_multi_pw_aff_identity(space);
2615 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
2616 isl_id_copy(id_test));
2617 scop_body = pet_scop_filter(scop_body, test_index, 1);
2619 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
2620 scop = add_implication(scop, id_test, domain, sign, 1);
2622 return scop;
2625 /* Check if the while loop is of the form
2627 * while (affine expression)
2628 * body
2630 * If so, call extract_affine_while to construct a scop.
2632 * Otherwise, construct a generic while scop, with iteration domain
2633 * { [t] : t >= 0 }. The scop consists of two parts, one for
2634 * evaluating the condition and one for the body.
2635 * The schedule is adjusted to reflect that the condition is evaluated
2636 * before the body is executed and the body is filtered to depend
2637 * on the result of the condition evaluating to true on all iterations
2638 * up to the current iteration, while the evaluation of the condition itself
2639 * is filtered to depend on the result of the condition evaluating to true
2640 * on all previous iterations.
2641 * The context of the scop representing the body is dropped
2642 * because we don't know how many times the body will be executed,
2643 * if at all.
2645 * If the body contains any break, then it is taken into
2646 * account in infinite_domain (if the skip condition is affine)
2647 * or in scop_add_break (if the skip condition is not affine).
2649 * If we were only able to extract part of the body, then simply
2650 * return that part.
2652 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2654 Expr *cond;
2655 int test_nr, stmt_nr;
2656 isl_id *id, *id_test, *id_break_test;
2657 isl_multi_pw_aff *test_index;
2658 isl_set *domain;
2659 isl_aff *ident;
2660 isl_pw_aff *pa;
2661 struct pet_scop *scop, *scop_body;
2662 bool has_var_break;
2664 cond = stmt->getCond();
2665 if (!cond) {
2666 unsupported(stmt);
2667 return NULL;
2670 clear_assignments clear(assigned_value);
2671 clear.TraverseStmt(stmt->getBody());
2673 pa = try_extract_affine_condition(cond);
2674 if (pa)
2675 return extract_affine_while(pa, stmt->getBody());
2677 if (!allow_nested) {
2678 unsupported(stmt);
2679 return NULL;
2682 test_nr = n_test++;
2683 stmt_nr = n_stmt++;
2684 scop_body = extract(stmt->getBody());
2685 if (partial)
2686 return scop_body;
2688 test_index = create_test_index(ctx, test_nr);
2689 scop = extract_non_affine_condition(cond, stmt_nr,
2690 isl_multi_pw_aff_copy(test_index));
2691 scop = scop_add_array(scop, test_index, ast_context);
2692 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2693 isl_multi_pw_aff_free(test_index);
2695 id = isl_id_alloc(ctx, "t", NULL);
2696 domain = infinite_domain(isl_id_copy(id), scop_body);
2697 ident = identity_aff(domain);
2699 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2700 if (has_var_break)
2701 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2703 scop = pet_scop_prefix(scop, 0);
2704 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_aff_copy(ident),
2705 isl_aff_copy(ident), isl_id_copy(id));
2706 scop_body = pet_scop_reset_context(scop_body);
2707 scop_body = pet_scop_prefix(scop_body, 1);
2708 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2709 isl_aff_copy(ident), ident, id);
2711 if (has_var_break) {
2712 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2713 isl_set_copy(domain), isl_val_one(ctx));
2714 scop_body = scop_add_break(scop_body, id_break_test,
2715 isl_set_copy(domain), isl_val_one(ctx));
2717 scop = scop_add_while(scop, scop_body, id_test, domain,
2718 isl_val_one(ctx));
2720 return scop;
2723 /* Check whether "cond" expresses a simple loop bound
2724 * on the only set dimension.
2725 * In particular, if "up" is set then "cond" should contain only
2726 * upper bounds on the set dimension.
2727 * Otherwise, it should contain only lower bounds.
2729 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2731 if (isl_val_is_pos(inc))
2732 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2733 else
2734 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2737 /* Extend a condition on a given iteration of a loop to one that
2738 * imposes the same condition on all previous iterations.
2739 * "domain" expresses the lower [upper] bound on the iterations
2740 * when inc is positive [negative].
2742 * In particular, we construct the condition (when inc is positive)
2744 * forall i' : (domain(i') and i' <= i) => cond(i')
2746 * which is equivalent to
2748 * not exists i' : domain(i') and i' <= i and not cond(i')
2750 * We construct this set by negating cond, applying a map
2752 * { [i'] -> [i] : domain(i') and i' <= i }
2754 * and then negating the result again.
2756 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2757 __isl_take isl_set *domain, __isl_take isl_val *inc)
2759 isl_map *previous_to_this;
2761 if (isl_val_is_pos(inc))
2762 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2763 else
2764 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2766 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2768 cond = isl_set_complement(cond);
2769 cond = isl_set_apply(cond, previous_to_this);
2770 cond = isl_set_complement(cond);
2772 isl_val_free(inc);
2774 return cond;
2777 /* Construct a domain of the form
2779 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2781 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2782 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2784 isl_aff *aff;
2785 isl_space *dim;
2786 isl_set *set;
2788 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2789 dim = isl_pw_aff_get_domain_space(init);
2790 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2791 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2792 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2794 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2795 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2796 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2797 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2799 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2801 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2803 return isl_set_params(set);
2806 /* Assuming "cond" represents a bound on a loop where the loop
2807 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2808 * is possible.
2810 * Under the given assumptions, wrapping is only possible if "cond" allows
2811 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2812 * increasing iterator and 0 in case of a decreasing iterator.
2814 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2815 __isl_keep isl_val *inc)
2817 bool cw;
2818 isl_ctx *ctx;
2819 isl_val *limit;
2820 isl_set *test;
2822 test = isl_set_copy(cond);
2824 ctx = isl_set_get_ctx(test);
2825 if (isl_val_is_neg(inc))
2826 limit = isl_val_zero(ctx);
2827 else {
2828 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2829 limit = isl_val_2exp(limit);
2830 limit = isl_val_sub_ui(limit, 1);
2833 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2834 cw = !isl_set_is_empty(test);
2835 isl_set_free(test);
2837 return cw;
2840 /* Given a one-dimensional space, construct the following affine expression
2841 * on this space
2843 * { [v] -> [v mod 2^width] }
2845 * where width is the number of bits used to represent the values
2846 * of the unsigned variable "iv".
2848 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2849 ValueDecl *iv)
2851 isl_ctx *ctx;
2852 isl_val *mod;
2853 isl_aff *aff;
2855 ctx = isl_space_get_ctx(dim);
2856 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2857 mod = isl_val_2exp(mod);
2859 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2860 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2861 aff = isl_aff_mod_val(aff, mod);
2863 return aff;
2866 /* Project out the parameter "id" from "set".
2868 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2869 __isl_keep isl_id *id)
2871 int pos;
2873 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2874 if (pos >= 0)
2875 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2877 return set;
2880 /* Compute the set of parameters for which "set1" is a subset of "set2".
2882 * set1 is a subset of set2 if
2884 * forall i in set1 : i in set2
2886 * or
2888 * not exists i in set1 and i not in set2
2890 * i.e.,
2892 * not exists i in set1 \ set2
2894 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2895 __isl_take isl_set *set2)
2897 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2900 /* Compute the set of parameter values for which "cond" holds
2901 * on the next iteration for each element of "dom".
2903 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2904 * and then compute the set of parameters for which the result is a subset
2905 * of "cond".
2907 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2908 __isl_take isl_set *dom, __isl_take isl_val *inc)
2910 isl_space *space;
2911 isl_aff *aff;
2912 isl_map *next;
2914 space = isl_set_get_space(dom);
2915 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2916 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2917 aff = isl_aff_add_constant_val(aff, inc);
2918 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2920 dom = isl_set_apply(dom, next);
2922 return enforce_subset(dom, cond);
2925 /* Construct a pet_scop for a for statement.
2926 * The for loop is required to be of the form
2928 * for (i = init; condition; ++i)
2930 * or
2932 * for (i = init; condition; --i)
2934 * The initialization of the for loop should either be an assignment
2935 * to an integer variable, or a declaration of such a variable with
2936 * initialization.
2938 * The condition is allowed to contain nested accesses, provided
2939 * they are not being written to inside the body of the loop.
2940 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2941 * essentially treated as a while loop, with iteration domain
2942 * { [i] : i >= init }.
2944 * We extract a pet_scop for the body and then embed it in a loop with
2945 * iteration domain and schedule
2947 * { [i] : i >= init and condition' }
2948 * { [i] -> [i] }
2950 * or
2952 * { [i] : i <= init and condition' }
2953 * { [i] -> [-i] }
2955 * Where condition' is equal to condition if the latter is
2956 * a simple upper [lower] bound and a condition that is extended
2957 * to apply to all previous iterations otherwise.
2959 * If the condition is non-affine, then we drop the condition from the
2960 * iteration domain and instead create a separate statement
2961 * for evaluating the condition. The body is then filtered to depend
2962 * on the result of the condition evaluating to true on all iterations
2963 * up to the current iteration, while the evaluation the condition itself
2964 * is filtered to depend on the result of the condition evaluating to true
2965 * on all previous iterations.
2966 * The context of the scop representing the body is dropped
2967 * because we don't know how many times the body will be executed,
2968 * if at all.
2970 * If the stride of the loop is not 1, then "i >= init" is replaced by
2972 * (exists a: i = init + stride * a and a >= 0)
2974 * If the loop iterator i is unsigned, then wrapping may occur.
2975 * We therefore use a virtual iterator instead that does not wrap.
2976 * However, the condition in the code applies
2977 * to the wrapped value, so we need to change condition(i)
2978 * into condition([i % 2^width]). Similarly, we replace all accesses
2979 * to the original iterator by the wrapping of the virtual iterator.
2980 * Note that there may be no need to perform this final wrapping
2981 * if the loop condition (after wrapping) satisfies certain conditions.
2982 * However, the is_simple_bound condition is not enough since it doesn't
2983 * check if there even is an upper bound.
2985 * Wrapping on unsigned iterators can be avoided entirely if
2986 * loop condition is simple, the loop iterator is incremented
2987 * [decremented] by one and the last value before wrapping cannot
2988 * possibly satisfy the loop condition.
2990 * Before extracting a pet_scop from the body we remove all
2991 * assignments in assigned_value to variables that are assigned
2992 * somewhere in the body of the loop.
2994 * Valid parameters for a for loop are those for which the initial
2995 * value itself, the increment on each domain iteration and
2996 * the condition on both the initial value and
2997 * the result of incrementing the iterator for each iteration of the domain
2998 * can be evaluated.
2999 * If the loop condition is non-affine, then we only consider validity
3000 * of the initial value.
3002 * If the body contains any break, then we keep track of it in "skip"
3003 * (if the skip condition is affine) or it is handled in scop_add_break
3004 * (if the skip condition is not affine).
3005 * Note that the affine break condition needs to be considered with
3006 * respect to previous iterations in the virtual domain (if any).
3008 * If we were only able to extract part of the body, then simply
3009 * return that part.
3011 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
3013 BinaryOperator *ass;
3014 Decl *decl;
3015 Stmt *init;
3016 Expr *lhs, *rhs;
3017 ValueDecl *iv;
3018 isl_local_space *ls;
3019 isl_set *domain;
3020 isl_aff *sched;
3021 isl_set *cond = NULL;
3022 isl_set *skip = NULL;
3023 isl_id *id, *id_test = NULL, *id_break_test;
3024 struct pet_scop *scop, *scop_cond = NULL;
3025 assigned_value_cache cache(assigned_value);
3026 isl_val *inc;
3027 bool was_assigned;
3028 bool is_one;
3029 bool is_unsigned;
3030 bool is_simple;
3031 bool is_virtual;
3032 bool has_affine_break;
3033 bool has_var_break;
3034 isl_aff *wrap = NULL;
3035 isl_pw_aff *pa, *pa_inc, *init_val;
3036 isl_set *valid_init;
3037 isl_set *valid_cond;
3038 isl_set *valid_cond_init;
3039 isl_set *valid_cond_next;
3040 isl_set *valid_inc;
3041 int stmt_id;
3043 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
3044 return extract_infinite_for(stmt);
3046 init = stmt->getInit();
3047 if (!init) {
3048 unsupported(stmt);
3049 return NULL;
3051 if ((ass = initialization_assignment(init)) != NULL) {
3052 iv = extract_induction_variable(ass);
3053 if (!iv)
3054 return NULL;
3055 lhs = ass->getLHS();
3056 rhs = ass->getRHS();
3057 } else if ((decl = initialization_declaration(init)) != NULL) {
3058 VarDecl *var = extract_induction_variable(init, decl);
3059 if (!var)
3060 return NULL;
3061 iv = var;
3062 rhs = var->getInit();
3063 lhs = create_DeclRefExpr(var);
3064 } else {
3065 unsupported(stmt->getInit());
3066 return NULL;
3069 assigned_value.erase(iv);
3070 clear_assignments clear(assigned_value);
3071 clear.TraverseStmt(stmt->getBody());
3073 was_assigned = assigned_value.find(iv) != assigned_value.end();
3074 clear_assignment(assigned_value, iv);
3075 init_val = extract_affine(rhs);
3076 if (!was_assigned)
3077 assigned_value.erase(iv);
3078 if (!init_val)
3079 return NULL;
3081 pa_inc = extract_increment(stmt, iv);
3082 if (!pa_inc) {
3083 isl_pw_aff_free(init_val);
3084 return NULL;
3087 inc = NULL;
3088 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
3089 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
3090 isl_pw_aff_free(init_val);
3091 isl_pw_aff_free(pa_inc);
3092 unsupported(stmt->getInc());
3093 isl_val_free(inc);
3094 return NULL;
3097 pa = try_extract_nested_condition(stmt->getCond());
3098 if (allow_nested && (!pa || pet_nested_any_in_pw_aff(pa)))
3099 stmt_id = n_stmt++;
3101 scop = extract(stmt->getBody());
3102 if (partial) {
3103 isl_pw_aff_free(init_val);
3104 isl_pw_aff_free(pa_inc);
3105 isl_pw_aff_free(pa);
3106 isl_val_free(inc);
3107 return scop;
3110 valid_inc = isl_pw_aff_domain(pa_inc);
3112 is_unsigned = iv->getType()->isUnsignedIntegerType();
3114 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
3116 has_affine_break = scop &&
3117 pet_scop_has_affine_skip(scop, pet_skip_later);
3118 if (has_affine_break)
3119 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
3120 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
3121 if (has_var_break)
3122 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
3124 if (pa && !is_nested_allowed(pa, scop)) {
3125 isl_pw_aff_free(pa);
3126 pa = NULL;
3129 if (!allow_nested && !pa)
3130 pa = try_extract_affine_condition(stmt->getCond());
3131 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3132 cond = isl_pw_aff_non_zero_set(pa);
3133 if (allow_nested && !cond) {
3134 isl_multi_pw_aff *test_index;
3135 int save_n_stmt = n_stmt;
3136 test_index = create_test_index(ctx, n_test++);
3137 n_stmt = stmt_id;
3138 scop_cond = extract_non_affine_condition(stmt->getCond(),
3139 n_stmt++, isl_multi_pw_aff_copy(test_index));
3140 n_stmt = save_n_stmt;
3141 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
3142 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
3143 isl_dim_out);
3144 isl_multi_pw_aff_free(test_index);
3145 scop_cond = pet_scop_prefix(scop_cond, 0);
3146 scop = pet_scop_reset_context(scop);
3147 scop = pet_scop_prefix(scop, 1);
3148 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
3151 cond = embed(cond, isl_id_copy(id));
3152 skip = embed(skip, isl_id_copy(id));
3153 valid_cond = isl_set_coalesce(valid_cond);
3154 valid_cond = embed(valid_cond, isl_id_copy(id));
3155 valid_inc = embed(valid_inc, isl_id_copy(id));
3156 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
3157 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
3159 valid_cond_init = enforce_subset(
3160 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
3161 isl_set_copy(valid_cond));
3162 if (is_one && !is_virtual) {
3163 isl_pw_aff_free(init_val);
3164 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
3165 lhs, rhs, init);
3166 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3167 valid_init = set_project_out_by_id(valid_init, id);
3168 domain = isl_pw_aff_non_zero_set(pa);
3169 } else {
3170 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
3171 domain = strided_domain(isl_id_copy(id), init_val,
3172 isl_val_copy(inc));
3175 domain = embed(domain, isl_id_copy(id));
3176 if (is_virtual) {
3177 isl_map *rev_wrap;
3178 wrap = compute_wrapping(isl_set_get_space(cond), iv);
3179 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
3180 rev_wrap = isl_map_reverse(rev_wrap);
3181 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
3182 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
3183 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
3184 valid_inc = isl_set_apply(valid_inc, rev_wrap);
3186 is_simple = is_simple_bound(cond, inc);
3187 if (!is_simple) {
3188 cond = isl_set_gist(cond, isl_set_copy(domain));
3189 is_simple = is_simple_bound(cond, inc);
3191 if (!is_simple)
3192 cond = valid_for_each_iteration(cond,
3193 isl_set_copy(domain), isl_val_copy(inc));
3194 domain = isl_set_intersect(domain, cond);
3195 if (has_affine_break) {
3196 skip = isl_set_intersect(skip , isl_set_copy(domain));
3197 skip = after(skip, isl_val_sgn(inc));
3198 domain = isl_set_subtract(domain, skip);
3200 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
3201 ls = isl_local_space_from_space(isl_set_get_space(domain));
3202 sched = isl_aff_var_on_domain(ls, isl_dim_set, 0);
3203 if (isl_val_is_neg(inc))
3204 sched = isl_aff_neg(sched);
3206 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
3207 isl_val_copy(inc));
3208 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
3210 if (!is_virtual)
3211 wrap = identity_aff(domain);
3213 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
3214 isl_aff_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
3215 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
3216 scop = resolve_nested(scop);
3217 if (has_var_break)
3218 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
3219 isl_val_copy(inc));
3220 if (id_test) {
3221 scop = scop_add_while(scop_cond, scop, id_test, domain,
3222 isl_val_copy(inc));
3223 isl_set_free(valid_inc);
3224 } else {
3225 scop = pet_scop_restrict_context(scop, valid_inc);
3226 scop = pet_scop_restrict_context(scop, valid_cond_next);
3227 scop = pet_scop_restrict_context(scop, valid_cond_init);
3228 isl_set_free(domain);
3230 clear_assignment(assigned_value, iv);
3232 isl_val_free(inc);
3234 scop = pet_scop_restrict_context(scop, valid_init);
3236 return scop;
3239 /* Try and construct a pet_scop corresponding to a compound statement.
3241 * "skip_declarations" is set if we should skip initial declarations
3242 * in the children of the compound statements. This then implies
3243 * that this sequence of children should not be treated as a block
3244 * since the initial statements may be skipped.
3246 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
3248 return extract(stmt->children(), !skip_declarations, skip_declarations);
3251 /* For each nested access parameter in "space",
3252 * construct a corresponding pet_expr, place it in args and
3253 * record its position in "param2pos".
3254 * "n_arg" is the number of elements that are already in args.
3255 * The position recorded in "param2pos" takes this number into account.
3256 * If the pet_expr corresponding to a parameter is identical to
3257 * the pet_expr corresponding to an earlier parameter, then these two
3258 * parameters are made to refer to the same element in args.
3260 * Return the final number of elements in args or -1 if an error has occurred.
3262 int PetScan::extract_nested(__isl_keep isl_space *space,
3263 int n_arg, pet_expr **args, std::map<int,int> &param2pos)
3265 int nparam;
3267 nparam = isl_space_dim(space, isl_dim_param);
3268 for (int i = 0; i < nparam; ++i) {
3269 int j;
3270 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3271 Expr *nested;
3273 if (!pet_nested_in_id(id)) {
3274 isl_id_free(id);
3275 continue;
3278 nested = (Expr *) isl_id_get_user(id);
3279 args[n_arg] = extract_expr(nested);
3280 isl_id_free(id);
3281 if (!args[n_arg])
3282 return -1;
3284 for (j = 0; j < n_arg; ++j)
3285 if (pet_expr_is_equal(args[j], args[n_arg]))
3286 break;
3288 if (j < n_arg) {
3289 pet_expr_free(args[n_arg]);
3290 args[n_arg] = NULL;
3291 param2pos[i] = j;
3292 } else
3293 param2pos[i] = n_arg++;
3296 return n_arg;
3299 /* For each nested access parameter in the access relations in "expr",
3300 * construct a corresponding pet_expr, place it in the arguments of "expr"
3301 * and record its position in "param2pos".
3302 * n is the number of nested access parameters.
3304 __isl_give pet_expr *PetScan::extract_nested(__isl_take pet_expr *expr, int n,
3305 std::map<int,int> &param2pos)
3307 isl_space *space;
3308 int i;
3309 pet_expr **args;
3311 args = isl_calloc_array(ctx, pet_expr *, n);
3312 if (!args)
3313 return pet_expr_free(expr);
3315 space = pet_expr_access_get_parameter_space(expr);
3316 n = extract_nested(space, 0, args, param2pos);
3317 isl_space_free(space);
3319 if (n < 0)
3320 expr = pet_expr_free(expr);
3321 else
3322 expr = pet_expr_set_n_arg(expr, n);
3324 for (i = 0; i < n; ++i)
3325 expr = pet_expr_set_arg(expr, i, args[i]);
3326 free(args);
3328 return expr;
3331 /* Look for parameters in any access relation in "expr" that
3332 * refer to nested accesses. In particular, these are
3333 * parameters with no name.
3335 * If there are any such parameters, then the domain of the index
3336 * expression and the access relation, which is still [] at this point,
3337 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
3338 * (after identifying identical nested accesses).
3340 * This transformation is performed in several steps.
3341 * We first extract the arguments in extract_nested.
3342 * param2pos maps the original parameter position to the position
3343 * of the argument.
3344 * Then we move these parameters to input dimensions.
3345 * t2pos maps the positions of these temporary input dimensions
3346 * to the positions of the corresponding arguments.
3347 * Finally, we express these temporary dimensions in terms of the domain
3348 * [[] -> [t_1,...,t_n]] and precompose index expression and access
3349 * relations with this function.
3351 __isl_give pet_expr *PetScan::resolve_nested(__isl_take pet_expr *expr)
3353 int n;
3354 int nparam;
3355 isl_space *space;
3356 isl_local_space *ls;
3357 isl_aff *aff;
3358 isl_multi_aff *ma;
3359 std::map<int,int> param2pos;
3360 std::map<int,int> t2pos;
3362 if (!expr)
3363 return expr;
3365 n = pet_expr_get_n_arg(expr);
3366 for (int i = 0; i < n; ++i) {
3367 pet_expr *arg;
3368 arg = pet_expr_get_arg(expr, i);
3369 arg = resolve_nested(arg);
3370 expr = pet_expr_set_arg(expr, i, arg);
3373 if (pet_expr_get_type(expr) != pet_expr_access)
3374 return expr;
3376 space = pet_expr_access_get_parameter_space(expr);
3377 n = pet_nested_n_in_space(space);
3378 isl_space_free(space);
3379 if (n == 0)
3380 return expr;
3382 expr = extract_nested(expr, n, param2pos);
3383 if (!expr)
3384 return NULL;
3386 expr = pet_expr_access_align_params(expr);
3387 if (!expr)
3388 return NULL;
3390 n = 0;
3391 space = pet_expr_access_get_parameter_space(expr);
3392 nparam = isl_space_dim(space, isl_dim_param);
3393 for (int i = nparam - 1; i >= 0; --i) {
3394 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3395 if (!pet_nested_in_id(id)) {
3396 isl_id_free(id);
3397 continue;
3400 expr = pet_expr_access_move_dims(expr,
3401 isl_dim_in, n, isl_dim_param, i, 1);
3402 t2pos[n] = param2pos[i];
3403 n++;
3405 isl_id_free(id);
3407 isl_space_free(space);
3409 space = pet_expr_access_get_parameter_space(expr);
3410 space = isl_space_set_from_params(space);
3411 space = isl_space_add_dims(space, isl_dim_set,
3412 pet_expr_get_n_arg(expr));
3413 space = isl_space_wrap(isl_space_from_range(space));
3414 ls = isl_local_space_from_space(isl_space_copy(space));
3415 space = isl_space_from_domain(space);
3416 space = isl_space_add_dims(space, isl_dim_out, n);
3417 ma = isl_multi_aff_zero(space);
3419 for (int i = 0; i < n; ++i) {
3420 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3421 isl_dim_set, t2pos[i]);
3422 ma = isl_multi_aff_set_aff(ma, i, aff);
3424 isl_local_space_free(ls);
3426 expr = pet_expr_access_pullback_multi_aff(expr, ma);
3428 return expr;
3431 /* Return the file offset of the expansion location of "Loc".
3433 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3435 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3438 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3440 /* Return a SourceLocation for the location after the first semicolon
3441 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3442 * call it and also skip trailing spaces and newline.
3444 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3445 const LangOptions &LO)
3447 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3450 #else
3452 /* Return a SourceLocation for the location after the first semicolon
3453 * after "loc". If Lexer::findLocationAfterToken is not available,
3454 * we look in the underlying character data for the first semicolon.
3456 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3457 const LangOptions &LO)
3459 const char *semi;
3460 const char *s = SM.getCharacterData(loc);
3462 semi = strchr(s, ';');
3463 if (!semi)
3464 return SourceLocation();
3465 return loc.getFileLocWithOffset(semi + 1 - s);
3468 #endif
3470 /* If the token at "loc" is the first token on the line, then return
3471 * a location referring to the start of the line.
3472 * Otherwise, return "loc".
3474 * This function is used to extend a scop to the start of the line
3475 * if the first token of the scop is also the first token on the line.
3477 * We look for the first token on the line. If its location is equal to "loc",
3478 * then the latter is the location of the first token on the line.
3480 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3481 SourceManager &SM, const LangOptions &LO)
3483 std::pair<FileID, unsigned> file_offset_pair;
3484 llvm::StringRef file;
3485 const char *pos;
3486 Token tok;
3487 SourceLocation token_loc, line_loc;
3488 int col;
3490 loc = SM.getExpansionLoc(loc);
3491 col = SM.getExpansionColumnNumber(loc);
3492 line_loc = loc.getLocWithOffset(1 - col);
3493 file_offset_pair = SM.getDecomposedLoc(line_loc);
3494 file = SM.getBufferData(file_offset_pair.first, NULL);
3495 pos = file.data() + file_offset_pair.second;
3497 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3498 file.begin(), pos, file.end());
3499 lexer.LexFromRawLexer(tok);
3500 token_loc = tok.getLocation();
3502 if (token_loc == loc)
3503 return line_loc;
3504 else
3505 return loc;
3508 /* Update start and end of "scop" to include the region covered by "range".
3509 * If "skip_semi" is set, then we assume "range" is followed by
3510 * a semicolon and also include this semicolon.
3512 struct pet_scop *PetScan::update_scop_start_end(struct pet_scop *scop,
3513 SourceRange range, bool skip_semi)
3515 SourceLocation loc = range.getBegin();
3516 SourceManager &SM = PP.getSourceManager();
3517 const LangOptions &LO = PP.getLangOpts();
3518 unsigned start, end;
3520 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3521 start = getExpansionOffset(SM, loc);
3522 loc = range.getEnd();
3523 if (skip_semi)
3524 loc = location_after_semi(loc, SM, LO);
3525 else
3526 loc = PP.getLocForEndOfToken(loc);
3527 end = getExpansionOffset(SM, loc);
3529 scop = pet_scop_update_start_end(scop, start, end);
3530 return scop;
3533 /* Convert a top-level pet_expr to a pet_scop with one statement.
3534 * This mainly involves resolving nested expression parameters
3535 * and setting the name of the iteration space.
3536 * The name is given by "label" if it is non-NULL. Otherwise,
3537 * it is of the form S_<n_stmt>.
3538 * start and end of the pet_scop are derived from those of "stmt".
3539 * If "stmt" is an expression statement, then its range does not
3540 * include the semicolon, while it should be included in the pet_scop.
3542 struct pet_scop *PetScan::extract(Stmt *stmt, __isl_take pet_expr *expr,
3543 __isl_take isl_id *label)
3545 struct pet_stmt *ps;
3546 struct pet_scop *scop;
3547 SourceLocation loc = stmt->getLocStart();
3548 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3549 bool skip_semi;
3551 expr = resolve_nested(expr);
3552 ps = pet_stmt_from_pet_expr(line, label, n_stmt++, expr);
3553 scop = pet_scop_from_pet_stmt(ctx, ps);
3555 skip_semi = isa<Expr>(stmt);
3556 scop = update_scop_start_end(scop, stmt->getSourceRange(), skip_semi);
3557 return scop;
3560 /* Check if we can extract an affine expression from "expr".
3561 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3562 * We turn on autodetection so that we won't generate any warnings
3563 * and turn off nesting, so that we won't accept any non-affine constructs.
3565 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3567 isl_pw_aff *pwaff;
3568 int save_autodetect = options->autodetect;
3569 bool save_nesting = nesting_enabled;
3571 options->autodetect = 1;
3572 nesting_enabled = false;
3574 pwaff = extract_affine(expr);
3576 options->autodetect = save_autodetect;
3577 nesting_enabled = save_nesting;
3579 return pwaff;
3582 /* Check if we can extract an affine constraint from "expr".
3583 * Return the constraint as an isl_set if we can and NULL otherwise.
3584 * We turn on autodetection so that we won't generate any warnings
3585 * and turn off nesting, so that we won't accept any non-affine constructs.
3587 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3589 isl_pw_aff *cond;
3590 int save_autodetect = options->autodetect;
3591 bool save_nesting = nesting_enabled;
3593 options->autodetect = 1;
3594 nesting_enabled = false;
3596 cond = extract_condition(expr);
3598 options->autodetect = save_autodetect;
3599 nesting_enabled = save_nesting;
3601 return cond;
3604 /* Check whether "expr" is an affine constraint.
3606 bool PetScan::is_affine_condition(Expr *expr)
3608 isl_pw_aff *cond;
3610 cond = try_extract_affine_condition(expr);
3611 isl_pw_aff_free(cond);
3613 return cond != NULL;
3616 /* Check if we can extract a condition from "expr".
3617 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3618 * If allow_nested is set, then the condition may involve parameters
3619 * corresponding to nested accesses.
3620 * We turn on autodetection so that we won't generate any warnings.
3622 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3624 isl_pw_aff *cond;
3625 int save_autodetect = options->autodetect;
3626 bool save_nesting = nesting_enabled;
3628 options->autodetect = 1;
3629 nesting_enabled = allow_nested;
3630 cond = extract_condition(expr);
3632 options->autodetect = save_autodetect;
3633 nesting_enabled = save_nesting;
3635 return cond;
3638 /* If the top-level expression of "stmt" is an assignment, then
3639 * return that assignment as a BinaryOperator.
3640 * Otherwise return NULL.
3642 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3644 BinaryOperator *ass;
3646 if (!stmt)
3647 return NULL;
3648 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3649 return NULL;
3651 ass = cast<BinaryOperator>(stmt);
3652 if(ass->getOpcode() != BO_Assign)
3653 return NULL;
3655 return ass;
3658 /* Check if the given if statement is a conditional assignement
3659 * with a non-affine condition. If so, construct a pet_scop
3660 * corresponding to this conditional assignment. Otherwise return NULL.
3662 * In particular we check if "stmt" is of the form
3664 * if (condition)
3665 * a = f(...);
3666 * else
3667 * a = g(...);
3669 * where a is some array or scalar access.
3670 * The constructed pet_scop then corresponds to the expression
3672 * a = condition ? f(...) : g(...)
3674 * All access relations in f(...) are intersected with condition
3675 * while all access relation in g(...) are intersected with the complement.
3677 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3679 BinaryOperator *ass_then, *ass_else;
3680 isl_multi_pw_aff *write_then, *write_else;
3681 isl_set *cond, *comp;
3682 isl_multi_pw_aff *index;
3683 isl_pw_aff *pa;
3684 int equal;
3685 int type_size;
3686 pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3687 bool save_nesting = nesting_enabled;
3689 if (!options->detect_conditional_assignment)
3690 return NULL;
3692 ass_then = top_assignment_or_null(stmt->getThen());
3693 ass_else = top_assignment_or_null(stmt->getElse());
3695 if (!ass_then || !ass_else)
3696 return NULL;
3698 if (is_affine_condition(stmt->getCond()))
3699 return NULL;
3701 write_then = extract_index(ass_then->getLHS());
3702 write_else = extract_index(ass_else->getLHS());
3704 equal = isl_multi_pw_aff_plain_is_equal(write_then, write_else);
3705 isl_multi_pw_aff_free(write_else);
3706 if (equal < 0 || !equal) {
3707 isl_multi_pw_aff_free(write_then);
3708 return NULL;
3711 nesting_enabled = allow_nested;
3712 pa = extract_condition(stmt->getCond());
3713 nesting_enabled = save_nesting;
3714 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3715 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3716 index = isl_multi_pw_aff_from_range(isl_multi_pw_aff_from_pw_aff(pa));
3718 pe_cond = pet_expr_from_index(index);
3720 pe_then = extract_expr(ass_then->getRHS());
3721 pe_then = pet_expr_restrict(pe_then, cond);
3722 pe_else = extract_expr(ass_else->getRHS());
3723 pe_else = pet_expr_restrict(pe_else, comp);
3725 pe = pet_expr_new_ternary(pe_cond, pe_then, pe_else);
3726 type_size = get_type_size(ass_then->getType(), ast_context);
3727 pe_write = pet_expr_from_index_and_depth(type_size, write_then,
3728 extract_depth(write_then));
3729 pe_write = pet_expr_access_set_write(pe_write, 1);
3730 pe_write = pet_expr_access_set_read(pe_write, 0);
3731 pe = pet_expr_new_binary(type_size, pet_op_assign, pe_write, pe);
3732 return extract(stmt, pe);
3735 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3736 * evaluating "cond" and writing the result to a virtual scalar,
3737 * as expressed by "index".
3739 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond, int stmt_nr,
3740 __isl_take isl_multi_pw_aff *index)
3742 pet_expr *expr, *write;
3743 struct pet_stmt *ps;
3744 SourceLocation loc = cond->getLocStart();
3745 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3747 write = pet_expr_from_index(index);
3748 write = pet_expr_access_set_write(write, 1);
3749 write = pet_expr_access_set_read(write, 0);
3750 expr = extract_expr(cond);
3751 expr = resolve_nested(expr);
3752 expr = pet_expr_new_binary(1, pet_op_assign, write, expr);
3753 ps = pet_stmt_from_pet_expr(line, NULL, stmt_nr, expr);
3754 return pet_scop_from_pet_stmt(ctx, ps);
3757 extern "C" {
3758 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr,
3759 void *user);
3762 /* Precompose the access relation and the index expression associated
3763 * to "expr" with the function pointed to by "user",
3764 * thereby embedding the access relation in the domain of this function.
3765 * The initial domain of the access relation and the index expression
3766 * is the zero-dimensional domain.
3768 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr, void *user)
3770 isl_multi_aff *ma = (isl_multi_aff *) user;
3772 return pet_expr_access_pullback_multi_aff(expr, isl_multi_aff_copy(ma));
3775 /* Precompose all access relations in "expr" with "ma", thereby
3776 * embedding them in the domain of "ma".
3778 static __isl_give pet_expr *embed(__isl_take pet_expr *expr,
3779 __isl_keep isl_multi_aff *ma)
3781 return pet_expr_map_access(expr, &embed_access, ma);
3784 /* For each nested access parameter in the domain of "stmt",
3785 * construct a corresponding pet_expr, place it before the original
3786 * elements in stmt->args and record its position in "param2pos".
3787 * n is the number of nested access parameters.
3789 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3790 std::map<int,int> &param2pos)
3792 int i;
3793 isl_space *space;
3794 int n_arg;
3795 pet_expr **args;
3797 n_arg = stmt->n_arg;
3798 args = isl_calloc_array(ctx, pet_expr *, n + n_arg);
3799 if (!args)
3800 goto error;
3802 space = isl_set_get_space(stmt->domain);
3803 n_arg = extract_nested(space, 0, args, param2pos);
3804 isl_space_free(space);
3806 if (n_arg < 0)
3807 goto error;
3809 for (i = 0; i < stmt->n_arg; ++i)
3810 args[n_arg + i] = stmt->args[i];
3811 free(stmt->args);
3812 stmt->args = args;
3813 stmt->n_arg += n_arg;
3815 return stmt;
3816 error:
3817 if (args) {
3818 for (i = 0; i < n; ++i)
3819 pet_expr_free(args[i]);
3820 free(args);
3822 pet_stmt_free(stmt);
3823 return NULL;
3826 /* Check whether any of the arguments i of "stmt" starting at position "n"
3827 * is equal to one of the first "n" arguments j.
3828 * If so, combine the constraints on arguments i and j and remove
3829 * argument i.
3831 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3833 int i, j;
3834 isl_map *map;
3836 if (!stmt)
3837 return NULL;
3838 if (n == 0)
3839 return stmt;
3840 if (n == stmt->n_arg)
3841 return stmt;
3843 map = isl_set_unwrap(stmt->domain);
3845 for (i = stmt->n_arg - 1; i >= n; --i) {
3846 for (j = 0; j < n; ++j)
3847 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3848 break;
3849 if (j >= n)
3850 continue;
3852 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3853 map = isl_map_project_out(map, isl_dim_out, i, 1);
3855 pet_expr_free(stmt->args[i]);
3856 for (j = i; j + 1 < stmt->n_arg; ++j)
3857 stmt->args[j] = stmt->args[j + 1];
3858 stmt->n_arg--;
3861 stmt->domain = isl_map_wrap(map);
3862 if (!stmt->domain)
3863 goto error;
3864 return stmt;
3865 error:
3866 pet_stmt_free(stmt);
3867 return NULL;
3870 /* Look for parameters in the iteration domain of "stmt" that
3871 * refer to nested accesses. In particular, these are
3872 * parameters with no name.
3874 * If there are any such parameters, then as many extra variables
3875 * (after identifying identical nested accesses) are inserted in the
3876 * range of the map wrapped inside the domain, before the original variables.
3877 * If the original domain is not a wrapped map, then a new wrapped
3878 * map is created with zero output dimensions.
3879 * The parameters are then equated to the corresponding output dimensions
3880 * and subsequently projected out, from the iteration domain,
3881 * the schedule and the access relations.
3882 * For each of the output dimensions, a corresponding argument
3883 * expression is inserted. Initially they are created with
3884 * a zero-dimensional domain, so they have to be embedded
3885 * in the current iteration domain.
3886 * param2pos maps the position of the parameter to the position
3887 * of the corresponding output dimension in the wrapped map.
3889 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3891 int n;
3892 int nparam;
3893 unsigned n_arg;
3894 isl_map *map;
3895 isl_space *space;
3896 isl_multi_aff *ma;
3897 std::map<int,int> param2pos;
3899 if (!stmt)
3900 return NULL;
3902 n = pet_nested_n_in_set(stmt->domain);
3903 if (n == 0)
3904 return stmt;
3906 n_arg = stmt->n_arg;
3907 stmt = extract_nested(stmt, n, param2pos);
3908 if (!stmt)
3909 return NULL;
3911 n = stmt->n_arg - n_arg;
3912 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3913 if (isl_set_is_wrapping(stmt->domain))
3914 map = isl_set_unwrap(stmt->domain);
3915 else
3916 map = isl_map_from_domain(stmt->domain);
3917 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3919 for (int i = nparam - 1; i >= 0; --i) {
3920 isl_id *id;
3922 if (!pet_nested_in_map(map, i))
3923 continue;
3925 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
3926 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3927 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3928 param2pos[i]);
3929 map = isl_map_project_out(map, isl_dim_param, i, 1);
3932 stmt->domain = isl_map_wrap(map);
3934 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
3935 space = isl_space_from_domain(isl_space_domain(space));
3936 ma = isl_multi_aff_zero(space);
3937 for (int pos = 0; pos < n; ++pos)
3938 stmt->args[pos] = embed(stmt->args[pos], ma);
3939 isl_multi_aff_free(ma);
3941 stmt = pet_stmt_remove_nested_parameters(stmt);
3942 stmt = remove_duplicate_arguments(stmt, n);
3944 return stmt;
3947 /* For each statement in "scop", move the parameters that correspond
3948 * to nested access into the ranges of the domains and create
3949 * corresponding argument expressions.
3951 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3953 if (!scop)
3954 return NULL;
3956 for (int i = 0; i < scop->n_stmt; ++i) {
3957 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3958 if (!scop->stmts[i])
3959 goto error;
3962 return scop;
3963 error:
3964 pet_scop_free(scop);
3965 return NULL;
3968 /* Given an access expression "expr", is the variable accessed by
3969 * "expr" assigned anywhere inside "scop"?
3971 static bool is_assigned(__isl_keep pet_expr *expr, pet_scop *scop)
3973 bool assigned = false;
3974 isl_id *id;
3976 id = pet_expr_access_get_id(expr);
3977 assigned = pet_scop_writes(scop, id);
3978 isl_id_free(id);
3980 return assigned;
3983 /* Are all nested access parameters in "pa" allowed given "scop".
3984 * In particular, is none of them written by anywhere inside "scop".
3986 * If "scop" has any skip conditions, then no nested access parameters
3987 * are allowed. In particular, if there is any nested access in a guard
3988 * for a piece of code containing a "continue", then we want to introduce
3989 * a separate statement for evaluating this guard so that we can express
3990 * that the result is false for all previous iterations.
3992 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3994 int nparam;
3996 if (!scop)
3997 return true;
3999 if (!pet_nested_any_in_pw_aff(pa))
4000 return true;
4002 if (pet_scop_has_skip(scop, pet_skip_now))
4003 return false;
4005 nparam = isl_pw_aff_dim(pa, isl_dim_param);
4006 for (int i = 0; i < nparam; ++i) {
4007 Expr *nested;
4008 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
4009 pet_expr *expr;
4010 bool allowed;
4012 if (!pet_nested_in_id(id)) {
4013 isl_id_free(id);
4014 continue;
4017 nested = (Expr *) isl_id_get_user(id);
4018 expr = extract_expr(nested);
4019 allowed = pet_expr_get_type(expr) == pet_expr_access &&
4020 !is_assigned(expr, scop);
4022 pet_expr_free(expr);
4023 isl_id_free(id);
4025 if (!allowed)
4026 return false;
4029 return true;
4032 /* Do we need to construct a skip condition of the given type
4033 * on an if statement, given that the if condition is non-affine?
4035 * pet_scop_filter_skip can only handle the case where the if condition
4036 * holds (the then branch) and the skip condition is universal.
4037 * In any other case, we need to construct a new skip condition.
4039 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
4040 bool have_else, enum pet_skip type)
4042 if (have_else && scop_else && pet_scop_has_skip(scop_else, type))
4043 return true;
4044 if (scop_then && pet_scop_has_skip(scop_then, type) &&
4045 !pet_scop_has_universal_skip(scop_then, type))
4046 return true;
4047 return false;
4050 /* Do we need to construct a skip condition of the given type
4051 * on an if statement, given that the if condition is affine?
4053 * There is no need to construct a new skip condition if all
4054 * the skip conditions are affine.
4056 static bool need_skip_aff(struct pet_scop *scop_then,
4057 struct pet_scop *scop_else, bool have_else, enum pet_skip type)
4059 if (scop_then && pet_scop_has_var_skip(scop_then, type))
4060 return true;
4061 if (have_else && scop_else && pet_scop_has_var_skip(scop_else, type))
4062 return true;
4063 return false;
4066 /* Do we need to construct a skip condition of the given type
4067 * on an if statement?
4069 static bool need_skip(struct pet_scop *scop_then, struct pet_scop *scop_else,
4070 bool have_else, enum pet_skip type, bool affine)
4072 if (affine)
4073 return need_skip_aff(scop_then, scop_else, have_else, type);
4074 else
4075 return need_skip(scop_then, scop_else, have_else, type);
4078 /* Construct an affine expression pet_expr that evaluates
4079 * to the constant "val".
4081 static __isl_give pet_expr *universally(isl_ctx *ctx, int val)
4083 isl_local_space *ls;
4084 isl_aff *aff;
4085 isl_multi_pw_aff *mpa;
4087 ls = isl_local_space_from_space(isl_space_set_alloc(ctx, 0, 0));
4088 aff = isl_aff_val_on_domain(ls, isl_val_int_from_si(ctx, val));
4089 mpa = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4091 return pet_expr_from_index(mpa);
4094 /* Construct an affine expression pet_expr that evaluates
4095 * to the constant 1.
4097 static __isl_give pet_expr *universally_true(isl_ctx *ctx)
4099 return universally(ctx, 1);
4102 /* Construct an affine expression pet_expr that evaluates
4103 * to the constant 0.
4105 static __isl_give pet_expr *universally_false(isl_ctx *ctx)
4107 return universally(ctx, 0);
4110 /* Given an index expression "test_index" for the if condition,
4111 * an index expression "skip_index" for the skip condition and
4112 * scops for the then and else branches, construct a scop for
4113 * computing "skip_index".
4115 * The computed scop contains a single statement that essentially does
4117 * skip_index = test_cond ? skip_cond_then : skip_cond_else
4119 * If the skip conditions of the then and/or else branch are not affine,
4120 * then they need to be filtered by test_index.
4121 * If they are missing, then this means the skip condition is false.
4123 * Since we are constructing a skip condition for the if statement,
4124 * the skip conditions on the then and else branches are removed.
4126 static struct pet_scop *extract_skip(PetScan *scan,
4127 __isl_take isl_multi_pw_aff *test_index,
4128 __isl_take isl_multi_pw_aff *skip_index,
4129 struct pet_scop *scop_then, struct pet_scop *scop_else, bool have_else,
4130 enum pet_skip type)
4132 pet_expr *expr_then, *expr_else, *expr, *expr_skip;
4133 struct pet_stmt *stmt;
4134 struct pet_scop *scop;
4135 isl_ctx *ctx = scan->ctx;
4137 if (!scop_then)
4138 goto error;
4139 if (have_else && !scop_else)
4140 goto error;
4142 if (pet_scop_has_skip(scop_then, type)) {
4143 expr_then = pet_scop_get_skip_expr(scop_then, type);
4144 pet_scop_reset_skip(scop_then, type);
4145 if (!pet_expr_is_affine(expr_then))
4146 expr_then = pet_expr_filter(expr_then,
4147 isl_multi_pw_aff_copy(test_index), 1);
4148 } else
4149 expr_then = universally_false(ctx);
4151 if (have_else && pet_scop_has_skip(scop_else, type)) {
4152 expr_else = pet_scop_get_skip_expr(scop_else, type);
4153 pet_scop_reset_skip(scop_else, type);
4154 if (!pet_expr_is_affine(expr_else))
4155 expr_else = pet_expr_filter(expr_else,
4156 isl_multi_pw_aff_copy(test_index), 0);
4157 } else
4158 expr_else = universally_false(ctx);
4160 expr = pet_expr_from_index(test_index);
4161 expr = pet_expr_new_ternary(expr, expr_then, expr_else);
4162 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4163 expr_skip = pet_expr_access_set_write(expr_skip, 1);
4164 expr_skip = pet_expr_access_set_read(expr_skip, 0);
4165 expr = pet_expr_new_binary(1, pet_op_assign, expr_skip, expr);
4166 stmt = pet_stmt_from_pet_expr(-1, NULL, scan->n_stmt++, expr);
4168 scop = pet_scop_from_pet_stmt(ctx, stmt);
4169 scop = scop_add_array(scop, skip_index, scan->ast_context);
4170 isl_multi_pw_aff_free(skip_index);
4172 return scop;
4173 error:
4174 isl_multi_pw_aff_free(test_index);
4175 isl_multi_pw_aff_free(skip_index);
4176 return NULL;
4179 /* Is scop's skip_now condition equal to its skip_later condition?
4180 * In particular, this means that it either has no skip_now condition
4181 * or both a skip_now and a skip_later condition (that are equal to each other).
4183 static bool skip_equals_skip_later(struct pet_scop *scop)
4185 int has_skip_now, has_skip_later;
4186 int equal;
4187 isl_multi_pw_aff *skip_now, *skip_later;
4189 if (!scop)
4190 return false;
4191 has_skip_now = pet_scop_has_skip(scop, pet_skip_now);
4192 has_skip_later = pet_scop_has_skip(scop, pet_skip_later);
4193 if (has_skip_now != has_skip_later)
4194 return false;
4195 if (!has_skip_now)
4196 return true;
4198 skip_now = pet_scop_get_skip(scop, pet_skip_now);
4199 skip_later = pet_scop_get_skip(scop, pet_skip_later);
4200 equal = isl_multi_pw_aff_is_equal(skip_now, skip_later);
4201 isl_multi_pw_aff_free(skip_now);
4202 isl_multi_pw_aff_free(skip_later);
4204 return equal;
4207 /* Drop the skip conditions of type pet_skip_later from scop1 and scop2.
4209 static void drop_skip_later(struct pet_scop *scop1, struct pet_scop *scop2)
4211 pet_scop_reset_skip(scop1, pet_skip_later);
4212 pet_scop_reset_skip(scop2, pet_skip_later);
4215 /* Structure that handles the construction of skip conditions.
4217 * scop_then and scop_else represent the then and else branches
4218 * of the if statement
4220 * skip[type] is true if we need to construct a skip condition of that type
4221 * equal is set if the skip conditions of types pet_skip_now and pet_skip_later
4222 * are equal to each other
4223 * index[type] is an index expression from a zero-dimension domain
4224 * to the virtual array representing the skip condition
4225 * scop[type] is a scop for computing the skip condition
4227 struct pet_skip_info {
4228 isl_ctx *ctx;
4230 bool skip[2];
4231 bool equal;
4232 isl_multi_pw_aff *index[2];
4233 struct pet_scop *scop[2];
4235 pet_skip_info(isl_ctx *ctx) : ctx(ctx) {}
4237 operator bool() { return skip[pet_skip_now] || skip[pet_skip_later]; }
4240 /* Structure that handles the construction of skip conditions on if statements.
4242 * scop_then and scop_else represent the then and else branches
4243 * of the if statement
4245 struct pet_skip_info_if : public pet_skip_info {
4246 struct pet_scop *scop_then, *scop_else;
4247 bool have_else;
4249 pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4250 struct pet_scop *scop_else, bool have_else, bool affine);
4251 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index,
4252 enum pet_skip type);
4253 void extract(PetScan *scan, __isl_keep isl_multi_pw_aff *index);
4254 void extract(PetScan *scan, __isl_keep isl_pw_aff *cond);
4255 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4256 int offset);
4257 struct pet_scop *add(struct pet_scop *scop, int offset);
4260 /* Initialize a pet_skip_info_if structure based on the then and else branches
4261 * and based on whether the if condition is affine or not.
4263 pet_skip_info_if::pet_skip_info_if(isl_ctx *ctx, struct pet_scop *scop_then,
4264 struct pet_scop *scop_else, bool have_else, bool affine) :
4265 pet_skip_info(ctx), scop_then(scop_then), scop_else(scop_else),
4266 have_else(have_else)
4268 skip[pet_skip_now] =
4269 need_skip(scop_then, scop_else, have_else, pet_skip_now, affine);
4270 equal = skip[pet_skip_now] && skip_equals_skip_later(scop_then) &&
4271 (!have_else || skip_equals_skip_later(scop_else));
4272 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4273 need_skip(scop_then, scop_else, have_else, pet_skip_later, affine);
4276 /* If we need to construct a skip condition of the given type,
4277 * then do so now.
4279 * "mpa" represents the if condition.
4281 void pet_skip_info_if::extract(PetScan *scan,
4282 __isl_keep isl_multi_pw_aff *mpa, enum pet_skip type)
4284 isl_ctx *ctx;
4286 if (!skip[type])
4287 return;
4289 ctx = isl_multi_pw_aff_get_ctx(mpa);
4290 index[type] = create_test_index(ctx, scan->n_test++);
4291 scop[type] = extract_skip(scan, isl_multi_pw_aff_copy(mpa),
4292 isl_multi_pw_aff_copy(index[type]),
4293 scop_then, scop_else, have_else, type);
4296 /* Construct the required skip conditions, given the if condition "index".
4298 void pet_skip_info_if::extract(PetScan *scan,
4299 __isl_keep isl_multi_pw_aff *index)
4301 extract(scan, index, pet_skip_now);
4302 extract(scan, index, pet_skip_later);
4303 if (equal)
4304 drop_skip_later(scop_then, scop_else);
4307 /* Construct the required skip conditions, given the if condition "cond".
4309 void pet_skip_info_if::extract(PetScan *scan, __isl_keep isl_pw_aff *cond)
4311 isl_multi_pw_aff *test;
4313 if (!skip[pet_skip_now] && !skip[pet_skip_later])
4314 return;
4316 test = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_copy(cond));
4317 test = isl_multi_pw_aff_from_range(test);
4318 extract(scan, test);
4319 isl_multi_pw_aff_free(test);
4322 /* Add the computed skip condition of the give type to "main" and
4323 * add the scop for computing the condition at the given offset.
4325 * If equal is set, then we only computed a skip condition for pet_skip_now,
4326 * but we also need to set it as main's pet_skip_later.
4328 struct pet_scop *pet_skip_info_if::add(struct pet_scop *main,
4329 enum pet_skip type, int offset)
4331 if (!skip[type])
4332 return main;
4334 scop[type] = pet_scop_prefix(scop[type], offset);
4335 main = pet_scop_add_par(ctx, main, scop[type]);
4336 scop[type] = NULL;
4338 if (equal)
4339 main = pet_scop_set_skip(main, pet_skip_later,
4340 isl_multi_pw_aff_copy(index[type]));
4342 main = pet_scop_set_skip(main, type, index[type]);
4343 index[type] = NULL;
4345 return main;
4348 /* Add the computed skip conditions to "main" and
4349 * add the scops for computing the conditions at the given offset.
4351 struct pet_scop *pet_skip_info_if::add(struct pet_scop *scop, int offset)
4353 scop = add(scop, pet_skip_now, offset);
4354 scop = add(scop, pet_skip_later, offset);
4356 return scop;
4359 /* Construct a pet_scop for a non-affine if statement.
4361 * We create a separate statement that writes the result
4362 * of the non-affine condition to a virtual scalar.
4363 * A constraint requiring the value of this virtual scalar to be one
4364 * is added to the iteration domains of the then branch.
4365 * Similarly, a constraint requiring the value of this virtual scalar
4366 * to be zero is added to the iteration domains of the else branch, if any.
4367 * We adjust the schedules to ensure that the virtual scalar is written
4368 * before it is read.
4370 * If there are any breaks or continues in the then and/or else
4371 * branches, then we may have to compute a new skip condition.
4372 * This is handled using a pet_skip_info_if object.
4373 * On initialization, the object checks if skip conditions need
4374 * to be computed. If so, it does so in "extract" and adds them in "add".
4376 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
4377 struct pet_scop *scop_then, struct pet_scop *scop_else,
4378 bool have_else, int stmt_id)
4380 struct pet_scop *scop;
4381 isl_multi_pw_aff *test_index;
4382 int save_n_stmt = n_stmt;
4384 test_index = create_test_index(ctx, n_test++);
4385 n_stmt = stmt_id;
4386 scop = extract_non_affine_condition(cond, n_stmt++,
4387 isl_multi_pw_aff_copy(test_index));
4388 n_stmt = save_n_stmt;
4389 scop = scop_add_array(scop, test_index, ast_context);
4391 pet_skip_info_if skip(ctx, scop_then, scop_else, have_else, false);
4392 skip.extract(this, test_index);
4394 scop = pet_scop_prefix(scop, 0);
4395 scop_then = pet_scop_prefix(scop_then, 1);
4396 scop_then = pet_scop_filter(scop_then,
4397 isl_multi_pw_aff_copy(test_index), 1);
4398 if (have_else) {
4399 scop_else = pet_scop_prefix(scop_else, 1);
4400 scop_else = pet_scop_filter(scop_else, test_index, 0);
4401 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
4402 } else
4403 isl_multi_pw_aff_free(test_index);
4405 scop = pet_scop_add_seq(ctx, scop, scop_then);
4407 scop = skip.add(scop, 2);
4409 return scop;
4412 /* Construct a pet_scop for an if statement.
4414 * If the condition fits the pattern of a conditional assignment,
4415 * then it is handled by extract_conditional_assignment.
4416 * Otherwise, we do the following.
4418 * If the condition is affine, then the condition is added
4419 * to the iteration domains of the then branch, while the
4420 * opposite of the condition in added to the iteration domains
4421 * of the else branch, if any.
4422 * We allow the condition to be dynamic, i.e., to refer to
4423 * scalars or array elements that may be written to outside
4424 * of the given if statement. These nested accesses are then represented
4425 * as output dimensions in the wrapping iteration domain.
4426 * If it is also written _inside_ the then or else branch, then
4427 * we treat the condition as non-affine.
4428 * As explained in extract_non_affine_if, this will introduce
4429 * an extra statement.
4430 * For aesthetic reasons, we want this statement to have a statement
4431 * number that is lower than those of the then and else branches.
4432 * In order to evaluate if we will need such a statement, however, we
4433 * first construct scops for the then and else branches.
4434 * We therefore reserve a statement number if we might have to
4435 * introduce such an extra statement.
4437 * If the condition is not affine, then the scop is created in
4438 * extract_non_affine_if.
4440 * If there are any breaks or continues in the then and/or else
4441 * branches, then we may have to compute a new skip condition.
4442 * This is handled using a pet_skip_info_if object.
4443 * On initialization, the object checks if skip conditions need
4444 * to be computed. If so, it does so in "extract" and adds them in "add".
4446 struct pet_scop *PetScan::extract(IfStmt *stmt)
4448 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4449 isl_pw_aff *cond;
4450 int stmt_id;
4451 isl_set *set;
4452 isl_set *valid;
4454 clear_assignments clear(assigned_value);
4455 clear.TraverseStmt(stmt->getThen());
4456 if (stmt->getElse())
4457 clear.TraverseStmt(stmt->getElse());
4459 scop = extract_conditional_assignment(stmt);
4460 if (scop)
4461 return scop;
4463 cond = try_extract_nested_condition(stmt->getCond());
4464 if (allow_nested && (!cond || pet_nested_any_in_pw_aff(cond)))
4465 stmt_id = n_stmt++;
4468 assigned_value_cache cache(assigned_value);
4469 scop_then = extract(stmt->getThen());
4472 if (stmt->getElse()) {
4473 assigned_value_cache cache(assigned_value);
4474 scop_else = extract(stmt->getElse());
4475 if (options->autodetect) {
4476 if (scop_then && !scop_else) {
4477 partial = true;
4478 isl_pw_aff_free(cond);
4479 return scop_then;
4481 if (!scop_then && scop_else) {
4482 partial = true;
4483 isl_pw_aff_free(cond);
4484 return scop_else;
4489 if (cond &&
4490 (!is_nested_allowed(cond, scop_then) ||
4491 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4492 isl_pw_aff_free(cond);
4493 cond = NULL;
4495 if (allow_nested && !cond)
4496 return extract_non_affine_if(stmt->getCond(), scop_then,
4497 scop_else, stmt->getElse(), stmt_id);
4499 if (!cond)
4500 cond = extract_condition(stmt->getCond());
4502 pet_skip_info_if skip(ctx, scop_then, scop_else, stmt->getElse(), true);
4503 skip.extract(this, cond);
4505 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4506 set = isl_pw_aff_non_zero_set(cond);
4507 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4509 if (stmt->getElse()) {
4510 set = isl_set_subtract(isl_set_copy(valid), set);
4511 scop_else = pet_scop_restrict(scop_else, set);
4512 scop = pet_scop_add_par(ctx, scop, scop_else);
4513 } else
4514 isl_set_free(set);
4515 scop = resolve_nested(scop);
4516 scop = pet_scop_restrict_context(scop, valid);
4518 if (skip)
4519 scop = pet_scop_prefix(scop, 0);
4520 scop = skip.add(scop, 1);
4522 return scop;
4525 /* Try and construct a pet_scop for a label statement.
4526 * We currently only allow labels on expression statements.
4528 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4530 isl_id *label;
4531 Stmt *sub;
4533 sub = stmt->getSubStmt();
4534 if (!isa<Expr>(sub)) {
4535 unsupported(stmt);
4536 return NULL;
4539 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4541 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4544 /* Return a one-dimensional multi piecewise affine expression that is equal
4545 * to the constant 1 and is defined over a zero-dimensional domain.
4547 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
4549 isl_space *space;
4550 isl_local_space *ls;
4551 isl_aff *aff;
4553 space = isl_space_set_alloc(ctx, 0, 0);
4554 ls = isl_local_space_from_space(space);
4555 aff = isl_aff_zero_on_domain(ls);
4556 aff = isl_aff_set_constant_si(aff, 1);
4558 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4561 /* Construct a pet_scop for a continue statement.
4563 * We simply create an empty scop with a universal pet_skip_now
4564 * skip condition. This skip condition will then be taken into
4565 * account by the enclosing loop construct, possibly after
4566 * being incorporated into outer skip conditions.
4568 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4570 pet_scop *scop;
4572 scop = pet_scop_empty(ctx);
4573 if (!scop)
4574 return NULL;
4576 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
4578 return scop;
4581 /* Construct a pet_scop for a break statement.
4583 * We simply create an empty scop with both a universal pet_skip_now
4584 * skip condition and a universal pet_skip_later skip condition.
4585 * These skip conditions will then be taken into
4586 * account by the enclosing loop construct, possibly after
4587 * being incorporated into outer skip conditions.
4589 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4591 pet_scop *scop;
4592 isl_multi_pw_aff *skip;
4594 scop = pet_scop_empty(ctx);
4595 if (!scop)
4596 return NULL;
4598 skip = one_mpa(ctx);
4599 scop = pet_scop_set_skip(scop, pet_skip_now,
4600 isl_multi_pw_aff_copy(skip));
4601 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
4603 return scop;
4606 /* Try and construct a pet_scop corresponding to "stmt".
4608 * If "stmt" is a compound statement, then "skip_declarations"
4609 * indicates whether we should skip initial declarations in the
4610 * compound statement.
4612 * If the constructed pet_scop is not a (possibly) partial representation
4613 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4614 * In particular, if skip_declarations is set, then we may have skipped
4615 * declarations inside "stmt" and so the pet_scop may not represent
4616 * the entire "stmt".
4617 * Note that this function may be called with "stmt" referring to the entire
4618 * body of the function, including the outer braces. In such cases,
4619 * skip_declarations will be set and the braces will not be taken into
4620 * account in scop->start and scop->end.
4622 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
4624 struct pet_scop *scop;
4626 if (isa<Expr>(stmt))
4627 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4629 switch (stmt->getStmtClass()) {
4630 case Stmt::WhileStmtClass:
4631 scop = extract(cast<WhileStmt>(stmt));
4632 break;
4633 case Stmt::ForStmtClass:
4634 scop = extract_for(cast<ForStmt>(stmt));
4635 break;
4636 case Stmt::IfStmtClass:
4637 scop = extract(cast<IfStmt>(stmt));
4638 break;
4639 case Stmt::CompoundStmtClass:
4640 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
4641 break;
4642 case Stmt::LabelStmtClass:
4643 scop = extract(cast<LabelStmt>(stmt));
4644 break;
4645 case Stmt::ContinueStmtClass:
4646 scop = extract(cast<ContinueStmt>(stmt));
4647 break;
4648 case Stmt::BreakStmtClass:
4649 scop = extract(cast<BreakStmt>(stmt));
4650 break;
4651 case Stmt::DeclStmtClass:
4652 scop = extract(cast<DeclStmt>(stmt));
4653 break;
4654 default:
4655 unsupported(stmt);
4656 return NULL;
4659 if (partial || skip_declarations)
4660 return scop;
4662 scop = update_scop_start_end(scop, stmt->getSourceRange(), false);
4664 return scop;
4667 /* Do we need to construct a skip condition of the given type
4668 * on a sequence of statements?
4670 * There is no need to construct a new skip condition if only
4671 * only of the two statements has a skip condition or if both
4672 * of their skip conditions are affine.
4674 * In principle we also don't need a new continuation variable if
4675 * the continuation of scop2 is affine, but then we would need
4676 * to allow more complicated forms of continuations.
4678 static bool need_skip_seq(struct pet_scop *scop1, struct pet_scop *scop2,
4679 enum pet_skip type)
4681 if (!scop1 || !pet_scop_has_skip(scop1, type))
4682 return false;
4683 if (!scop2 || !pet_scop_has_skip(scop2, type))
4684 return false;
4685 if (pet_scop_has_affine_skip(scop1, type) &&
4686 pet_scop_has_affine_skip(scop2, type))
4687 return false;
4688 return true;
4691 /* Construct a scop for computing the skip condition of the given type and
4692 * with index expression "skip_index" for a sequence of two scops "scop1"
4693 * and "scop2".
4695 * The computed scop contains a single statement that essentially does
4697 * skip_index = skip_cond_1 ? 1 : skip_cond_2
4699 * or, in other words, skip_cond1 || skip_cond2.
4700 * In this expression, skip_cond_2 is filtered to reflect that it is
4701 * only evaluated when skip_cond_1 is false.
4703 * The skip condition on scop1 is not removed because it still needs
4704 * to be applied to scop2 when these two scops are combined.
4706 static struct pet_scop *extract_skip_seq(PetScan *ps,
4707 __isl_take isl_multi_pw_aff *skip_index,
4708 struct pet_scop *scop1, struct pet_scop *scop2, enum pet_skip type)
4710 pet_expr *expr1, *expr2, *expr, *expr_skip;
4711 struct pet_stmt *stmt;
4712 struct pet_scop *scop;
4713 isl_ctx *ctx = ps->ctx;
4715 if (!scop1 || !scop2)
4716 goto error;
4718 expr1 = pet_scop_get_skip_expr(scop1, type);
4719 expr2 = pet_scop_get_skip_expr(scop2, type);
4720 pet_scop_reset_skip(scop2, type);
4722 expr2 = pet_expr_filter(expr2, pet_expr_access_get_index(expr1), 0);
4724 expr = universally_true(ctx);
4725 expr = pet_expr_new_ternary(expr1, expr, expr2);
4726 expr_skip = pet_expr_from_index(isl_multi_pw_aff_copy(skip_index));
4727 expr_skip = pet_expr_access_set_write(expr_skip, 1);
4728 expr_skip = pet_expr_access_set_read(expr_skip, 0);
4729 expr = pet_expr_new_binary(1, pet_op_assign, expr_skip, expr);
4730 stmt = pet_stmt_from_pet_expr(-1, NULL, ps->n_stmt++, expr);
4732 scop = pet_scop_from_pet_stmt(ctx, stmt);
4733 scop = scop_add_array(scop, skip_index, ps->ast_context);
4734 isl_multi_pw_aff_free(skip_index);
4736 return scop;
4737 error:
4738 isl_multi_pw_aff_free(skip_index);
4739 return NULL;
4742 /* Structure that handles the construction of skip conditions
4743 * on sequences of statements.
4745 * scop1 and scop2 represent the two statements that are combined
4747 struct pet_skip_info_seq : public pet_skip_info {
4748 struct pet_scop *scop1, *scop2;
4750 pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4751 struct pet_scop *scop2);
4752 void extract(PetScan *scan, enum pet_skip type);
4753 void extract(PetScan *scan);
4754 struct pet_scop *add(struct pet_scop *scop, enum pet_skip type,
4755 int offset);
4756 struct pet_scop *add(struct pet_scop *scop, int offset);
4759 /* Initialize a pet_skip_info_seq structure based on
4760 * on the two statements that are going to be combined.
4762 pet_skip_info_seq::pet_skip_info_seq(isl_ctx *ctx, struct pet_scop *scop1,
4763 struct pet_scop *scop2) : pet_skip_info(ctx), scop1(scop1), scop2(scop2)
4765 skip[pet_skip_now] = need_skip_seq(scop1, scop2, pet_skip_now);
4766 equal = skip[pet_skip_now] && skip_equals_skip_later(scop1) &&
4767 skip_equals_skip_later(scop2);
4768 skip[pet_skip_later] = skip[pet_skip_now] && !equal &&
4769 need_skip_seq(scop1, scop2, pet_skip_later);
4772 /* If we need to construct a skip condition of the given type,
4773 * then do so now.
4775 void pet_skip_info_seq::extract(PetScan *scan, enum pet_skip type)
4777 if (!skip[type])
4778 return;
4780 index[type] = create_test_index(ctx, scan->n_test++);
4781 scop[type] = extract_skip_seq(scan, isl_multi_pw_aff_copy(index[type]),
4782 scop1, scop2, type);
4785 /* Construct the required skip conditions.
4787 void pet_skip_info_seq::extract(PetScan *scan)
4789 extract(scan, pet_skip_now);
4790 extract(scan, pet_skip_later);
4791 if (equal)
4792 drop_skip_later(scop1, scop2);
4795 /* Add the computed skip condition of the given type to "main" and
4796 * add the scop for computing the condition at the given offset (the statement
4797 * number). Within this offset, the condition is computed at position 1
4798 * to ensure that it is computed after the corresponding statement.
4800 * If equal is set, then we only computed a skip condition for pet_skip_now,
4801 * but we also need to set it as main's pet_skip_later.
4803 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *main,
4804 enum pet_skip type, int offset)
4806 if (!skip[type])
4807 return main;
4809 scop[type] = pet_scop_prefix(scop[type], 1);
4810 scop[type] = pet_scop_prefix(scop[type], offset);
4811 main = pet_scop_add_par(ctx, main, scop[type]);
4812 scop[type] = NULL;
4814 if (equal)
4815 main = pet_scop_set_skip(main, pet_skip_later,
4816 isl_multi_pw_aff_copy(index[type]));
4818 main = pet_scop_set_skip(main, type, index[type]);
4819 index[type] = NULL;
4821 return main;
4824 /* Add the computed skip conditions to "main" and
4825 * add the scops for computing the conditions at the given offset.
4827 struct pet_scop *pet_skip_info_seq::add(struct pet_scop *scop, int offset)
4829 scop = add(scop, pet_skip_now, offset);
4830 scop = add(scop, pet_skip_later, offset);
4832 return scop;
4835 /* Extract a clone of the kill statement in "scop".
4836 * "scop" is expected to have been created from a DeclStmt
4837 * and should have the kill as its first statement.
4839 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
4841 pet_expr *kill;
4842 struct pet_stmt *stmt;
4843 isl_multi_pw_aff *index;
4844 isl_map *access;
4845 pet_expr *arg;
4847 if (!scop)
4848 return NULL;
4849 if (scop->n_stmt < 1)
4850 isl_die(ctx, isl_error_internal,
4851 "expecting at least one statement", return NULL);
4852 stmt = scop->stmts[0];
4853 if (!pet_stmt_is_kill(stmt))
4854 isl_die(ctx, isl_error_internal,
4855 "expecting kill statement", return NULL);
4857 arg = pet_expr_get_arg(stmt->body, 0);
4858 index = pet_expr_access_get_index(arg);
4859 access = pet_expr_access_get_access(arg);
4860 pet_expr_free(arg);
4861 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
4862 access = isl_map_reset_tuple_id(access, isl_dim_in);
4863 kill = pet_expr_kill_from_access_and_index(access, index);
4864 return pet_stmt_from_pet_expr(stmt->line, NULL, n_stmt++, kill);
4867 /* Mark all arrays in "scop" as being exposed.
4869 static struct pet_scop *mark_exposed(struct pet_scop *scop)
4871 if (!scop)
4872 return NULL;
4873 for (int i = 0; i < scop->n_array; ++i)
4874 scop->arrays[i]->exposed = 1;
4875 return scop;
4878 /* Try and construct a pet_scop corresponding to (part of)
4879 * a sequence of statements.
4881 * "block" is set if the sequence respresents the children of
4882 * a compound statement.
4883 * "skip_declarations" is set if we should skip initial declarations
4884 * in the sequence of statements.
4886 * If there are any breaks or continues in the individual statements,
4887 * then we may have to compute a new skip condition.
4888 * This is handled using a pet_skip_info_seq object.
4889 * On initialization, the object checks if skip conditions need
4890 * to be computed. If so, it does so in "extract" and adds them in "add".
4892 * If "block" is set, then we need to insert kill statements at
4893 * the end of the block for any array that has been declared by
4894 * one of the statements in the sequence. Each of these declarations
4895 * results in the construction of a kill statement at the place
4896 * of the declaration, so we simply collect duplicates of
4897 * those kill statements and append these duplicates to the constructed scop.
4899 * If "block" is not set, then any array declared by one of the statements
4900 * in the sequence is marked as being exposed.
4902 * If autodetect is set, then we allow the extraction of only a subrange
4903 * of the sequence of statements. However, if there is at least one statement
4904 * for which we could not construct a scop and the final range contains
4905 * either no statements or at least one kill, then we discard the entire
4906 * range.
4908 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
4909 bool skip_declarations)
4911 pet_scop *scop;
4912 StmtIterator i;
4913 int j;
4914 bool partial_range = false;
4915 set<struct pet_stmt *> kills;
4916 set<struct pet_stmt *>::iterator it;
4918 scop = pet_scop_empty(ctx);
4919 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4920 Stmt *child = *i;
4921 struct pet_scop *scop_i;
4923 if (scop->n_stmt == 0 && skip_declarations &&
4924 child->getStmtClass() == Stmt::DeclStmtClass)
4925 continue;
4927 scop_i = extract(child);
4928 if (scop->n_stmt != 0 && partial) {
4929 pet_scop_free(scop_i);
4930 break;
4932 pet_skip_info_seq skip(ctx, scop, scop_i);
4933 skip.extract(this);
4934 if (skip)
4935 scop_i = pet_scop_prefix(scop_i, 0);
4936 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4937 if (block)
4938 kills.insert(extract_kill(scop_i));
4939 else
4940 scop_i = mark_exposed(scop_i);
4942 scop_i = pet_scop_prefix(scop_i, j);
4943 if (options->autodetect) {
4944 if (scop_i)
4945 scop = pet_scop_add_seq(ctx, scop, scop_i);
4946 else
4947 partial_range = true;
4948 if (scop->n_stmt != 0 && !scop_i)
4949 partial = true;
4950 } else {
4951 scop = pet_scop_add_seq(ctx, scop, scop_i);
4954 scop = skip.add(scop, j);
4956 if (partial || !scop)
4957 break;
4960 for (it = kills.begin(); it != kills.end(); ++it) {
4961 pet_scop *scop_j;
4962 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4963 scop_j = pet_scop_prefix(scop_j, j);
4964 scop = pet_scop_add_seq(ctx, scop, scop_j);
4967 if (scop && partial_range) {
4968 if (scop->n_stmt == 0 || kills.size() != 0) {
4969 pet_scop_free(scop);
4970 return NULL;
4972 partial = true;
4975 return scop;
4978 /* Check if the scop marked by the user is exactly this Stmt
4979 * or part of this Stmt.
4980 * If so, return a pet_scop corresponding to the marked region.
4981 * Otherwise, return NULL.
4983 struct pet_scop *PetScan::scan(Stmt *stmt)
4985 SourceManager &SM = PP.getSourceManager();
4986 unsigned start_off, end_off;
4988 start_off = getExpansionOffset(SM, stmt->getLocStart());
4989 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4991 if (start_off > loc.end)
4992 return NULL;
4993 if (end_off < loc.start)
4994 return NULL;
4995 if (start_off >= loc.start && end_off <= loc.end) {
4996 return extract(stmt);
4999 StmtIterator start;
5000 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
5001 Stmt *child = *start;
5002 if (!child)
5003 continue;
5004 start_off = getExpansionOffset(SM, child->getLocStart());
5005 end_off = getExpansionOffset(SM, child->getLocEnd());
5006 if (start_off < loc.start && end_off >= loc.end)
5007 return scan(child);
5008 if (start_off >= loc.start)
5009 break;
5012 StmtIterator end;
5013 for (end = start; end != stmt->child_end(); ++end) {
5014 Stmt *child = *end;
5015 start_off = SM.getFileOffset(child->getLocStart());
5016 if (start_off >= loc.end)
5017 break;
5020 return extract(StmtRange(start, end), false, false);
5023 /* Set the size of index "pos" of "array" to "size".
5024 * In particular, add a constraint of the form
5026 * i_pos < size
5028 * to array->extent and a constraint of the form
5030 * size >= 0
5032 * to array->context.
5034 static struct pet_array *update_size(struct pet_array *array, int pos,
5035 __isl_take isl_pw_aff *size)
5037 isl_set *valid;
5038 isl_set *univ;
5039 isl_set *bound;
5040 isl_space *dim;
5041 isl_aff *aff;
5042 isl_pw_aff *index;
5043 isl_id *id;
5045 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
5046 array->context = isl_set_intersect(array->context, valid);
5048 dim = isl_set_get_space(array->extent);
5049 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
5050 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
5051 univ = isl_set_universe(isl_aff_get_domain_space(aff));
5052 index = isl_pw_aff_alloc(univ, aff);
5054 size = isl_pw_aff_add_dims(size, isl_dim_in,
5055 isl_set_dim(array->extent, isl_dim_set));
5056 id = isl_set_get_tuple_id(array->extent);
5057 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
5058 bound = isl_pw_aff_lt_set(index, size);
5060 array->extent = isl_set_intersect(array->extent, bound);
5062 if (!array->context || !array->extent)
5063 goto error;
5065 return array;
5066 error:
5067 pet_array_free(array);
5068 return NULL;
5071 /* Figure out the size of the array at position "pos" and all
5072 * subsequent positions from "type" and update "array" accordingly.
5074 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
5075 const Type *type, int pos)
5077 const ArrayType *atype;
5078 isl_pw_aff *size;
5080 if (!array)
5081 return NULL;
5083 if (type->isPointerType()) {
5084 type = type->getPointeeType().getTypePtr();
5085 return set_upper_bounds(array, type, pos + 1);
5087 if (!type->isArrayType())
5088 return array;
5090 type = type->getCanonicalTypeInternal().getTypePtr();
5091 atype = cast<ArrayType>(type);
5093 if (type->isConstantArrayType()) {
5094 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
5095 size = extract_affine(ca->getSize());
5096 array = update_size(array, pos, size);
5097 } else if (type->isVariableArrayType()) {
5098 const VariableArrayType *vla = cast<VariableArrayType>(atype);
5099 size = extract_affine(vla->getSizeExpr());
5100 array = update_size(array, pos, size);
5103 type = atype->getElementType().getTypePtr();
5105 return set_upper_bounds(array, type, pos + 1);
5108 /* Is "T" the type of a variable length array with static size?
5110 static bool is_vla_with_static_size(QualType T)
5112 const VariableArrayType *vlatype;
5114 if (!T->isVariableArrayType())
5115 return false;
5116 vlatype = cast<VariableArrayType>(T);
5117 return vlatype->getSizeModifier() == VariableArrayType::Static;
5120 /* Return the type of "decl" as an array.
5122 * In particular, if "decl" is a parameter declaration that
5123 * is a variable length array with a static size, then
5124 * return the original type (i.e., the variable length array).
5125 * Otherwise, return the type of decl.
5127 static QualType get_array_type(ValueDecl *decl)
5129 ParmVarDecl *parm;
5130 QualType T;
5132 parm = dyn_cast<ParmVarDecl>(decl);
5133 if (!parm)
5134 return decl->getType();
5136 T = parm->getOriginalType();
5137 if (!is_vla_with_static_size(T))
5138 return decl->getType();
5139 return T;
5142 /* Does "decl" have definition that we can keep track of in a pet_type?
5144 static bool has_printable_definition(RecordDecl *decl)
5146 if (!decl->getDeclName())
5147 return false;
5148 return decl->getLexicalDeclContext() == decl->getDeclContext();
5151 /* Construct and return a pet_array corresponding to the variable "decl".
5152 * In particular, initialize array->extent to
5154 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
5156 * and then call set_upper_bounds to set the upper bounds on the indices
5157 * based on the type of the variable.
5159 * If the base type is that of a record with a top-level definition and
5160 * if "types" is not null, then the RecordDecl corresponding to the type
5161 * is added to "types".
5163 * If the base type is that of a record with no top-level definition,
5164 * then we replace it by "<subfield>".
5166 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
5167 lex_recorddecl_set *types)
5169 struct pet_array *array;
5170 QualType qt = get_array_type(decl);
5171 const Type *type = qt.getTypePtr();
5172 int depth = array_depth(type);
5173 QualType base = pet_clang_base_type(qt);
5174 string name;
5175 isl_id *id;
5176 isl_space *dim;
5178 array = isl_calloc_type(ctx, struct pet_array);
5179 if (!array)
5180 return NULL;
5182 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
5183 dim = isl_space_set_alloc(ctx, 0, depth);
5184 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
5186 array->extent = isl_set_nat_universe(dim);
5188 dim = isl_space_params_alloc(ctx, 0);
5189 array->context = isl_set_universe(dim);
5191 array = set_upper_bounds(array, type, 0);
5192 if (!array)
5193 return NULL;
5195 name = base.getAsString();
5197 if (types && base->isRecordType()) {
5198 RecordDecl *decl = pet_clang_record_decl(base);
5199 if (has_printable_definition(decl))
5200 types->insert(decl);
5201 else
5202 name = "<subfield>";
5205 array->element_type = strdup(name.c_str());
5206 array->element_is_record = base->isRecordType();
5207 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
5209 return array;
5212 /* Construct and return a pet_array corresponding to the sequence
5213 * of declarations "decls".
5214 * If the sequence contains a single declaration, then it corresponds
5215 * to a simple array access. Otherwise, it corresponds to a member access,
5216 * with the declaration for the substructure following that of the containing
5217 * structure in the sequence of declarations.
5218 * We start with the outermost substructure and then combine it with
5219 * information from the inner structures.
5221 * Additionally, keep track of all required types in "types".
5223 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
5224 vector<ValueDecl *> decls, lex_recorddecl_set *types)
5226 struct pet_array *array;
5227 vector<ValueDecl *>::iterator it;
5229 it = decls.begin();
5231 array = extract_array(ctx, *it, types);
5233 for (++it; it != decls.end(); ++it) {
5234 struct pet_array *parent;
5235 const char *base_name, *field_name;
5236 char *product_name;
5238 parent = array;
5239 array = extract_array(ctx, *it, types);
5240 if (!array)
5241 return pet_array_free(parent);
5243 base_name = isl_set_get_tuple_name(parent->extent);
5244 field_name = isl_set_get_tuple_name(array->extent);
5245 product_name = member_access_name(ctx, base_name, field_name);
5247 array->extent = isl_set_product(isl_set_copy(parent->extent),
5248 array->extent);
5249 if (product_name)
5250 array->extent = isl_set_set_tuple_name(array->extent,
5251 product_name);
5252 array->context = isl_set_intersect(array->context,
5253 isl_set_copy(parent->context));
5255 pet_array_free(parent);
5256 free(product_name);
5258 if (!array->extent || !array->context || !product_name)
5259 return pet_array_free(array);
5262 return array;
5265 /* Add a pet_type corresponding to "decl" to "scop, provided
5266 * it is a member of "types" and it has not been added before
5267 * (i.e., it is not a member of "types_done".
5269 * Since we want the user to be able to print the types
5270 * in the order in which they appear in the scop, we need to
5271 * make sure that types of fields in a structure appear before
5272 * that structure. We therefore call ourselves recursively
5273 * on the types of all record subfields.
5275 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
5276 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
5277 lex_recorddecl_set &types_done)
5279 string s;
5280 llvm::raw_string_ostream S(s);
5281 RecordDecl::field_iterator it;
5283 if (types.find(decl) == types.end())
5284 return scop;
5285 if (types_done.find(decl) != types_done.end())
5286 return scop;
5288 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
5289 RecordDecl *record;
5290 QualType type = it->getType();
5292 if (!type->isRecordType())
5293 continue;
5294 record = pet_clang_record_decl(type);
5295 scop = add_type(ctx, scop, record, PP, types, types_done);
5298 if (strlen(decl->getName().str().c_str()) == 0)
5299 return scop;
5301 decl->print(S, PrintingPolicy(PP.getLangOpts()));
5302 S.str();
5304 scop->types[scop->n_type] = pet_type_alloc(ctx,
5305 decl->getName().str().c_str(), s.c_str());
5306 if (!scop->types[scop->n_type])
5307 return pet_scop_free(scop);
5309 types_done.insert(decl);
5311 scop->n_type++;
5313 return scop;
5316 /* Construct a list of pet_arrays, one for each array (or scalar)
5317 * accessed inside "scop", add this list to "scop" and return the result.
5319 * The context of "scop" is updated with the intersection of
5320 * the contexts of all arrays, i.e., constraints on the parameters
5321 * that ensure that the arrays have a valid (non-negative) size.
5323 * If the any of the extracted arrays refers to a member access,
5324 * then also add the required types to "scop".
5326 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
5328 int i;
5329 array_desc_set arrays;
5330 array_desc_set::iterator it;
5331 lex_recorddecl_set types;
5332 lex_recorddecl_set types_done;
5333 lex_recorddecl_set::iterator types_it;
5334 int n_array;
5335 struct pet_array **scop_arrays;
5337 if (!scop)
5338 return NULL;
5340 pet_scop_collect_arrays(scop, arrays);
5341 if (arrays.size() == 0)
5342 return scop;
5344 n_array = scop->n_array;
5346 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
5347 n_array + arrays.size());
5348 if (!scop_arrays)
5349 goto error;
5350 scop->arrays = scop_arrays;
5352 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
5353 struct pet_array *array;
5354 array = extract_array(ctx, *it, &types);
5355 scop->arrays[n_array + i] = array;
5356 if (!scop->arrays[n_array + i])
5357 goto error;
5358 scop->n_array++;
5359 scop->context = isl_set_intersect(scop->context,
5360 isl_set_copy(array->context));
5361 if (!scop->context)
5362 goto error;
5365 if (types.size() == 0)
5366 return scop;
5368 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
5369 if (!scop->types)
5370 goto error;
5372 for (types_it = types.begin(); types_it != types.end(); ++types_it)
5373 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
5375 return scop;
5376 error:
5377 pet_scop_free(scop);
5378 return NULL;
5381 /* Bound all parameters in scop->context to the possible values
5382 * of the corresponding C variable.
5384 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
5386 int n;
5388 if (!scop)
5389 return NULL;
5391 n = isl_set_dim(scop->context, isl_dim_param);
5392 for (int i = 0; i < n; ++i) {
5393 isl_id *id;
5394 ValueDecl *decl;
5396 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
5397 if (pet_nested_in_id(id)) {
5398 isl_id_free(id);
5399 isl_die(isl_set_get_ctx(scop->context),
5400 isl_error_internal,
5401 "unresolved nested parameter", goto error);
5403 decl = (ValueDecl *) isl_id_get_user(id);
5404 isl_id_free(id);
5406 scop->context = set_parameter_bounds(scop->context, i, decl);
5408 if (!scop->context)
5409 goto error;
5412 return scop;
5413 error:
5414 pet_scop_free(scop);
5415 return NULL;
5418 /* Construct a pet_scop from the given function.
5420 * If the scop was delimited by scop and endscop pragmas, then we override
5421 * the file offsets by those derived from the pragmas.
5423 struct pet_scop *PetScan::scan(FunctionDecl *fd)
5425 pet_scop *scop;
5426 Stmt *stmt;
5428 stmt = fd->getBody();
5430 if (options->autodetect)
5431 scop = extract(stmt, true);
5432 else {
5433 scop = scan(stmt);
5434 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
5436 scop = pet_scop_detect_parameter_accesses(scop);
5437 scop = scan_arrays(scop);
5438 scop = add_parameter_bounds(scop);
5439 scop = pet_scop_gist(scop, value_bounds);
5441 return scop;