extract out pet_to_bool
[pet.git] / scan.cc
blob303234a782f18a971beb0e9a5024094a4972c275
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"
58 #include "skip.h"
60 #include "config.h"
62 using namespace std;
63 using namespace clang;
65 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
67 switch (kind) {
68 case UO_Minus:
69 return pet_op_minus;
70 case UO_Not:
71 return pet_op_not;
72 case UO_LNot:
73 return pet_op_lnot;
74 case UO_PostInc:
75 return pet_op_post_inc;
76 case UO_PostDec:
77 return pet_op_post_dec;
78 case UO_PreInc:
79 return pet_op_pre_inc;
80 case UO_PreDec:
81 return pet_op_pre_dec;
82 default:
83 return pet_op_last;
87 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
89 switch (kind) {
90 case BO_AddAssign:
91 return pet_op_add_assign;
92 case BO_SubAssign:
93 return pet_op_sub_assign;
94 case BO_MulAssign:
95 return pet_op_mul_assign;
96 case BO_DivAssign:
97 return pet_op_div_assign;
98 case BO_Assign:
99 return pet_op_assign;
100 case BO_Add:
101 return pet_op_add;
102 case BO_Sub:
103 return pet_op_sub;
104 case BO_Mul:
105 return pet_op_mul;
106 case BO_Div:
107 return pet_op_div;
108 case BO_Rem:
109 return pet_op_mod;
110 case BO_Shl:
111 return pet_op_shl;
112 case BO_Shr:
113 return pet_op_shr;
114 case BO_EQ:
115 return pet_op_eq;
116 case BO_NE:
117 return pet_op_ne;
118 case BO_LE:
119 return pet_op_le;
120 case BO_GE:
121 return pet_op_ge;
122 case BO_LT:
123 return pet_op_lt;
124 case BO_GT:
125 return pet_op_gt;
126 case BO_And:
127 return pet_op_and;
128 case BO_Xor:
129 return pet_op_xor;
130 case BO_Or:
131 return pet_op_or;
132 case BO_LAnd:
133 return pet_op_land;
134 case BO_LOr:
135 return pet_op_lor;
136 default:
137 return pet_op_last;
141 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
142 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
144 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
145 SourceLocation(), var, false, var->getInnerLocStart(),
146 var->getType(), VK_LValue);
148 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
149 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
151 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
152 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
153 VK_LValue);
155 #else
156 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
158 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
159 var, var->getInnerLocStart(), var->getType(), VK_LValue);
161 #endif
163 /* Check if the element type corresponding to the given array type
164 * has a const qualifier.
166 static bool const_base(QualType qt)
168 const Type *type = qt.getTypePtr();
170 if (type->isPointerType())
171 return const_base(type->getPointeeType());
172 if (type->isArrayType()) {
173 const ArrayType *atype;
174 type = type->getCanonicalTypeInternal().getTypePtr();
175 atype = cast<ArrayType>(type);
176 return const_base(atype->getElementType());
179 return qt.isConstQualified();
182 /* Mark "decl" as having an unknown value in "assigned_value".
184 * If no (known or unknown) value was assigned to "decl" before,
185 * then it may have been treated as a parameter before and may
186 * therefore appear in a value assigned to another variable.
187 * If so, this assignment needs to be turned into an unknown value too.
189 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
190 ValueDecl *decl)
192 map<ValueDecl *, isl_pw_aff *>::iterator it;
194 it = assigned_value.find(decl);
196 assigned_value[decl] = NULL;
198 if (it != assigned_value.end())
199 return;
201 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
202 isl_pw_aff *pa = it->second;
203 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
205 for (int i = 0; i < nparam; ++i) {
206 isl_id *id;
208 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
209 continue;
210 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
211 if (isl_id_get_user(id) == decl)
212 it->second = NULL;
213 isl_id_free(id);
218 /* Look for any assignments to scalar variables in part of the parse
219 * tree and set assigned_value to NULL for each of them.
220 * Also reset assigned_value if the address of a scalar variable
221 * is being taken. As an exception, if the address is passed to a function
222 * that is declared to receive a const pointer, then assigned_value is
223 * not reset.
225 * This ensures that we won't use any previously stored value
226 * in the current subtree and its parents.
228 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
229 map<ValueDecl *, isl_pw_aff *> &assigned_value;
230 set<UnaryOperator *> skip;
232 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
233 assigned_value(assigned_value) {}
235 /* Check for "address of" operators whose value is passed
236 * to a const pointer argument and add them to "skip", so that
237 * we can skip them in VisitUnaryOperator.
239 bool VisitCallExpr(CallExpr *expr) {
240 FunctionDecl *fd;
241 fd = expr->getDirectCallee();
242 if (!fd)
243 return true;
244 for (int i = 0; i < expr->getNumArgs(); ++i) {
245 Expr *arg = expr->getArg(i);
246 UnaryOperator *op;
247 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
248 ImplicitCastExpr *ice;
249 ice = cast<ImplicitCastExpr>(arg);
250 arg = ice->getSubExpr();
252 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
253 continue;
254 op = cast<UnaryOperator>(arg);
255 if (op->getOpcode() != UO_AddrOf)
256 continue;
257 if (const_base(fd->getParamDecl(i)->getType()))
258 skip.insert(op);
260 return true;
263 bool VisitUnaryOperator(UnaryOperator *expr) {
264 Expr *arg;
265 DeclRefExpr *ref;
266 ValueDecl *decl;
268 switch (expr->getOpcode()) {
269 case UO_AddrOf:
270 case UO_PostInc:
271 case UO_PostDec:
272 case UO_PreInc:
273 case UO_PreDec:
274 break;
275 default:
276 return true;
278 if (skip.find(expr) != skip.end())
279 return true;
281 arg = expr->getSubExpr();
282 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
283 return true;
284 ref = cast<DeclRefExpr>(arg);
285 decl = ref->getDecl();
286 clear_assignment(assigned_value, decl);
287 return true;
290 bool VisitBinaryOperator(BinaryOperator *expr) {
291 Expr *lhs;
292 DeclRefExpr *ref;
293 ValueDecl *decl;
295 if (!expr->isAssignmentOp())
296 return true;
297 lhs = expr->getLHS();
298 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
299 return true;
300 ref = cast<DeclRefExpr>(lhs);
301 decl = ref->getDecl();
302 clear_assignment(assigned_value, decl);
303 return true;
307 /* Keep a copy of the currently assigned values.
309 * Any variable that is assigned a value inside the current scope
310 * is removed again when we leave the scope (either because it wasn't
311 * stored in the cache or because it has a different value in the cache).
313 struct assigned_value_cache {
314 map<ValueDecl *, isl_pw_aff *> &assigned_value;
315 map<ValueDecl *, isl_pw_aff *> cache;
317 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
318 assigned_value(assigned_value), cache(assigned_value) {}
319 ~assigned_value_cache() {
320 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
321 for (it = assigned_value.begin(); it != assigned_value.end();
322 ++it) {
323 if (!it->second ||
324 (cache.find(it->first) != cache.end() &&
325 cache[it->first] != it->second))
326 cache[it->first] = NULL;
328 assigned_value = cache;
332 /* Insert an expression into the collection of expressions,
333 * provided it is not already in there.
334 * The isl_pw_affs are freed in the destructor.
336 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
338 std::set<isl_pw_aff *>::iterator it;
340 if (expressions.find(expr) == expressions.end())
341 expressions.insert(expr);
342 else
343 isl_pw_aff_free(expr);
346 PetScan::~PetScan()
348 std::set<isl_pw_aff *>::iterator it;
350 for (it = expressions.begin(); it != expressions.end(); ++it)
351 isl_pw_aff_free(*it);
353 isl_union_map_free(value_bounds);
356 /* Report a diagnostic, unless autodetect is set.
358 void PetScan::report(Stmt *stmt, unsigned id)
360 if (options->autodetect)
361 return;
363 SourceLocation loc = stmt->getLocStart();
364 DiagnosticsEngine &diag = PP.getDiagnostics();
365 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
368 /* Called if we found something we (currently) cannot handle.
369 * We'll provide more informative warnings later.
371 * We only actually complain if autodetect is false.
373 void PetScan::unsupported(Stmt *stmt)
375 DiagnosticsEngine &diag = PP.getDiagnostics();
376 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
377 "unsupported");
378 report(stmt, id);
381 /* Report a missing prototype, unless autodetect is set.
383 void PetScan::report_prototype_required(Stmt *stmt)
385 DiagnosticsEngine &diag = PP.getDiagnostics();
386 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
387 "prototype required");
388 report(stmt, id);
391 /* Report a missing increment, unless autodetect is set.
393 void PetScan::report_missing_increment(Stmt *stmt)
395 DiagnosticsEngine &diag = PP.getDiagnostics();
396 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
397 "missing increment");
398 report(stmt, id);
401 /* Extract an integer from "expr".
403 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
405 const Type *type = expr->getType().getTypePtr();
406 int is_signed = type->hasSignedIntegerRepresentation();
407 llvm::APInt val = expr->getValue();
408 int is_negative = is_signed && val.isNegative();
409 isl_val *v;
411 if (is_negative)
412 val = -val;
414 v = extract_unsigned(ctx, val);
416 if (is_negative)
417 v = isl_val_neg(v);
418 return v;
421 /* Extract an integer from "val", which is assumed to be non-negative.
423 __isl_give isl_val *PetScan::extract_unsigned(isl_ctx *ctx,
424 const llvm::APInt &val)
426 unsigned n;
427 const uint64_t *data;
429 data = val.getRawData();
430 n = val.getNumWords();
431 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
434 /* Extract an integer from "expr".
435 * Return NULL if "expr" does not (obviously) represent an integer.
437 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
439 return extract_int(expr->getSubExpr());
442 /* Extract an integer from "expr".
443 * Return NULL if "expr" does not (obviously) represent an integer.
445 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
447 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
448 return extract_int(ctx, cast<IntegerLiteral>(expr));
449 if (expr->getStmtClass() == Stmt::ParenExprClass)
450 return extract_int(cast<ParenExpr>(expr));
452 unsupported(expr);
453 return NULL;
456 /* Extract an affine expression from the IntegerLiteral "expr".
458 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
460 isl_space *dim = isl_space_params_alloc(ctx, 0);
461 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
462 isl_aff *aff = isl_aff_zero_on_domain(ls);
463 isl_set *dom = isl_set_universe(dim);
464 isl_val *v;
466 v = extract_int(expr);
467 aff = isl_aff_add_constant_val(aff, v);
469 return isl_pw_aff_alloc(dom, aff);
472 /* Extract an affine expression from the APInt "val", which is assumed
473 * to be non-negative.
475 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
477 isl_space *dim = isl_space_params_alloc(ctx, 0);
478 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
479 isl_aff *aff = isl_aff_zero_on_domain(ls);
480 isl_set *dom = isl_set_universe(dim);
481 isl_val *v;
483 v = extract_unsigned(ctx, val);
484 aff = isl_aff_add_constant_val(aff, v);
486 return isl_pw_aff_alloc(dom, aff);
489 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
491 return extract_affine(expr->getSubExpr());
494 /* Return the number of bits needed to represent the type "qt",
495 * if it is an integer type. Otherwise return 0.
496 * If qt is signed then return the opposite of the number of bits.
498 static int get_type_size(QualType qt, ASTContext &ast_context)
500 int size;
502 if (!qt->isIntegerType())
503 return 0;
505 size = ast_context.getIntWidth(qt);
506 if (!qt->isUnsignedIntegerType())
507 size = -size;
509 return size;
512 /* Return the number of bits needed to represent the type of "decl",
513 * if it is an integer type. Otherwise return 0.
514 * If qt is signed then return the opposite of the number of bits.
516 static int get_type_size(ValueDecl *decl)
518 return get_type_size(decl->getType(), decl->getASTContext());
521 /* Bound parameter "pos" of "set" to the possible values of "decl".
523 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
524 unsigned pos, ValueDecl *decl)
526 int type_size;
527 isl_ctx *ctx;
528 isl_val *bound;
530 ctx = isl_set_get_ctx(set);
531 type_size = get_type_size(decl);
532 if (type_size == 0)
533 isl_die(ctx, isl_error_invalid, "not an integer type",
534 return isl_set_free(set));
535 if (type_size > 0) {
536 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
537 bound = isl_val_int_from_ui(ctx, type_size);
538 bound = isl_val_2exp(bound);
539 bound = isl_val_sub_ui(bound, 1);
540 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
541 } else {
542 bound = isl_val_int_from_ui(ctx, -type_size - 1);
543 bound = isl_val_2exp(bound);
544 bound = isl_val_sub_ui(bound, 1);
545 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
546 isl_val_copy(bound));
547 bound = isl_val_neg(bound);
548 bound = isl_val_sub_ui(bound, 1);
549 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
552 return set;
555 /* Extract an affine expression from the DeclRefExpr "expr".
557 * If the variable has been assigned a value, then we check whether
558 * we know what (affine) value was assigned.
559 * If so, we return this value. Otherwise we convert "expr"
560 * to an extra parameter (provided nesting_enabled is set).
562 * Otherwise, we simply return an expression that is equal
563 * to a parameter corresponding to the referenced variable.
565 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
567 ValueDecl *decl = expr->getDecl();
568 const Type *type = decl->getType().getTypePtr();
569 isl_id *id;
570 isl_space *dim;
571 isl_aff *aff;
572 isl_set *dom;
574 if (!type->isIntegerType()) {
575 unsupported(expr);
576 return NULL;
579 if (assigned_value.find(decl) != assigned_value.end()) {
580 if (assigned_value[decl])
581 return isl_pw_aff_copy(assigned_value[decl]);
582 else
583 return nested_access(expr);
586 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
587 dim = isl_space_params_alloc(ctx, 1);
589 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
591 dom = isl_set_universe(isl_space_copy(dim));
592 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
593 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
595 return isl_pw_aff_alloc(dom, aff);
598 /* Extract an affine expression from an integer division operation.
599 * In particular, if "expr" is lhs/rhs, then return
601 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
603 * The second argument (rhs) is required to be a (positive) integer constant.
605 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
607 int is_cst;
608 isl_pw_aff *rhs, *lhs;
610 rhs = extract_affine(expr->getRHS());
611 is_cst = isl_pw_aff_is_cst(rhs);
612 if (is_cst < 0 || !is_cst) {
613 isl_pw_aff_free(rhs);
614 if (!is_cst)
615 unsupported(expr);
616 return NULL;
619 lhs = extract_affine(expr->getLHS());
621 return isl_pw_aff_tdiv_q(lhs, rhs);
624 /* Extract an affine expression from a modulo operation.
625 * In particular, if "expr" is lhs/rhs, then return
627 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
629 * The second argument (rhs) is required to be a (positive) integer constant.
631 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
633 int is_cst;
634 isl_pw_aff *rhs, *lhs;
636 rhs = extract_affine(expr->getRHS());
637 is_cst = isl_pw_aff_is_cst(rhs);
638 if (is_cst < 0 || !is_cst) {
639 isl_pw_aff_free(rhs);
640 if (!is_cst)
641 unsupported(expr);
642 return NULL;
645 lhs = extract_affine(expr->getLHS());
647 return isl_pw_aff_tdiv_r(lhs, rhs);
650 /* Extract an affine expression from a multiplication operation.
651 * This is only allowed if at least one of the two arguments
652 * is a (piecewise) constant.
654 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
656 isl_pw_aff *lhs;
657 isl_pw_aff *rhs;
659 lhs = extract_affine(expr->getLHS());
660 rhs = extract_affine(expr->getRHS());
662 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
663 isl_pw_aff_free(lhs);
664 isl_pw_aff_free(rhs);
665 unsupported(expr);
666 return NULL;
669 return isl_pw_aff_mul(lhs, rhs);
672 /* Extract an affine expression from an addition or subtraction operation.
674 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
676 isl_pw_aff *lhs;
677 isl_pw_aff *rhs;
679 lhs = extract_affine(expr->getLHS());
680 rhs = extract_affine(expr->getRHS());
682 switch (expr->getOpcode()) {
683 case BO_Add:
684 return isl_pw_aff_add(lhs, rhs);
685 case BO_Sub:
686 return isl_pw_aff_sub(lhs, rhs);
687 default:
688 isl_pw_aff_free(lhs);
689 isl_pw_aff_free(rhs);
690 return NULL;
695 /* Compute
697 * pwaff mod 2^width
699 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
700 unsigned width)
702 isl_ctx *ctx;
703 isl_val *mod;
705 ctx = isl_pw_aff_get_ctx(pwaff);
706 mod = isl_val_int_from_ui(ctx, width);
707 mod = isl_val_2exp(mod);
709 pwaff = isl_pw_aff_mod_val(pwaff, mod);
711 return pwaff;
714 /* Limit the domain of "pwaff" to those elements where the function
715 * value satisfies
717 * 2^{width-1} <= pwaff < 2^{width-1}
719 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
720 unsigned width)
722 isl_ctx *ctx;
723 isl_val *v;
724 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
725 isl_local_space *ls = isl_local_space_from_space(space);
726 isl_aff *bound;
727 isl_set *dom;
728 isl_pw_aff *b;
730 ctx = isl_pw_aff_get_ctx(pwaff);
731 v = isl_val_int_from_ui(ctx, width - 1);
732 v = isl_val_2exp(v);
734 bound = isl_aff_zero_on_domain(ls);
735 bound = isl_aff_add_constant_val(bound, v);
736 b = isl_pw_aff_from_aff(bound);
738 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
739 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
741 b = isl_pw_aff_neg(b);
742 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
743 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
745 return pwaff;
748 /* Handle potential overflows on signed computations.
750 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
751 * the we adjust the domain of "pa" to avoid overflows.
753 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
754 unsigned width)
756 if (options->signed_overflow == PET_OVERFLOW_AVOID)
757 pa = avoid_overflow(pa, width);
759 return pa;
762 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
764 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
765 __isl_take isl_set *dom)
767 isl_pw_aff *pa;
768 pa = isl_set_indicator_function(set);
769 pa = isl_pw_aff_intersect_domain(pa, isl_set_coalesce(dom));
770 return pa;
773 /* Extract an affine expression from some binary operations.
774 * If the result of the expression is unsigned, then we wrap it
775 * based on the size of the type. Otherwise, we ensure that
776 * no overflow occurs.
778 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
780 isl_pw_aff *res;
781 unsigned width;
783 switch (expr->getOpcode()) {
784 case BO_Add:
785 case BO_Sub:
786 res = extract_affine_add(expr);
787 break;
788 case BO_Div:
789 res = extract_affine_div(expr);
790 break;
791 case BO_Rem:
792 res = extract_affine_mod(expr);
793 break;
794 case BO_Mul:
795 res = extract_affine_mul(expr);
796 break;
797 case BO_LT:
798 case BO_LE:
799 case BO_GT:
800 case BO_GE:
801 case BO_EQ:
802 case BO_NE:
803 case BO_LAnd:
804 case BO_LOr:
805 return extract_condition(expr);
806 default:
807 unsupported(expr);
808 return NULL;
811 width = ast_context.getIntWidth(expr->getType());
812 if (expr->getType()->isUnsignedIntegerType())
813 res = wrap(res, width);
814 else
815 res = signed_overflow(res, width);
817 return res;
820 /* Extract an affine expression from a negation operation.
822 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
824 if (expr->getOpcode() == UO_Minus)
825 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
826 if (expr->getOpcode() == UO_LNot)
827 return extract_condition(expr);
829 unsupported(expr);
830 return NULL;
833 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
835 return extract_affine(expr->getSubExpr());
838 /* Extract an affine expression from some special function calls.
839 * In particular, we handle "min", "max", "ceild", "floord",
840 * "intMod", "intFloor" and "intCeil".
841 * In case of the latter five, the second argument needs to be
842 * a (positive) integer constant.
844 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
846 FunctionDecl *fd;
847 string name;
848 isl_pw_aff *aff1, *aff2;
850 fd = expr->getDirectCallee();
851 if (!fd) {
852 unsupported(expr);
853 return NULL;
856 name = fd->getDeclName().getAsString();
857 if (!(expr->getNumArgs() == 2 && name == "min") &&
858 !(expr->getNumArgs() == 2 && name == "max") &&
859 !(expr->getNumArgs() == 2 && name == "intMod") &&
860 !(expr->getNumArgs() == 2 && name == "intFloor") &&
861 !(expr->getNumArgs() == 2 && name == "intCeil") &&
862 !(expr->getNumArgs() == 2 && name == "floord") &&
863 !(expr->getNumArgs() == 2 && name == "ceild")) {
864 unsupported(expr);
865 return NULL;
868 if (name == "min" || name == "max") {
869 aff1 = extract_affine(expr->getArg(0));
870 aff2 = extract_affine(expr->getArg(1));
872 if (name == "min")
873 aff1 = isl_pw_aff_min(aff1, aff2);
874 else
875 aff1 = isl_pw_aff_max(aff1, aff2);
876 } else if (name == "intMod") {
877 isl_val *v;
878 Expr *arg2 = expr->getArg(1);
880 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
881 unsupported(expr);
882 return NULL;
884 aff1 = extract_affine(expr->getArg(0));
885 v = extract_int(cast<IntegerLiteral>(arg2));
886 aff1 = isl_pw_aff_mod_val(aff1, v);
887 } else if (name == "floord" || name == "ceild" ||
888 name == "intFloor" || name == "intCeil") {
889 isl_val *v;
890 Expr *arg2 = expr->getArg(1);
892 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
893 unsupported(expr);
894 return NULL;
896 aff1 = extract_affine(expr->getArg(0));
897 v = extract_int(cast<IntegerLiteral>(arg2));
898 aff1 = isl_pw_aff_scale_down_val(aff1, v);
899 if (name == "floord" || name == "intFloor")
900 aff1 = isl_pw_aff_floor(aff1);
901 else
902 aff1 = isl_pw_aff_ceil(aff1);
903 } else {
904 unsupported(expr);
905 return NULL;
908 return aff1;
911 /* This method is called when we come across an access that is
912 * nested in what is supposed to be an affine expression.
913 * If nesting is allowed, we return a new parameter that corresponds
914 * to this nested access. Otherwise, we simply complain.
916 * Note that we currently don't allow nested accesses themselves
917 * to contain any nested accesses, so we check if we can extract
918 * the access without any nesting and complain if we can't.
920 * The new parameter is resolved in resolve_nested.
922 isl_pw_aff *PetScan::nested_access(Expr *expr)
924 isl_id *id;
925 isl_space *dim;
926 isl_aff *aff;
927 isl_set *dom;
928 isl_multi_pw_aff *index;
930 if (!nesting_enabled) {
931 unsupported(expr);
932 return NULL;
935 allow_nested = false;
936 index = extract_index(expr);
937 allow_nested = true;
938 if (!index) {
939 unsupported(expr);
940 return NULL;
942 isl_multi_pw_aff_free(index);
944 id = pet_nested_clang_expr(ctx, expr);
945 dim = isl_space_params_alloc(ctx, 1);
947 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
949 dom = isl_set_universe(isl_space_copy(dim));
950 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
951 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
953 return isl_pw_aff_alloc(dom, aff);
956 /* Affine expressions are not supposed to contain array accesses,
957 * but if nesting is allowed, we return a parameter corresponding
958 * to the array access.
960 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
962 return nested_access(expr);
965 /* Affine expressions are not supposed to contain member accesses,
966 * but if nesting is allowed, we return a parameter corresponding
967 * to the member access.
969 __isl_give isl_pw_aff *PetScan::extract_affine(MemberExpr *expr)
971 return nested_access(expr);
974 /* Extract an affine expression from a conditional operation.
976 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
978 isl_pw_aff *cond, *lhs, *rhs;
980 cond = extract_condition(expr->getCond());
981 lhs = extract_affine(expr->getTrueExpr());
982 rhs = extract_affine(expr->getFalseExpr());
984 return isl_pw_aff_cond(cond, lhs, rhs);
987 /* Extract an affine expression, if possible, from "expr".
988 * Otherwise return NULL.
990 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
992 switch (expr->getStmtClass()) {
993 case Stmt::ImplicitCastExprClass:
994 return extract_affine(cast<ImplicitCastExpr>(expr));
995 case Stmt::IntegerLiteralClass:
996 return extract_affine(cast<IntegerLiteral>(expr));
997 case Stmt::DeclRefExprClass:
998 return extract_affine(cast<DeclRefExpr>(expr));
999 case Stmt::BinaryOperatorClass:
1000 return extract_affine(cast<BinaryOperator>(expr));
1001 case Stmt::UnaryOperatorClass:
1002 return extract_affine(cast<UnaryOperator>(expr));
1003 case Stmt::ParenExprClass:
1004 return extract_affine(cast<ParenExpr>(expr));
1005 case Stmt::CallExprClass:
1006 return extract_affine(cast<CallExpr>(expr));
1007 case Stmt::ArraySubscriptExprClass:
1008 return extract_affine(cast<ArraySubscriptExpr>(expr));
1009 case Stmt::MemberExprClass:
1010 return extract_affine(cast<MemberExpr>(expr));
1011 case Stmt::ConditionalOperatorClass:
1012 return extract_affine(cast<ConditionalOperator>(expr));
1013 default:
1014 unsupported(expr);
1016 return NULL;
1019 __isl_give isl_multi_pw_aff *PetScan::extract_index(ImplicitCastExpr *expr)
1021 return extract_index(expr->getSubExpr());
1024 /* Return the depth of an array of the given type.
1026 static int array_depth(const Type *type)
1028 if (type->isPointerType())
1029 return 1 + array_depth(type->getPointeeType().getTypePtr());
1030 if (type->isArrayType()) {
1031 const ArrayType *atype;
1032 type = type->getCanonicalTypeInternal().getTypePtr();
1033 atype = cast<ArrayType>(type);
1034 return 1 + array_depth(atype->getElementType().getTypePtr());
1036 return 0;
1039 /* Return the depth of the array accessed by the index expression "index".
1040 * If "index" is an affine expression, i.e., if it does not access
1041 * any array, then return 1.
1042 * If "index" represent a member access, i.e., if its range is a wrapped
1043 * relation, then return the sum of the depth of the array of structures
1044 * and that of the member inside the structure.
1046 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
1048 isl_id *id;
1049 ValueDecl *decl;
1051 if (!index)
1052 return -1;
1054 if (isl_multi_pw_aff_range_is_wrapping(index)) {
1055 int domain_depth, range_depth;
1056 isl_multi_pw_aff *domain, *range;
1058 domain = isl_multi_pw_aff_copy(index);
1059 domain = isl_multi_pw_aff_range_factor_domain(domain);
1060 domain_depth = extract_depth(domain);
1061 isl_multi_pw_aff_free(domain);
1062 range = isl_multi_pw_aff_copy(index);
1063 range = isl_multi_pw_aff_range_factor_range(range);
1064 range_depth = extract_depth(range);
1065 isl_multi_pw_aff_free(range);
1067 return domain_depth + range_depth;
1070 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
1071 return 1;
1073 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
1074 if (!id)
1075 return -1;
1076 decl = (ValueDecl *) isl_id_get_user(id);
1077 isl_id_free(id);
1079 return array_depth(decl->getType().getTypePtr());
1082 /* Extract an index expression from a reference to a variable.
1083 * If the variable has name "A", then the returned index expression
1084 * is of the form
1086 * { [] -> A[] }
1088 __isl_give isl_multi_pw_aff *PetScan::extract_index(DeclRefExpr *expr)
1090 return extract_index(expr->getDecl());
1093 /* Extract an index expression from a variable.
1094 * If the variable has name "A", then the returned index expression
1095 * is of the form
1097 * { [] -> A[] }
1099 __isl_give isl_multi_pw_aff *PetScan::extract_index(ValueDecl *decl)
1101 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
1102 isl_space *space = isl_space_alloc(ctx, 0, 0, 0);
1104 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1106 return isl_multi_pw_aff_zero(space);
1109 /* Extract an index expression from an integer contant.
1110 * If the value of the constant is "v", then the returned access relation
1111 * is
1113 * { [] -> [v] }
1115 __isl_give isl_multi_pw_aff *PetScan::extract_index(IntegerLiteral *expr)
1117 isl_multi_pw_aff *mpa;
1119 mpa = isl_multi_pw_aff_from_pw_aff(extract_affine(expr));
1120 mpa = isl_multi_pw_aff_from_range(mpa);
1121 return mpa;
1124 /* Try and extract an index expression from the given Expr.
1125 * Return NULL if it doesn't work out.
1127 __isl_give isl_multi_pw_aff *PetScan::extract_index(Expr *expr)
1129 switch (expr->getStmtClass()) {
1130 case Stmt::ImplicitCastExprClass:
1131 return extract_index(cast<ImplicitCastExpr>(expr));
1132 case Stmt::DeclRefExprClass:
1133 return extract_index(cast<DeclRefExpr>(expr));
1134 case Stmt::ArraySubscriptExprClass:
1135 return extract_index(cast<ArraySubscriptExpr>(expr));
1136 case Stmt::IntegerLiteralClass:
1137 return extract_index(cast<IntegerLiteral>(expr));
1138 case Stmt::MemberExprClass:
1139 return extract_index(cast<MemberExpr>(expr));
1140 default:
1141 unsupported(expr);
1143 return NULL;
1146 /* Given a partial index expression "base" and an extra index "index",
1147 * append the extra index to "base" and return the result.
1148 * Additionally, add the constraints that the extra index is non-negative.
1149 * If "index" represent a member access, i.e., if its range is a wrapped
1150 * relation, then we recursively extend the range of this nested relation.
1152 static __isl_give isl_multi_pw_aff *subscript(__isl_take isl_multi_pw_aff *base,
1153 __isl_take isl_pw_aff *index)
1155 isl_id *id;
1156 isl_set *domain;
1157 isl_multi_pw_aff *access;
1158 int member_access;
1160 member_access = isl_multi_pw_aff_range_is_wrapping(base);
1161 if (member_access < 0)
1162 goto error;
1163 if (member_access) {
1164 isl_multi_pw_aff *domain, *range;
1165 isl_id *id;
1167 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_out);
1168 domain = isl_multi_pw_aff_copy(base);
1169 domain = isl_multi_pw_aff_range_factor_domain(domain);
1170 range = isl_multi_pw_aff_range_factor_range(base);
1171 range = subscript(range, index);
1172 access = isl_multi_pw_aff_range_product(domain, range);
1173 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_out, id);
1174 return access;
1177 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_set);
1178 index = isl_pw_aff_from_range(index);
1179 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
1180 index = isl_pw_aff_intersect_domain(index, domain);
1181 access = isl_multi_pw_aff_from_pw_aff(index);
1182 access = isl_multi_pw_aff_flat_range_product(base, access);
1183 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_set, id);
1185 return access;
1186 error:
1187 isl_multi_pw_aff_free(base);
1188 isl_pw_aff_free(index);
1189 return NULL;
1192 /* Extract an index expression from the given array subscript expression.
1193 * If nesting is allowed in general, then we turn it on while
1194 * examining the index expression.
1196 * We first extract an index expression from the base.
1197 * This will result in an index expression with a range that corresponds
1198 * to the earlier indices.
1199 * We then extract the current index, restrict its domain
1200 * to those values that result in a non-negative index and
1201 * append the index to the base index expression.
1203 __isl_give isl_multi_pw_aff *PetScan::extract_index(ArraySubscriptExpr *expr)
1205 Expr *base = expr->getBase();
1206 Expr *idx = expr->getIdx();
1207 isl_pw_aff *index;
1208 isl_multi_pw_aff *base_access;
1209 isl_multi_pw_aff *access;
1210 bool save_nesting = nesting_enabled;
1212 nesting_enabled = allow_nested;
1214 base_access = extract_index(base);
1215 index = extract_affine(idx);
1217 nesting_enabled = save_nesting;
1219 access = subscript(base_access, index);
1221 return access;
1224 /* Construct a name for a member access by concatenating the name
1225 * of the array of structures and the member, separated by an underscore.
1227 * The caller is responsible for freeing the result.
1229 static char *member_access_name(isl_ctx *ctx, const char *base,
1230 const char *field)
1232 int len;
1233 char *name;
1235 len = strlen(base) + 1 + strlen(field);
1236 name = isl_alloc_array(ctx, char, len + 1);
1237 if (!name)
1238 return NULL;
1239 snprintf(name, len + 1, "%s_%s", base, field);
1241 return name;
1244 /* Given an index expression "base" for an element of an array of structures
1245 * and an expression "field" for the field member being accessed, construct
1246 * an index expression for an access to that member of the given structure.
1247 * In particular, take the range product of "base" and "field" and
1248 * attach a name to the result.
1250 static __isl_give isl_multi_pw_aff *member(__isl_take isl_multi_pw_aff *base,
1251 __isl_take isl_multi_pw_aff *field)
1253 isl_ctx *ctx;
1254 isl_multi_pw_aff *access;
1255 const char *base_name, *field_name;
1256 char *name;
1258 ctx = isl_multi_pw_aff_get_ctx(base);
1260 base_name = isl_multi_pw_aff_get_tuple_name(base, isl_dim_out);
1261 field_name = isl_multi_pw_aff_get_tuple_name(field, isl_dim_out);
1262 name = member_access_name(ctx, base_name, field_name);
1264 access = isl_multi_pw_aff_range_product(base, field);
1266 access = isl_multi_pw_aff_set_tuple_name(access, isl_dim_out, name);
1267 free(name);
1269 return access;
1272 /* Extract an index expression from a member expression.
1274 * If the base access (to the structure containing the member)
1275 * is of the form
1277 * [] -> A[..]
1279 * and the member is called "f", then the member access is of
1280 * the form
1282 * [] -> A_f[A[..] -> f[]]
1284 * If the member access is to an anonymous struct, then simply return
1286 * [] -> A[..]
1288 * If the member access in the source code is of the form
1290 * A->f
1292 * then it is treated as
1294 * A[0].f
1296 __isl_give isl_multi_pw_aff *PetScan::extract_index(MemberExpr *expr)
1298 Expr *base = expr->getBase();
1299 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
1300 isl_multi_pw_aff *base_access, *field_access;
1301 isl_id *id;
1302 isl_space *space;
1304 base_access = extract_index(base);
1306 if (expr->isArrow()) {
1307 isl_space *space = isl_space_params_alloc(ctx, 0);
1308 isl_local_space *ls = isl_local_space_from_space(space);
1309 isl_aff *aff = isl_aff_zero_on_domain(ls);
1310 isl_pw_aff *index = isl_pw_aff_from_aff(aff);
1311 base_access = subscript(base_access, index);
1314 if (field->isAnonymousStructOrUnion())
1315 return base_access;
1317 id = isl_id_alloc(ctx, field->getName().str().c_str(), field);
1318 space = isl_multi_pw_aff_get_domain_space(base_access);
1319 space = isl_space_from_domain(space);
1320 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1321 field_access = isl_multi_pw_aff_zero(space);
1323 return member(base_access, field_access);
1326 /* Check if "expr" calls function "minmax" with two arguments and if so
1327 * make lhs and rhs refer to these two arguments.
1329 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1331 CallExpr *call;
1332 FunctionDecl *fd;
1333 string name;
1335 if (expr->getStmtClass() != Stmt::CallExprClass)
1336 return false;
1338 call = cast<CallExpr>(expr);
1339 fd = call->getDirectCallee();
1340 if (!fd)
1341 return false;
1343 if (call->getNumArgs() != 2)
1344 return false;
1346 name = fd->getDeclName().getAsString();
1347 if (name != minmax)
1348 return false;
1350 lhs = call->getArg(0);
1351 rhs = call->getArg(1);
1353 return true;
1356 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1357 * lhs and rhs refer to the two arguments.
1359 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1361 return is_minmax(expr, "min", lhs, rhs);
1364 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1365 * lhs and rhs refer to the two arguments.
1367 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1369 return is_minmax(expr, "max", lhs, rhs);
1372 /* Return "lhs && rhs", with shortcut semantics.
1373 * That is, if lhs is false, then the result is defined even if rhs is not.
1374 * In practice, we compute lhs ? rhs : lhs.
1376 static __isl_give isl_pw_aff *pw_aff_and_then(__isl_take isl_pw_aff *lhs,
1377 __isl_take isl_pw_aff *rhs)
1379 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), rhs, lhs);
1382 /* Return "lhs || rhs", with shortcut semantics.
1383 * That is, if lhs is true, then the result is defined even if rhs is not.
1384 * In practice, we compute lhs ? lhs : rhs.
1386 static __isl_give isl_pw_aff *pw_aff_or_else(__isl_take isl_pw_aff *lhs,
1387 __isl_take isl_pw_aff *rhs)
1389 return isl_pw_aff_cond(isl_pw_aff_copy(lhs), lhs, rhs);
1392 /* Extract an affine expressions representing the comparison "LHS op RHS"
1393 * "comp" is the original statement that "LHS op RHS" is derived from
1394 * and is used for diagnostics.
1396 * If the comparison is of the form
1398 * a <= min(b,c)
1400 * then the expression is constructed as the conjunction of
1401 * the comparisons
1403 * a <= b and a <= c
1405 * A similar optimization is performed for max(a,b) <= c.
1406 * We do this because that will lead to simpler representations
1407 * of the expression.
1408 * If isl is ever enhanced to explicitly deal with min and max expressions,
1409 * this optimization can be removed.
1411 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1412 Expr *LHS, Expr *RHS, Stmt *comp)
1414 isl_pw_aff *lhs;
1415 isl_pw_aff *rhs;
1416 isl_pw_aff *res;
1417 isl_set *cond;
1418 isl_set *dom;
1419 enum pet_op_type type;
1421 if (op == BO_GT)
1422 return extract_comparison(BO_LT, RHS, LHS, comp);
1423 if (op == BO_GE)
1424 return extract_comparison(BO_LE, RHS, LHS, comp);
1426 if (op == BO_LT || op == BO_LE) {
1427 Expr *expr1, *expr2;
1428 if (is_min(RHS, expr1, expr2)) {
1429 lhs = extract_comparison(op, LHS, expr1, comp);
1430 rhs = extract_comparison(op, LHS, expr2, comp);
1431 return pet_and(lhs, rhs);
1433 if (is_max(LHS, expr1, expr2)) {
1434 lhs = extract_comparison(op, expr1, RHS, comp);
1435 rhs = extract_comparison(op, expr2, RHS, comp);
1436 return pet_and(lhs, rhs);
1440 lhs = extract_affine(LHS);
1441 rhs = extract_affine(RHS);
1443 type = BinaryOperatorKind2pet_op_type(op);
1444 return pet_comparison(type, lhs, rhs);
1447 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1449 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1450 comp->getRHS(), comp);
1453 /* Extract an affine expression representing the negation (logical not)
1454 * of a subexpression.
1456 __isl_give isl_pw_aff *PetScan::extract_boolean(UnaryOperator *op)
1458 isl_pw_aff *cond;
1460 cond = extract_condition(op->getSubExpr());
1461 return pet_not(cond);
1464 /* Extract an affine expression representing the disjunction (logical or)
1465 * or conjunction (logical and) of two subexpressions.
1467 __isl_give isl_pw_aff *PetScan::extract_boolean(BinaryOperator *comp)
1469 isl_pw_aff *lhs, *rhs;
1471 lhs = extract_condition(comp->getLHS());
1472 rhs = extract_condition(comp->getRHS());
1474 switch (comp->getOpcode()) {
1475 case BO_LAnd:
1476 return pw_aff_and_then(lhs, rhs);
1477 case BO_LOr:
1478 return pw_aff_or_else(lhs, rhs);
1479 default:
1480 isl_pw_aff_free(lhs);
1481 isl_pw_aff_free(rhs);
1484 unsupported(comp);
1485 return NULL;
1488 __isl_give isl_pw_aff *PetScan::extract_condition(UnaryOperator *expr)
1490 switch (expr->getOpcode()) {
1491 case UO_LNot:
1492 return extract_boolean(expr);
1493 default:
1494 unsupported(expr);
1495 return NULL;
1499 /* Extract the affine expression "expr != 0 ? 1 : 0".
1501 __isl_give isl_pw_aff *PetScan::extract_implicit_condition(Expr *expr)
1503 isl_pw_aff *res;
1505 res = extract_affine(expr);
1506 return pet_to_bool(res);
1509 /* Extract an affine expression from a boolean expression.
1510 * In particular, return the expression "expr ? 1 : 0".
1512 * If the expression doesn't look like a condition, we assume it
1513 * is an affine expression and return the condition "expr != 0 ? 1 : 0".
1515 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1517 BinaryOperator *comp;
1519 if (!expr) {
1520 isl_set *u = isl_set_universe(isl_space_params_alloc(ctx, 0));
1521 return indicator_function(u, isl_set_copy(u));
1524 if (expr->getStmtClass() == Stmt::ParenExprClass)
1525 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
1527 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
1528 return extract_condition(cast<UnaryOperator>(expr));
1530 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
1531 return extract_implicit_condition(expr);
1533 comp = cast<BinaryOperator>(expr);
1534 switch (comp->getOpcode()) {
1535 case BO_LT:
1536 case BO_LE:
1537 case BO_GT:
1538 case BO_GE:
1539 case BO_EQ:
1540 case BO_NE:
1541 return extract_comparison(comp);
1542 case BO_LAnd:
1543 case BO_LOr:
1544 return extract_boolean(comp);
1545 default:
1546 return extract_implicit_condition(expr);
1550 /* Construct a pet_expr representing a unary operator expression.
1552 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1554 pet_expr *arg;
1555 enum pet_op_type op;
1557 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1558 if (op == pet_op_last) {
1559 unsupported(expr);
1560 return NULL;
1563 arg = extract_expr(expr->getSubExpr());
1565 if (expr->isIncrementDecrementOp() &&
1566 pet_expr_get_type(arg) == pet_expr_access) {
1567 arg = mark_write(arg);
1568 arg = pet_expr_access_set_read(arg, 1);
1571 return pet_expr_new_unary(op, arg);
1574 /* Mark the given access pet_expr as a write.
1575 * If a scalar is being accessed, then mark its value
1576 * as unknown in assigned_value.
1578 __isl_give pet_expr *PetScan::mark_write(__isl_take pet_expr *access)
1580 isl_id *id;
1581 ValueDecl *decl;
1583 access = pet_expr_access_set_write(access, 1);
1584 access = pet_expr_access_set_read(access, 0);
1586 if (!access || !pet_expr_is_scalar_access(access))
1587 return access;
1589 id = pet_expr_access_get_id(access);
1590 decl = (ValueDecl *) isl_id_get_user(id);
1591 clear_assignment(assigned_value, decl);
1592 isl_id_free(id);
1594 return access;
1597 /* Assign "rhs" to "lhs".
1599 * In particular, if "lhs" is a scalar variable, then mark
1600 * the variable as having been assigned. If, furthermore, "rhs"
1601 * is an affine expression, then keep track of this value in assigned_value
1602 * so that we can plug it in when we later come across the same variable.
1604 void PetScan::assign(__isl_keep pet_expr *lhs, Expr *rhs)
1606 isl_id *id;
1607 ValueDecl *decl;
1608 isl_pw_aff *pa;
1610 if (!lhs)
1611 return;
1612 if (!pet_expr_is_scalar_access(lhs))
1613 return;
1615 id = pet_expr_access_get_id(lhs);
1616 decl = (ValueDecl *) isl_id_get_user(id);
1617 isl_id_free(id);
1619 pa = try_extract_affine(rhs);
1620 clear_assignment(assigned_value, decl);
1621 if (!pa)
1622 return;
1623 assigned_value[decl] = pa;
1624 insert_expression(pa);
1627 /* Construct a pet_expr representing a binary operator expression.
1629 * If the top level operator is an assignment and the LHS is an access,
1630 * then we mark that access as a write. If the operator is a compound
1631 * assignment, the access is marked as both a read and a write.
1633 * If "expr" assigns something to a scalar variable, then we mark
1634 * the variable as having been assigned. If, furthermore, the expression
1635 * is affine, then keep track of this value in assigned_value
1636 * so that we can plug it in when we later come across the same variable.
1638 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1640 int type_size;
1641 pet_expr *lhs, *rhs;
1642 enum pet_op_type op;
1644 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1645 if (op == pet_op_last) {
1646 unsupported(expr);
1647 return NULL;
1650 lhs = extract_expr(expr->getLHS());
1651 rhs = extract_expr(expr->getRHS());
1653 if (expr->isAssignmentOp() &&
1654 pet_expr_get_type(lhs) == pet_expr_access) {
1655 lhs = mark_write(lhs);
1656 if (expr->isCompoundAssignmentOp())
1657 lhs = pet_expr_access_set_read(lhs, 1);
1660 if (expr->getOpcode() == BO_Assign)
1661 assign(lhs, expr->getRHS());
1663 type_size = get_type_size(expr->getType(), ast_context);
1664 return pet_expr_new_binary(type_size, op, lhs, rhs);
1667 /* Construct a pet_scop with a single statement killing the entire
1668 * array "array".
1670 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1672 isl_id *id;
1673 isl_space *space;
1674 isl_multi_pw_aff *index;
1675 isl_map *access;
1676 pet_expr *expr;
1678 if (!array)
1679 return NULL;
1680 access = isl_map_from_range(isl_set_copy(array->extent));
1681 id = isl_set_get_tuple_id(array->extent);
1682 space = isl_space_alloc(ctx, 0, 0, 0);
1683 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1684 index = isl_multi_pw_aff_zero(space);
1685 expr = pet_expr_kill_from_access_and_index(access, index);
1686 return extract(stmt, expr);
1689 /* Construct a pet_scop for a (single) variable declaration.
1691 * The scop contains the variable being declared (as an array)
1692 * and a statement killing the array.
1694 * If the variable is initialized in the AST, then the scop
1695 * also contains an assignment to the variable.
1697 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1699 int type_size;
1700 Decl *decl;
1701 VarDecl *vd;
1702 pet_expr *lhs, *rhs, *pe;
1703 struct pet_scop *scop_decl, *scop;
1704 struct pet_array *array;
1706 if (!stmt->isSingleDecl()) {
1707 unsupported(stmt);
1708 return NULL;
1711 decl = stmt->getSingleDecl();
1712 vd = cast<VarDecl>(decl);
1714 array = extract_array(ctx, vd, NULL);
1715 if (array)
1716 array->declared = 1;
1717 scop_decl = kill(stmt, array);
1718 scop_decl = pet_scop_add_array(scop_decl, array);
1720 if (!vd->getInit())
1721 return scop_decl;
1723 lhs = extract_access_expr(vd);
1724 rhs = extract_expr(vd->getInit());
1726 lhs = mark_write(lhs);
1727 assign(lhs, vd->getInit());
1729 type_size = get_type_size(vd->getType(), ast_context);
1730 pe = pet_expr_new_binary(type_size, pet_op_assign, lhs, rhs);
1731 scop = extract(stmt, pe);
1733 scop_decl = pet_scop_prefix(scop_decl, 0);
1734 scop = pet_scop_prefix(scop, 1);
1736 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1738 return scop;
1741 /* Construct a pet_expr representing a conditional operation.
1743 * We first try to extract the condition as an affine expression.
1744 * If that fails, we construct a pet_expr tree representing the condition.
1746 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1748 pet_expr *cond, *lhs, *rhs;
1749 isl_pw_aff *pa;
1751 pa = try_extract_affine(expr->getCond());
1752 if (pa) {
1753 isl_multi_pw_aff *test = isl_multi_pw_aff_from_pw_aff(pa);
1754 test = isl_multi_pw_aff_from_range(test);
1755 cond = pet_expr_from_index(test);
1756 } else
1757 cond = extract_expr(expr->getCond());
1758 lhs = extract_expr(expr->getTrueExpr());
1759 rhs = extract_expr(expr->getFalseExpr());
1761 return pet_expr_new_ternary(cond, lhs, rhs);
1764 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1766 return extract_expr(expr->getSubExpr());
1769 /* Construct a pet_expr representing a floating point value.
1771 * If the floating point literal does not appear in a macro,
1772 * then we use the original representation in the source code
1773 * as the string representation. Otherwise, we use the pretty
1774 * printer to produce a string representation.
1776 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1778 double d;
1779 string s;
1780 const LangOptions &LO = PP.getLangOpts();
1781 SourceLocation loc = expr->getLocation();
1783 if (!loc.isMacroID()) {
1784 SourceManager &SM = PP.getSourceManager();
1785 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1786 s = string(SM.getCharacterData(loc), len);
1787 } else {
1788 llvm::raw_string_ostream S(s);
1789 expr->printPretty(S, 0, PrintingPolicy(LO));
1790 S.str();
1792 d = expr->getValueAsApproximateDouble();
1793 return pet_expr_new_double(ctx, d, s.c_str());
1796 /* Convert the index expression "index" into an access pet_expr of type "qt".
1798 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
1799 __isl_take isl_multi_pw_aff *index)
1801 pet_expr *pe;
1802 int depth;
1803 int type_size;
1805 depth = extract_depth(index);
1806 type_size = get_type_size(qt, ast_context);
1808 pe = pet_expr_from_index_and_depth(type_size, index, depth);
1810 return pe;
1813 /* Extract an index expression from "expr" and then convert it into
1814 * an access pet_expr.
1816 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
1818 return extract_access_expr(expr->getType(), extract_index(expr));
1821 /* Extract an index expression from "decl" and then convert it into
1822 * an access pet_expr.
1824 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1826 return extract_access_expr(decl->getType(), extract_index(decl));
1829 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
1831 return extract_expr(expr->getSubExpr());
1834 /* Extract an assume statement from the argument "expr"
1835 * of a __pencil_assume statement.
1837 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
1839 isl_pw_aff *cond;
1840 pet_expr *res;
1842 cond = try_extract_affine_condition(expr);
1843 if (!cond) {
1844 res = extract_expr(expr);
1845 } else {
1846 isl_multi_pw_aff *index;
1847 index = isl_multi_pw_aff_from_pw_aff(cond);
1848 index = isl_multi_pw_aff_from_range(index);
1849 res = pet_expr_from_index(index);
1851 return pet_expr_new_unary(pet_op_assume, res);
1854 /* Construct a pet_expr corresponding to the function call argument "expr".
1855 * The argument appears in position "pos" of a call to function "fd".
1857 * If we are passing along a pointer to an array element
1858 * or an entire row or even higher dimensional slice of an array,
1859 * then the function being called may write into the array.
1861 * We assume here that if the function is declared to take a pointer
1862 * to a const type, then the function will perform a read
1863 * and that otherwise, it will perform a write.
1865 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
1866 Expr *expr)
1868 pet_expr *res;
1869 int is_addr = 0, is_partial = 0;
1870 Stmt::StmtClass sc;
1872 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
1873 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
1874 expr = ice->getSubExpr();
1876 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
1877 UnaryOperator *op = cast<UnaryOperator>(expr);
1878 if (op->getOpcode() == UO_AddrOf) {
1879 is_addr = 1;
1880 expr = op->getSubExpr();
1883 res = extract_expr(expr);
1884 if (!res)
1885 return NULL;
1886 sc = expr->getStmtClass();
1887 if ((sc == Stmt::ArraySubscriptExprClass ||
1888 sc == Stmt::MemberExprClass) &&
1889 array_depth(expr->getType().getTypePtr()) > 0)
1890 is_partial = 1;
1891 if ((is_addr || is_partial) &&
1892 pet_expr_get_type(res) == pet_expr_access) {
1893 ParmVarDecl *parm;
1894 if (!fd->hasPrototype()) {
1895 report_prototype_required(expr);
1896 return pet_expr_free(res);
1898 parm = fd->getParamDecl(pos);
1899 if (!const_base(parm->getType()))
1900 res = mark_write(res);
1903 if (is_addr)
1904 res = pet_expr_new_unary(pet_op_address_of, res);
1905 return res;
1908 /* Construct a pet_expr representing a function call.
1910 * In the special case of a "call" to __pencil_assume,
1911 * construct an assume expression instead.
1913 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1915 pet_expr *res = NULL;
1916 FunctionDecl *fd;
1917 string name;
1918 unsigned n_arg;
1920 fd = expr->getDirectCallee();
1921 if (!fd) {
1922 unsupported(expr);
1923 return NULL;
1926 name = fd->getDeclName().getAsString();
1927 n_arg = expr->getNumArgs();
1929 if (n_arg == 1 && name == "__pencil_assume")
1930 return extract_assume(expr->getArg(0));
1932 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1933 if (!res)
1934 return NULL;
1936 for (int i = 0; i < n_arg; ++i) {
1937 Expr *arg = expr->getArg(i);
1938 res = pet_expr_set_arg(res, i,
1939 PetScan::extract_argument(fd, i, arg));
1942 return res;
1945 /* Construct a pet_expr representing a (C style) cast.
1947 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1949 pet_expr *arg;
1950 QualType type;
1952 arg = extract_expr(expr->getSubExpr());
1953 if (!arg)
1954 return NULL;
1956 type = expr->getTypeAsWritten();
1957 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1960 /* Construct a pet_expr representing an integer.
1962 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1964 return pet_expr_new_int(extract_int(expr));
1967 /* Try and construct a pet_expr representing "expr".
1969 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1971 switch (expr->getStmtClass()) {
1972 case Stmt::UnaryOperatorClass:
1973 return extract_expr(cast<UnaryOperator>(expr));
1974 case Stmt::CompoundAssignOperatorClass:
1975 case Stmt::BinaryOperatorClass:
1976 return extract_expr(cast<BinaryOperator>(expr));
1977 case Stmt::ImplicitCastExprClass:
1978 return extract_expr(cast<ImplicitCastExpr>(expr));
1979 case Stmt::ArraySubscriptExprClass:
1980 case Stmt::DeclRefExprClass:
1981 case Stmt::MemberExprClass:
1982 return extract_access_expr(expr);
1983 case Stmt::IntegerLiteralClass:
1984 return extract_expr(cast<IntegerLiteral>(expr));
1985 case Stmt::FloatingLiteralClass:
1986 return extract_expr(cast<FloatingLiteral>(expr));
1987 case Stmt::ParenExprClass:
1988 return extract_expr(cast<ParenExpr>(expr));
1989 case Stmt::ConditionalOperatorClass:
1990 return extract_expr(cast<ConditionalOperator>(expr));
1991 case Stmt::CallExprClass:
1992 return extract_expr(cast<CallExpr>(expr));
1993 case Stmt::CStyleCastExprClass:
1994 return extract_expr(cast<CStyleCastExpr>(expr));
1995 default:
1996 unsupported(expr);
1998 return NULL;
2001 /* Check if the given initialization statement is an assignment.
2002 * If so, return that assignment. Otherwise return NULL.
2004 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
2006 BinaryOperator *ass;
2008 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
2009 return NULL;
2011 ass = cast<BinaryOperator>(init);
2012 if (ass->getOpcode() != BO_Assign)
2013 return NULL;
2015 return ass;
2018 /* Check if the given initialization statement is a declaration
2019 * of a single variable.
2020 * If so, return that declaration. Otherwise return NULL.
2022 Decl *PetScan::initialization_declaration(Stmt *init)
2024 DeclStmt *decl;
2026 if (init->getStmtClass() != Stmt::DeclStmtClass)
2027 return NULL;
2029 decl = cast<DeclStmt>(init);
2031 if (!decl->isSingleDecl())
2032 return NULL;
2034 return decl->getSingleDecl();
2037 /* Given the assignment operator in the initialization of a for loop,
2038 * extract the induction variable, i.e., the (integer)variable being
2039 * assigned.
2041 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
2043 Expr *lhs;
2044 DeclRefExpr *ref;
2045 ValueDecl *decl;
2046 const Type *type;
2048 lhs = init->getLHS();
2049 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2050 unsupported(init);
2051 return NULL;
2054 ref = cast<DeclRefExpr>(lhs);
2055 decl = ref->getDecl();
2056 type = decl->getType().getTypePtr();
2058 if (!type->isIntegerType()) {
2059 unsupported(lhs);
2060 return NULL;
2063 return decl;
2066 /* Given the initialization statement of a for loop and the single
2067 * declaration in this initialization statement,
2068 * extract the induction variable, i.e., the (integer) variable being
2069 * declared.
2071 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
2073 VarDecl *vd;
2075 vd = cast<VarDecl>(decl);
2077 const QualType type = vd->getType();
2078 if (!type->isIntegerType()) {
2079 unsupported(init);
2080 return NULL;
2083 if (!vd->getInit()) {
2084 unsupported(init);
2085 return NULL;
2088 return vd;
2091 /* Check that op is of the form iv++ or iv--.
2092 * Return an affine expression "1" or "-1" accordingly.
2094 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
2095 clang::UnaryOperator *op, clang::ValueDecl *iv)
2097 Expr *sub;
2098 DeclRefExpr *ref;
2099 isl_space *space;
2100 isl_aff *aff;
2102 if (!op->isIncrementDecrementOp()) {
2103 unsupported(op);
2104 return NULL;
2107 sub = op->getSubExpr();
2108 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
2109 unsupported(op);
2110 return NULL;
2113 ref = cast<DeclRefExpr>(sub);
2114 if (ref->getDecl() != iv) {
2115 unsupported(op);
2116 return NULL;
2119 space = isl_space_params_alloc(ctx, 0);
2120 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2122 if (op->isIncrementOp())
2123 aff = isl_aff_add_constant_si(aff, 1);
2124 else
2125 aff = isl_aff_add_constant_si(aff, -1);
2127 return isl_pw_aff_from_aff(aff);
2130 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
2131 * has a single constant expression, then put this constant in *user.
2132 * The caller is assumed to have checked that this function will
2133 * be called exactly once.
2135 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
2136 void *user)
2138 isl_val **inc = (isl_val **)user;
2139 int res = 0;
2141 if (isl_aff_is_cst(aff))
2142 *inc = isl_aff_get_constant_val(aff);
2143 else
2144 res = -1;
2146 isl_set_free(set);
2147 isl_aff_free(aff);
2149 return res;
2152 /* Check if op is of the form
2154 * iv = iv + inc
2156 * and return inc as an affine expression.
2158 * We extract an affine expression from the RHS, subtract iv and return
2159 * the result.
2161 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
2162 clang::ValueDecl *iv)
2164 Expr *lhs;
2165 DeclRefExpr *ref;
2166 isl_id *id;
2167 isl_space *dim;
2168 isl_aff *aff;
2169 isl_pw_aff *val;
2171 if (op->getOpcode() != BO_Assign) {
2172 unsupported(op);
2173 return NULL;
2176 lhs = op->getLHS();
2177 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2178 unsupported(op);
2179 return NULL;
2182 ref = cast<DeclRefExpr>(lhs);
2183 if (ref->getDecl() != iv) {
2184 unsupported(op);
2185 return NULL;
2188 val = extract_affine(op->getRHS());
2190 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
2192 dim = isl_space_params_alloc(ctx, 1);
2193 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2194 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2195 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2197 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
2199 return val;
2202 /* Check that op is of the form iv += cst or iv -= cst
2203 * and return an affine expression corresponding oto cst or -cst accordingly.
2205 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
2206 CompoundAssignOperator *op, clang::ValueDecl *iv)
2208 Expr *lhs;
2209 DeclRefExpr *ref;
2210 bool neg = false;
2211 isl_pw_aff *val;
2212 BinaryOperatorKind opcode;
2214 opcode = op->getOpcode();
2215 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
2216 unsupported(op);
2217 return NULL;
2219 if (opcode == BO_SubAssign)
2220 neg = true;
2222 lhs = op->getLHS();
2223 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2224 unsupported(op);
2225 return NULL;
2228 ref = cast<DeclRefExpr>(lhs);
2229 if (ref->getDecl() != iv) {
2230 unsupported(op);
2231 return NULL;
2234 val = extract_affine(op->getRHS());
2235 if (neg)
2236 val = isl_pw_aff_neg(val);
2238 return val;
2241 /* Check that the increment of the given for loop increments
2242 * (or decrements) the induction variable "iv" and return
2243 * the increment as an affine expression if successful.
2245 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
2246 ValueDecl *iv)
2248 Stmt *inc = stmt->getInc();
2250 if (!inc) {
2251 report_missing_increment(stmt);
2252 return NULL;
2255 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
2256 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
2257 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
2258 return extract_compound_increment(
2259 cast<CompoundAssignOperator>(inc), iv);
2260 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
2261 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
2263 unsupported(inc);
2264 return NULL;
2267 /* Embed the given iteration domain in an extra outer loop
2268 * with induction variable "var".
2269 * If this variable appeared as a parameter in the constraints,
2270 * it is replaced by the new outermost dimension.
2272 static __isl_give isl_set *embed(__isl_take isl_set *set,
2273 __isl_take isl_id *var)
2275 int pos;
2277 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
2278 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
2279 if (pos >= 0) {
2280 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
2281 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2284 isl_id_free(var);
2285 return set;
2288 /* Return those elements in the space of "cond" that come after
2289 * (based on "sign") an element in "cond".
2291 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
2293 isl_map *previous_to_this;
2295 if (sign > 0)
2296 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
2297 else
2298 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
2300 cond = isl_set_apply(cond, previous_to_this);
2302 return cond;
2305 /* Create the infinite iteration domain
2307 * { [id] : id >= 0 }
2309 * If "scop" has an affine skip of type pet_skip_later,
2310 * then remove those iterations i that have an earlier iteration
2311 * where the skip condition is satisfied, meaning that iteration i
2312 * is not executed.
2313 * Since we are dealing with a loop without loop iterator,
2314 * the skip condition cannot refer to the current loop iterator and
2315 * so effectively, the returned set is of the form
2317 * { [0]; [id] : id >= 1 and not skip }
2319 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
2320 struct pet_scop *scop)
2322 isl_ctx *ctx = isl_id_get_ctx(id);
2323 isl_set *domain;
2324 isl_set *skip;
2326 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
2327 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
2329 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
2330 return domain;
2332 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2333 skip = embed(skip, isl_id_copy(id));
2334 skip = isl_set_intersect(skip , isl_set_copy(domain));
2335 domain = isl_set_subtract(domain, after(skip, 1));
2337 return domain;
2340 /* Create an identity affine expression on the space containing "domain",
2341 * which is assumed to be one-dimensional.
2343 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
2345 isl_local_space *ls;
2347 ls = isl_local_space_from_space(isl_set_get_space(domain));
2348 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
2351 /* Create an affine expression that maps elements
2352 * of a single-dimensional array "id_test" to the previous element
2353 * (according to "inc"), provided this element belongs to "domain".
2354 * That is, create the affine expression
2356 * { id[x] -> id[x - inc] : x - inc in domain }
2358 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
2359 __isl_take isl_set *domain, __isl_take isl_val *inc)
2361 isl_space *space;
2362 isl_local_space *ls;
2363 isl_aff *aff;
2364 isl_multi_pw_aff *prev;
2366 space = isl_set_get_space(domain);
2367 ls = isl_local_space_from_space(space);
2368 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2369 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
2370 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
2371 domain = isl_set_preimage_multi_pw_aff(domain,
2372 isl_multi_pw_aff_copy(prev));
2373 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
2374 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
2376 return prev;
2379 /* Add an implication to "scop" expressing that if an element of
2380 * virtual array "id_test" has value "satisfied" then all previous elements
2381 * of this array also have that value. The set of previous elements
2382 * is bounded by "domain". If "sign" is negative then the iterator
2383 * is decreasing and we express that all subsequent array elements
2384 * (but still defined previously) have the same value.
2386 static struct pet_scop *add_implication(struct pet_scop *scop,
2387 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
2388 int satisfied)
2390 isl_space *space;
2391 isl_map *map;
2393 domain = isl_set_set_tuple_id(domain, id_test);
2394 space = isl_set_get_space(domain);
2395 if (sign > 0)
2396 map = isl_map_lex_ge(space);
2397 else
2398 map = isl_map_lex_le(space);
2399 map = isl_map_intersect_range(map, domain);
2400 scop = pet_scop_add_implication(scop, map, satisfied);
2402 return scop;
2405 /* Add a filter to "scop" that imposes that it is only executed
2406 * when the variable identified by "id_test" has a zero value
2407 * for all previous iterations of "domain".
2409 * In particular, add a filter that imposes that the array
2410 * has a zero value at the previous iteration of domain and
2411 * add an implication that implies that it then has that
2412 * value for all previous iterations.
2414 static struct pet_scop *scop_add_break(struct pet_scop *scop,
2415 __isl_take isl_id *id_test, __isl_take isl_set *domain,
2416 __isl_take isl_val *inc)
2418 isl_multi_pw_aff *prev;
2419 int sign = isl_val_sgn(inc);
2421 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2422 scop = add_implication(scop, id_test, domain, sign, 0);
2423 scop = pet_scop_filter(scop, prev, 0);
2425 return scop;
2428 /* Construct a pet_scop for an infinite loop around the given body.
2430 * We extract a pet_scop for the body and then embed it in a loop with
2431 * iteration domain
2433 * { [t] : t >= 0 }
2435 * and schedule
2437 * { [t] -> [t] }
2439 * If the body contains any break, then it is taken into
2440 * account in infinite_domain (if the skip condition is affine)
2441 * or in scop_add_break (if the skip condition is not affine).
2443 * If we were only able to extract part of the body, then simply
2444 * return that part.
2446 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2448 isl_id *id, *id_test;
2449 isl_set *domain;
2450 isl_aff *ident;
2451 struct pet_scop *scop;
2452 bool has_var_break;
2454 scop = extract(body);
2455 if (!scop)
2456 return NULL;
2457 if (partial)
2458 return scop;
2460 id = isl_id_alloc(ctx, "t", NULL);
2461 domain = infinite_domain(isl_id_copy(id), scop);
2462 ident = identity_aff(domain);
2464 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2465 if (has_var_break)
2466 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
2468 scop = pet_scop_embed(scop, isl_set_copy(domain),
2469 isl_aff_copy(ident), ident, id);
2470 if (has_var_break)
2471 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
2472 else
2473 isl_set_free(domain);
2475 return scop;
2478 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2480 * for (;;)
2481 * body
2484 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2486 clear_assignments clear(assigned_value);
2487 clear.TraverseStmt(stmt->getBody());
2489 return extract_infinite_loop(stmt->getBody());
2492 /* Add an array with the given extent (range of "index") to the list
2493 * of arrays in "scop" and return the extended pet_scop.
2494 * The array is marked as attaining values 0 and 1 only and
2495 * as each element being assigned at most once.
2497 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2498 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
2500 int int_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2502 return pet_scop_add_boolean_array(scop, isl_multi_pw_aff_copy(index),
2503 int_size);
2506 /* Construct a pet_scop for a while loop of the form
2508 * while (pa)
2509 * body
2511 * In particular, construct a scop for an infinite loop around body and
2512 * intersect the domain with the affine expression.
2513 * Note that this intersection may result in an empty loop.
2515 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2516 Stmt *body)
2518 struct pet_scop *scop;
2519 isl_set *dom;
2520 isl_set *valid;
2522 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2523 dom = isl_pw_aff_non_zero_set(pa);
2524 scop = extract_infinite_loop(body);
2525 scop = pet_scop_restrict(scop, dom);
2526 scop = pet_scop_restrict_context(scop, valid);
2528 return scop;
2531 /* Construct a scop for a while, given the scops for the condition
2532 * and the body, the filter identifier and the iteration domain of
2533 * the while loop.
2535 * In particular, the scop for the condition is filtered to depend
2536 * on "id_test" evaluating to true for all previous iterations
2537 * of the loop, while the scop for the body is filtered to depend
2538 * on "id_test" evaluating to true for all iterations up to the
2539 * current iteration.
2540 * The actual filter only imposes that this virtual array has
2541 * value one on the previous or the current iteration.
2542 * The fact that this condition also applies to the previous
2543 * iterations is enforced by an implication.
2545 * These filtered scops are then combined into a single scop.
2547 * "sign" is positive if the iterator increases and negative
2548 * if it decreases.
2550 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2551 struct pet_scop *scop_body, __isl_take isl_id *id_test,
2552 __isl_take isl_set *domain, __isl_take isl_val *inc)
2554 isl_ctx *ctx = isl_set_get_ctx(domain);
2555 isl_space *space;
2556 isl_multi_pw_aff *test_index;
2557 isl_multi_pw_aff *prev;
2558 int sign = isl_val_sgn(inc);
2559 struct pet_scop *scop;
2561 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2562 scop_cond = pet_scop_filter(scop_cond, prev, 1);
2564 space = isl_space_map_from_set(isl_set_get_space(domain));
2565 test_index = isl_multi_pw_aff_identity(space);
2566 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
2567 isl_id_copy(id_test));
2568 scop_body = pet_scop_filter(scop_body, test_index, 1);
2570 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
2571 scop = add_implication(scop, id_test, domain, sign, 1);
2573 return scop;
2576 /* Check if the while loop is of the form
2578 * while (affine expression)
2579 * body
2581 * If so, call extract_affine_while to construct a scop.
2583 * Otherwise, construct a generic while scop, with iteration domain
2584 * { [t] : t >= 0 }. The scop consists of two parts, one for
2585 * evaluating the condition and one for the body.
2586 * The schedule is adjusted to reflect that the condition is evaluated
2587 * before the body is executed and the body is filtered to depend
2588 * on the result of the condition evaluating to true on all iterations
2589 * up to the current iteration, while the evaluation of the condition itself
2590 * is filtered to depend on the result of the condition evaluating to true
2591 * on all previous iterations.
2592 * The context of the scop representing the body is dropped
2593 * because we don't know how many times the body will be executed,
2594 * if at all.
2596 * If the body contains any break, then it is taken into
2597 * account in infinite_domain (if the skip condition is affine)
2598 * or in scop_add_break (if the skip condition is not affine).
2600 * If we were only able to extract part of the body, then simply
2601 * return that part.
2603 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2605 Expr *cond;
2606 int test_nr, stmt_nr;
2607 isl_id *id, *id_test, *id_break_test;
2608 isl_multi_pw_aff *test_index;
2609 isl_set *domain;
2610 isl_aff *ident;
2611 isl_pw_aff *pa;
2612 struct pet_scop *scop, *scop_body;
2613 bool has_var_break;
2615 cond = stmt->getCond();
2616 if (!cond) {
2617 unsupported(stmt);
2618 return NULL;
2621 clear_assignments clear(assigned_value);
2622 clear.TraverseStmt(stmt->getBody());
2624 pa = try_extract_affine_condition(cond);
2625 if (pa)
2626 return extract_affine_while(pa, stmt->getBody());
2628 if (!allow_nested) {
2629 unsupported(stmt);
2630 return NULL;
2633 test_nr = n_test++;
2634 stmt_nr = n_stmt++;
2635 scop_body = extract(stmt->getBody());
2636 if (partial)
2637 return scop_body;
2639 test_index = pet_create_test_index(ctx, test_nr);
2640 scop = extract_non_affine_condition(cond, stmt_nr,
2641 isl_multi_pw_aff_copy(test_index));
2642 scop = scop_add_array(scop, test_index, ast_context);
2643 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2644 isl_multi_pw_aff_free(test_index);
2646 id = isl_id_alloc(ctx, "t", NULL);
2647 domain = infinite_domain(isl_id_copy(id), scop_body);
2648 ident = identity_aff(domain);
2650 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2651 if (has_var_break)
2652 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2654 scop = pet_scop_prefix(scop, 0);
2655 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_aff_copy(ident),
2656 isl_aff_copy(ident), isl_id_copy(id));
2657 scop_body = pet_scop_reset_context(scop_body);
2658 scop_body = pet_scop_prefix(scop_body, 1);
2659 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2660 isl_aff_copy(ident), ident, id);
2662 if (has_var_break) {
2663 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2664 isl_set_copy(domain), isl_val_one(ctx));
2665 scop_body = scop_add_break(scop_body, id_break_test,
2666 isl_set_copy(domain), isl_val_one(ctx));
2668 scop = scop_add_while(scop, scop_body, id_test, domain,
2669 isl_val_one(ctx));
2671 return scop;
2674 /* Check whether "cond" expresses a simple loop bound
2675 * on the only set dimension.
2676 * In particular, if "up" is set then "cond" should contain only
2677 * upper bounds on the set dimension.
2678 * Otherwise, it should contain only lower bounds.
2680 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2682 if (isl_val_is_pos(inc))
2683 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2684 else
2685 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2688 /* Extend a condition on a given iteration of a loop to one that
2689 * imposes the same condition on all previous iterations.
2690 * "domain" expresses the lower [upper] bound on the iterations
2691 * when inc is positive [negative].
2693 * In particular, we construct the condition (when inc is positive)
2695 * forall i' : (domain(i') and i' <= i) => cond(i')
2697 * which is equivalent to
2699 * not exists i' : domain(i') and i' <= i and not cond(i')
2701 * We construct this set by negating cond, applying a map
2703 * { [i'] -> [i] : domain(i') and i' <= i }
2705 * and then negating the result again.
2707 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2708 __isl_take isl_set *domain, __isl_take isl_val *inc)
2710 isl_map *previous_to_this;
2712 if (isl_val_is_pos(inc))
2713 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2714 else
2715 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2717 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2719 cond = isl_set_complement(cond);
2720 cond = isl_set_apply(cond, previous_to_this);
2721 cond = isl_set_complement(cond);
2723 isl_val_free(inc);
2725 return cond;
2728 /* Construct a domain of the form
2730 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2732 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2733 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2735 isl_aff *aff;
2736 isl_space *dim;
2737 isl_set *set;
2739 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2740 dim = isl_pw_aff_get_domain_space(init);
2741 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2742 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2743 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2745 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2746 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2747 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2748 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2750 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2752 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2754 return isl_set_params(set);
2757 /* Assuming "cond" represents a bound on a loop where the loop
2758 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2759 * is possible.
2761 * Under the given assumptions, wrapping is only possible if "cond" allows
2762 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2763 * increasing iterator and 0 in case of a decreasing iterator.
2765 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2766 __isl_keep isl_val *inc)
2768 bool cw;
2769 isl_ctx *ctx;
2770 isl_val *limit;
2771 isl_set *test;
2773 test = isl_set_copy(cond);
2775 ctx = isl_set_get_ctx(test);
2776 if (isl_val_is_neg(inc))
2777 limit = isl_val_zero(ctx);
2778 else {
2779 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2780 limit = isl_val_2exp(limit);
2781 limit = isl_val_sub_ui(limit, 1);
2784 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2785 cw = !isl_set_is_empty(test);
2786 isl_set_free(test);
2788 return cw;
2791 /* Given a one-dimensional space, construct the following affine expression
2792 * on this space
2794 * { [v] -> [v mod 2^width] }
2796 * where width is the number of bits used to represent the values
2797 * of the unsigned variable "iv".
2799 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2800 ValueDecl *iv)
2802 isl_ctx *ctx;
2803 isl_val *mod;
2804 isl_aff *aff;
2806 ctx = isl_space_get_ctx(dim);
2807 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2808 mod = isl_val_2exp(mod);
2810 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2811 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2812 aff = isl_aff_mod_val(aff, mod);
2814 return aff;
2817 /* Project out the parameter "id" from "set".
2819 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2820 __isl_keep isl_id *id)
2822 int pos;
2824 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2825 if (pos >= 0)
2826 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2828 return set;
2831 /* Compute the set of parameters for which "set1" is a subset of "set2".
2833 * set1 is a subset of set2 if
2835 * forall i in set1 : i in set2
2837 * or
2839 * not exists i in set1 and i not in set2
2841 * i.e.,
2843 * not exists i in set1 \ set2
2845 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2846 __isl_take isl_set *set2)
2848 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2851 /* Compute the set of parameter values for which "cond" holds
2852 * on the next iteration for each element of "dom".
2854 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2855 * and then compute the set of parameters for which the result is a subset
2856 * of "cond".
2858 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2859 __isl_take isl_set *dom, __isl_take isl_val *inc)
2861 isl_space *space;
2862 isl_aff *aff;
2863 isl_map *next;
2865 space = isl_set_get_space(dom);
2866 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2867 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2868 aff = isl_aff_add_constant_val(aff, inc);
2869 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2871 dom = isl_set_apply(dom, next);
2873 return enforce_subset(dom, cond);
2876 /* Construct a pet_scop for a for statement.
2877 * The for loop is required to be of the form
2879 * for (i = init; condition; ++i)
2881 * or
2883 * for (i = init; condition; --i)
2885 * The initialization of the for loop should either be an assignment
2886 * to an integer variable, or a declaration of such a variable with
2887 * initialization.
2889 * The condition is allowed to contain nested accesses, provided
2890 * they are not being written to inside the body of the loop.
2891 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2892 * essentially treated as a while loop, with iteration domain
2893 * { [i] : i >= init }.
2895 * We extract a pet_scop for the body and then embed it in a loop with
2896 * iteration domain and schedule
2898 * { [i] : i >= init and condition' }
2899 * { [i] -> [i] }
2901 * or
2903 * { [i] : i <= init and condition' }
2904 * { [i] -> [-i] }
2906 * Where condition' is equal to condition if the latter is
2907 * a simple upper [lower] bound and a condition that is extended
2908 * to apply to all previous iterations otherwise.
2910 * If the condition is non-affine, then we drop the condition from the
2911 * iteration domain and instead create a separate statement
2912 * for evaluating the condition. The body is then filtered to depend
2913 * on the result of the condition evaluating to true on all iterations
2914 * up to the current iteration, while the evaluation the condition itself
2915 * is filtered to depend on the result of the condition evaluating to true
2916 * on all previous iterations.
2917 * The context of the scop representing the body is dropped
2918 * because we don't know how many times the body will be executed,
2919 * if at all.
2921 * If the stride of the loop is not 1, then "i >= init" is replaced by
2923 * (exists a: i = init + stride * a and a >= 0)
2925 * If the loop iterator i is unsigned, then wrapping may occur.
2926 * We therefore use a virtual iterator instead that does not wrap.
2927 * However, the condition in the code applies
2928 * to the wrapped value, so we need to change condition(i)
2929 * into condition([i % 2^width]). Similarly, we replace all accesses
2930 * to the original iterator by the wrapping of the virtual iterator.
2931 * Note that there may be no need to perform this final wrapping
2932 * if the loop condition (after wrapping) satisfies certain conditions.
2933 * However, the is_simple_bound condition is not enough since it doesn't
2934 * check if there even is an upper bound.
2936 * Wrapping on unsigned iterators can be avoided entirely if
2937 * loop condition is simple, the loop iterator is incremented
2938 * [decremented] by one and the last value before wrapping cannot
2939 * possibly satisfy the loop condition.
2941 * Before extracting a pet_scop from the body we remove all
2942 * assignments in assigned_value to variables that are assigned
2943 * somewhere in the body of the loop.
2945 * Valid parameters for a for loop are those for which the initial
2946 * value itself, the increment on each domain iteration and
2947 * the condition on both the initial value and
2948 * the result of incrementing the iterator for each iteration of the domain
2949 * can be evaluated.
2950 * If the loop condition is non-affine, then we only consider validity
2951 * of the initial value.
2953 * If the body contains any break, then we keep track of it in "skip"
2954 * (if the skip condition is affine) or it is handled in scop_add_break
2955 * (if the skip condition is not affine).
2956 * Note that the affine break condition needs to be considered with
2957 * respect to previous iterations in the virtual domain (if any).
2959 * If we were only able to extract part of the body, then simply
2960 * return that part.
2962 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2964 BinaryOperator *ass;
2965 Decl *decl;
2966 Stmt *init;
2967 Expr *lhs, *rhs;
2968 ValueDecl *iv;
2969 isl_local_space *ls;
2970 isl_set *domain;
2971 isl_aff *sched;
2972 isl_set *cond = NULL;
2973 isl_set *skip = NULL;
2974 isl_id *id, *id_test = NULL, *id_break_test;
2975 struct pet_scop *scop, *scop_cond = NULL;
2976 assigned_value_cache cache(assigned_value);
2977 isl_val *inc;
2978 bool was_assigned;
2979 bool is_one;
2980 bool is_unsigned;
2981 bool is_simple;
2982 bool is_virtual;
2983 bool has_affine_break;
2984 bool has_var_break;
2985 isl_aff *wrap = NULL;
2986 isl_pw_aff *pa, *pa_inc, *init_val;
2987 isl_set *valid_init;
2988 isl_set *valid_cond;
2989 isl_set *valid_cond_init;
2990 isl_set *valid_cond_next;
2991 isl_set *valid_inc;
2992 int stmt_id;
2994 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2995 return extract_infinite_for(stmt);
2997 init = stmt->getInit();
2998 if (!init) {
2999 unsupported(stmt);
3000 return NULL;
3002 if ((ass = initialization_assignment(init)) != NULL) {
3003 iv = extract_induction_variable(ass);
3004 if (!iv)
3005 return NULL;
3006 lhs = ass->getLHS();
3007 rhs = ass->getRHS();
3008 } else if ((decl = initialization_declaration(init)) != NULL) {
3009 VarDecl *var = extract_induction_variable(init, decl);
3010 if (!var)
3011 return NULL;
3012 iv = var;
3013 rhs = var->getInit();
3014 lhs = create_DeclRefExpr(var);
3015 } else {
3016 unsupported(stmt->getInit());
3017 return NULL;
3020 assigned_value.erase(iv);
3021 clear_assignments clear(assigned_value);
3022 clear.TraverseStmt(stmt->getBody());
3024 was_assigned = assigned_value.find(iv) != assigned_value.end();
3025 clear_assignment(assigned_value, iv);
3026 init_val = extract_affine(rhs);
3027 if (!was_assigned)
3028 assigned_value.erase(iv);
3029 if (!init_val)
3030 return NULL;
3032 pa_inc = extract_increment(stmt, iv);
3033 if (!pa_inc) {
3034 isl_pw_aff_free(init_val);
3035 return NULL;
3038 inc = NULL;
3039 if (isl_pw_aff_n_piece(pa_inc) != 1 ||
3040 isl_pw_aff_foreach_piece(pa_inc, &extract_cst, &inc) < 0) {
3041 isl_pw_aff_free(init_val);
3042 isl_pw_aff_free(pa_inc);
3043 unsupported(stmt->getInc());
3044 isl_val_free(inc);
3045 return NULL;
3048 pa = try_extract_nested_condition(stmt->getCond());
3049 if (allow_nested && (!pa || pet_nested_any_in_pw_aff(pa)))
3050 stmt_id = n_stmt++;
3052 scop = extract(stmt->getBody());
3053 if (partial) {
3054 isl_pw_aff_free(init_val);
3055 isl_pw_aff_free(pa_inc);
3056 isl_pw_aff_free(pa);
3057 isl_val_free(inc);
3058 return scop;
3061 valid_inc = isl_pw_aff_domain(pa_inc);
3063 is_unsigned = iv->getType()->isUnsignedIntegerType();
3065 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
3067 has_affine_break = scop &&
3068 pet_scop_has_affine_skip(scop, pet_skip_later);
3069 if (has_affine_break)
3070 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
3071 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
3072 if (has_var_break)
3073 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
3075 if (pa && !is_nested_allowed(pa, scop)) {
3076 isl_pw_aff_free(pa);
3077 pa = NULL;
3080 if (!allow_nested && !pa)
3081 pa = try_extract_affine_condition(stmt->getCond());
3082 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3083 cond = isl_pw_aff_non_zero_set(pa);
3084 if (allow_nested && !cond) {
3085 isl_multi_pw_aff *test_index;
3086 int save_n_stmt = n_stmt;
3087 test_index = pet_create_test_index(ctx, n_test++);
3088 n_stmt = stmt_id;
3089 scop_cond = extract_non_affine_condition(stmt->getCond(),
3090 n_stmt++, isl_multi_pw_aff_copy(test_index));
3091 n_stmt = save_n_stmt;
3092 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
3093 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
3094 isl_dim_out);
3095 isl_multi_pw_aff_free(test_index);
3096 scop_cond = pet_scop_prefix(scop_cond, 0);
3097 scop = pet_scop_reset_context(scop);
3098 scop = pet_scop_prefix(scop, 1);
3099 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
3102 cond = embed(cond, isl_id_copy(id));
3103 skip = embed(skip, isl_id_copy(id));
3104 valid_cond = isl_set_coalesce(valid_cond);
3105 valid_cond = embed(valid_cond, isl_id_copy(id));
3106 valid_inc = embed(valid_inc, isl_id_copy(id));
3107 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
3108 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
3110 valid_cond_init = enforce_subset(
3111 isl_set_from_pw_aff(isl_pw_aff_copy(init_val)),
3112 isl_set_copy(valid_cond));
3113 if (is_one && !is_virtual) {
3114 isl_pw_aff_free(init_val);
3115 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
3116 lhs, rhs, init);
3117 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3118 valid_init = set_project_out_by_id(valid_init, id);
3119 domain = isl_pw_aff_non_zero_set(pa);
3120 } else {
3121 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
3122 domain = strided_domain(isl_id_copy(id), init_val,
3123 isl_val_copy(inc));
3126 domain = embed(domain, isl_id_copy(id));
3127 if (is_virtual) {
3128 isl_map *rev_wrap;
3129 wrap = compute_wrapping(isl_set_get_space(cond), iv);
3130 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
3131 rev_wrap = isl_map_reverse(rev_wrap);
3132 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
3133 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
3134 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
3135 valid_inc = isl_set_apply(valid_inc, rev_wrap);
3137 is_simple = is_simple_bound(cond, inc);
3138 if (!is_simple) {
3139 cond = isl_set_gist(cond, isl_set_copy(domain));
3140 is_simple = is_simple_bound(cond, inc);
3142 if (!is_simple)
3143 cond = valid_for_each_iteration(cond,
3144 isl_set_copy(domain), isl_val_copy(inc));
3145 domain = isl_set_intersect(domain, cond);
3146 if (has_affine_break) {
3147 skip = isl_set_intersect(skip , isl_set_copy(domain));
3148 skip = after(skip, isl_val_sgn(inc));
3149 domain = isl_set_subtract(domain, skip);
3151 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
3152 ls = isl_local_space_from_space(isl_set_get_space(domain));
3153 sched = isl_aff_var_on_domain(ls, isl_dim_set, 0);
3154 if (isl_val_is_neg(inc))
3155 sched = isl_aff_neg(sched);
3157 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
3158 isl_val_copy(inc));
3159 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
3161 if (!is_virtual)
3162 wrap = identity_aff(domain);
3164 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
3165 isl_aff_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
3166 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
3167 scop = resolve_nested(scop);
3168 if (has_var_break)
3169 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
3170 isl_val_copy(inc));
3171 if (id_test) {
3172 scop = scop_add_while(scop_cond, scop, id_test, domain,
3173 isl_val_copy(inc));
3174 isl_set_free(valid_inc);
3175 } else {
3176 scop = pet_scop_restrict_context(scop, valid_inc);
3177 scop = pet_scop_restrict_context(scop, valid_cond_next);
3178 scop = pet_scop_restrict_context(scop, valid_cond_init);
3179 isl_set_free(domain);
3181 clear_assignment(assigned_value, iv);
3183 isl_val_free(inc);
3185 scop = pet_scop_restrict_context(scop, valid_init);
3187 return scop;
3190 /* Try and construct a pet_scop corresponding to a compound statement.
3192 * "skip_declarations" is set if we should skip initial declarations
3193 * in the children of the compound statements. This then implies
3194 * that this sequence of children should not be treated as a block
3195 * since the initial statements may be skipped.
3197 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
3199 return extract(stmt->children(), !skip_declarations, skip_declarations);
3202 /* For each nested access parameter in "space",
3203 * construct a corresponding pet_expr, place it in args and
3204 * record its position in "param2pos".
3205 * "n_arg" is the number of elements that are already in args.
3206 * The position recorded in "param2pos" takes this number into account.
3207 * If the pet_expr corresponding to a parameter is identical to
3208 * the pet_expr corresponding to an earlier parameter, then these two
3209 * parameters are made to refer to the same element in args.
3211 * Return the final number of elements in args or -1 if an error has occurred.
3213 int PetScan::extract_nested(__isl_keep isl_space *space,
3214 int n_arg, pet_expr **args, std::map<int,int> &param2pos)
3216 int nparam;
3218 nparam = isl_space_dim(space, isl_dim_param);
3219 for (int i = 0; i < nparam; ++i) {
3220 int j;
3221 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3222 Expr *nested;
3224 if (!pet_nested_in_id(id)) {
3225 isl_id_free(id);
3226 continue;
3229 nested = (Expr *) isl_id_get_user(id);
3230 args[n_arg] = extract_expr(nested);
3231 isl_id_free(id);
3232 if (!args[n_arg])
3233 return -1;
3235 for (j = 0; j < n_arg; ++j)
3236 if (pet_expr_is_equal(args[j], args[n_arg]))
3237 break;
3239 if (j < n_arg) {
3240 pet_expr_free(args[n_arg]);
3241 args[n_arg] = NULL;
3242 param2pos[i] = j;
3243 } else
3244 param2pos[i] = n_arg++;
3247 return n_arg;
3250 /* For each nested access parameter in the access relations in "expr",
3251 * construct a corresponding pet_expr, place it in the arguments of "expr"
3252 * and record its position in "param2pos".
3253 * n is the number of nested access parameters.
3255 __isl_give pet_expr *PetScan::extract_nested(__isl_take pet_expr *expr, int n,
3256 std::map<int,int> &param2pos)
3258 isl_space *space;
3259 int i;
3260 pet_expr **args;
3262 args = isl_calloc_array(ctx, pet_expr *, n);
3263 if (!args)
3264 return pet_expr_free(expr);
3266 space = pet_expr_access_get_parameter_space(expr);
3267 n = extract_nested(space, 0, args, param2pos);
3268 isl_space_free(space);
3270 if (n < 0)
3271 expr = pet_expr_free(expr);
3272 else
3273 expr = pet_expr_set_n_arg(expr, n);
3275 for (i = 0; i < n; ++i)
3276 expr = pet_expr_set_arg(expr, i, args[i]);
3277 free(args);
3279 return expr;
3282 /* Look for parameters in any access relation in "expr" that
3283 * refer to nested accesses. In particular, these are
3284 * parameters with no name.
3286 * If there are any such parameters, then the domain of the index
3287 * expression and the access relation, which is still [] at this point,
3288 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
3289 * (after identifying identical nested accesses).
3291 * This transformation is performed in several steps.
3292 * We first extract the arguments in extract_nested.
3293 * param2pos maps the original parameter position to the position
3294 * of the argument.
3295 * Then we move these parameters to input dimensions.
3296 * t2pos maps the positions of these temporary input dimensions
3297 * to the positions of the corresponding arguments.
3298 * Finally, we express these temporary dimensions in terms of the domain
3299 * [[] -> [t_1,...,t_n]] and precompose index expression and access
3300 * relations with this function.
3302 __isl_give pet_expr *PetScan::resolve_nested(__isl_take pet_expr *expr)
3304 int n;
3305 int nparam;
3306 isl_space *space;
3307 isl_local_space *ls;
3308 isl_aff *aff;
3309 isl_multi_aff *ma;
3310 std::map<int,int> param2pos;
3311 std::map<int,int> t2pos;
3313 if (!expr)
3314 return expr;
3316 n = pet_expr_get_n_arg(expr);
3317 for (int i = 0; i < n; ++i) {
3318 pet_expr *arg;
3319 arg = pet_expr_get_arg(expr, i);
3320 arg = resolve_nested(arg);
3321 expr = pet_expr_set_arg(expr, i, arg);
3324 if (pet_expr_get_type(expr) != pet_expr_access)
3325 return expr;
3327 space = pet_expr_access_get_parameter_space(expr);
3328 n = pet_nested_n_in_space(space);
3329 isl_space_free(space);
3330 if (n == 0)
3331 return expr;
3333 expr = extract_nested(expr, n, param2pos);
3334 if (!expr)
3335 return NULL;
3337 expr = pet_expr_access_align_params(expr);
3338 if (!expr)
3339 return NULL;
3341 n = 0;
3342 space = pet_expr_access_get_parameter_space(expr);
3343 nparam = isl_space_dim(space, isl_dim_param);
3344 for (int i = nparam - 1; i >= 0; --i) {
3345 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3346 if (!pet_nested_in_id(id)) {
3347 isl_id_free(id);
3348 continue;
3351 expr = pet_expr_access_move_dims(expr,
3352 isl_dim_in, n, isl_dim_param, i, 1);
3353 t2pos[n] = param2pos[i];
3354 n++;
3356 isl_id_free(id);
3358 isl_space_free(space);
3360 space = pet_expr_access_get_parameter_space(expr);
3361 space = isl_space_set_from_params(space);
3362 space = isl_space_add_dims(space, isl_dim_set,
3363 pet_expr_get_n_arg(expr));
3364 space = isl_space_wrap(isl_space_from_range(space));
3365 ls = isl_local_space_from_space(isl_space_copy(space));
3366 space = isl_space_from_domain(space);
3367 space = isl_space_add_dims(space, isl_dim_out, n);
3368 ma = isl_multi_aff_zero(space);
3370 for (int i = 0; i < n; ++i) {
3371 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3372 isl_dim_set, t2pos[i]);
3373 ma = isl_multi_aff_set_aff(ma, i, aff);
3375 isl_local_space_free(ls);
3377 expr = pet_expr_access_pullback_multi_aff(expr, ma);
3379 return expr;
3382 /* Return the file offset of the expansion location of "Loc".
3384 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3386 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3389 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3391 /* Return a SourceLocation for the location after the first semicolon
3392 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3393 * call it and also skip trailing spaces and newline.
3395 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3396 const LangOptions &LO)
3398 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3401 #else
3403 /* Return a SourceLocation for the location after the first semicolon
3404 * after "loc". If Lexer::findLocationAfterToken is not available,
3405 * we look in the underlying character data for the first semicolon.
3407 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3408 const LangOptions &LO)
3410 const char *semi;
3411 const char *s = SM.getCharacterData(loc);
3413 semi = strchr(s, ';');
3414 if (!semi)
3415 return SourceLocation();
3416 return loc.getFileLocWithOffset(semi + 1 - s);
3419 #endif
3421 /* If the token at "loc" is the first token on the line, then return
3422 * a location referring to the start of the line.
3423 * Otherwise, return "loc".
3425 * This function is used to extend a scop to the start of the line
3426 * if the first token of the scop is also the first token on the line.
3428 * We look for the first token on the line. If its location is equal to "loc",
3429 * then the latter is the location of the first token on the line.
3431 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3432 SourceManager &SM, const LangOptions &LO)
3434 std::pair<FileID, unsigned> file_offset_pair;
3435 llvm::StringRef file;
3436 const char *pos;
3437 Token tok;
3438 SourceLocation token_loc, line_loc;
3439 int col;
3441 loc = SM.getExpansionLoc(loc);
3442 col = SM.getExpansionColumnNumber(loc);
3443 line_loc = loc.getLocWithOffset(1 - col);
3444 file_offset_pair = SM.getDecomposedLoc(line_loc);
3445 file = SM.getBufferData(file_offset_pair.first, NULL);
3446 pos = file.data() + file_offset_pair.second;
3448 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3449 file.begin(), pos, file.end());
3450 lexer.LexFromRawLexer(tok);
3451 token_loc = tok.getLocation();
3453 if (token_loc == loc)
3454 return line_loc;
3455 else
3456 return loc;
3459 /* Update start and end of "scop" to include the region covered by "range".
3460 * If "skip_semi" is set, then we assume "range" is followed by
3461 * a semicolon and also include this semicolon.
3463 struct pet_scop *PetScan::update_scop_start_end(struct pet_scop *scop,
3464 SourceRange range, bool skip_semi)
3466 SourceLocation loc = range.getBegin();
3467 SourceManager &SM = PP.getSourceManager();
3468 const LangOptions &LO = PP.getLangOpts();
3469 unsigned start, end;
3471 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3472 start = getExpansionOffset(SM, loc);
3473 loc = range.getEnd();
3474 if (skip_semi)
3475 loc = location_after_semi(loc, SM, LO);
3476 else
3477 loc = PP.getLocForEndOfToken(loc);
3478 end = getExpansionOffset(SM, loc);
3480 scop = pet_scop_update_start_end(scop, start, end);
3481 return scop;
3484 /* Convert a top-level pet_expr to a pet_scop with one statement.
3485 * This mainly involves resolving nested expression parameters
3486 * and setting the name of the iteration space.
3487 * The name is given by "label" if it is non-NULL. Otherwise,
3488 * it is of the form S_<n_stmt>.
3489 * start and end of the pet_scop are derived from those of "stmt".
3490 * If "stmt" is an expression statement, then its range does not
3491 * include the semicolon, while it should be included in the pet_scop.
3493 struct pet_scop *PetScan::extract(Stmt *stmt, __isl_take pet_expr *expr,
3494 __isl_take isl_id *label)
3496 struct pet_stmt *ps;
3497 struct pet_scop *scop;
3498 SourceLocation loc = stmt->getLocStart();
3499 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3500 bool skip_semi;
3502 expr = resolve_nested(expr);
3503 ps = pet_stmt_from_pet_expr(line, label, n_stmt++, expr);
3504 scop = pet_scop_from_pet_stmt(ctx, ps);
3506 skip_semi = isa<Expr>(stmt);
3507 scop = update_scop_start_end(scop, stmt->getSourceRange(), skip_semi);
3508 return scop;
3511 /* Check if we can extract an affine expression from "expr".
3512 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3513 * We turn on autodetection so that we won't generate any warnings
3514 * and turn off nesting, so that we won't accept any non-affine constructs.
3516 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3518 isl_pw_aff *pwaff;
3519 int save_autodetect = options->autodetect;
3520 bool save_nesting = nesting_enabled;
3522 options->autodetect = 1;
3523 nesting_enabled = false;
3525 pwaff = extract_affine(expr);
3527 options->autodetect = save_autodetect;
3528 nesting_enabled = save_nesting;
3530 return pwaff;
3533 /* Check if we can extract an affine constraint from "expr".
3534 * Return the constraint as an isl_set if we can and NULL otherwise.
3535 * We turn on autodetection so that we won't generate any warnings
3536 * and turn off nesting, so that we won't accept any non-affine constructs.
3538 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3540 isl_pw_aff *cond;
3541 int save_autodetect = options->autodetect;
3542 bool save_nesting = nesting_enabled;
3544 options->autodetect = 1;
3545 nesting_enabled = false;
3547 cond = extract_condition(expr);
3549 options->autodetect = save_autodetect;
3550 nesting_enabled = save_nesting;
3552 return cond;
3555 /* Check whether "expr" is an affine constraint.
3557 bool PetScan::is_affine_condition(Expr *expr)
3559 isl_pw_aff *cond;
3561 cond = try_extract_affine_condition(expr);
3562 isl_pw_aff_free(cond);
3564 return cond != NULL;
3567 /* Check if we can extract a condition from "expr".
3568 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3569 * If allow_nested is set, then the condition may involve parameters
3570 * corresponding to nested accesses.
3571 * We turn on autodetection so that we won't generate any warnings.
3573 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3575 isl_pw_aff *cond;
3576 int save_autodetect = options->autodetect;
3577 bool save_nesting = nesting_enabled;
3579 options->autodetect = 1;
3580 nesting_enabled = allow_nested;
3581 cond = extract_condition(expr);
3583 options->autodetect = save_autodetect;
3584 nesting_enabled = save_nesting;
3586 return cond;
3589 /* If the top-level expression of "stmt" is an assignment, then
3590 * return that assignment as a BinaryOperator.
3591 * Otherwise return NULL.
3593 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3595 BinaryOperator *ass;
3597 if (!stmt)
3598 return NULL;
3599 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3600 return NULL;
3602 ass = cast<BinaryOperator>(stmt);
3603 if(ass->getOpcode() != BO_Assign)
3604 return NULL;
3606 return ass;
3609 /* Check if the given if statement is a conditional assignement
3610 * with a non-affine condition. If so, construct a pet_scop
3611 * corresponding to this conditional assignment. Otherwise return NULL.
3613 * In particular we check if "stmt" is of the form
3615 * if (condition)
3616 * a = f(...);
3617 * else
3618 * a = g(...);
3620 * where a is some array or scalar access.
3621 * The constructed pet_scop then corresponds to the expression
3623 * a = condition ? f(...) : g(...)
3625 * All access relations in f(...) are intersected with condition
3626 * while all access relation in g(...) are intersected with the complement.
3628 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3630 BinaryOperator *ass_then, *ass_else;
3631 isl_multi_pw_aff *write_then, *write_else;
3632 isl_set *cond, *comp;
3633 isl_multi_pw_aff *index;
3634 isl_pw_aff *pa;
3635 int equal;
3636 int type_size;
3637 pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3638 bool save_nesting = nesting_enabled;
3640 if (!options->detect_conditional_assignment)
3641 return NULL;
3643 ass_then = top_assignment_or_null(stmt->getThen());
3644 ass_else = top_assignment_or_null(stmt->getElse());
3646 if (!ass_then || !ass_else)
3647 return NULL;
3649 if (is_affine_condition(stmt->getCond()))
3650 return NULL;
3652 write_then = extract_index(ass_then->getLHS());
3653 write_else = extract_index(ass_else->getLHS());
3655 equal = isl_multi_pw_aff_plain_is_equal(write_then, write_else);
3656 isl_multi_pw_aff_free(write_else);
3657 if (equal < 0 || !equal) {
3658 isl_multi_pw_aff_free(write_then);
3659 return NULL;
3662 nesting_enabled = allow_nested;
3663 pa = extract_condition(stmt->getCond());
3664 nesting_enabled = save_nesting;
3665 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3666 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3667 index = isl_multi_pw_aff_from_range(isl_multi_pw_aff_from_pw_aff(pa));
3669 pe_cond = pet_expr_from_index(index);
3671 pe_then = extract_expr(ass_then->getRHS());
3672 pe_then = pet_expr_restrict(pe_then, cond);
3673 pe_else = extract_expr(ass_else->getRHS());
3674 pe_else = pet_expr_restrict(pe_else, comp);
3676 pe = pet_expr_new_ternary(pe_cond, pe_then, pe_else);
3677 type_size = get_type_size(ass_then->getType(), ast_context);
3678 pe_write = pet_expr_from_index_and_depth(type_size, write_then,
3679 extract_depth(write_then));
3680 pe_write = pet_expr_access_set_write(pe_write, 1);
3681 pe_write = pet_expr_access_set_read(pe_write, 0);
3682 pe = pet_expr_new_binary(type_size, pet_op_assign, pe_write, pe);
3683 return extract(stmt, pe);
3686 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3687 * evaluating "cond" and writing the result to a virtual scalar,
3688 * as expressed by "index".
3690 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond, int stmt_nr,
3691 __isl_take isl_multi_pw_aff *index)
3693 pet_expr *expr, *write;
3694 struct pet_stmt *ps;
3695 SourceLocation loc = cond->getLocStart();
3696 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3698 write = pet_expr_from_index(index);
3699 write = pet_expr_access_set_write(write, 1);
3700 write = pet_expr_access_set_read(write, 0);
3701 expr = extract_expr(cond);
3702 expr = resolve_nested(expr);
3703 expr = pet_expr_new_binary(1, pet_op_assign, write, expr);
3704 ps = pet_stmt_from_pet_expr(line, NULL, stmt_nr, expr);
3705 return pet_scop_from_pet_stmt(ctx, ps);
3708 extern "C" {
3709 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr,
3710 void *user);
3713 /* Precompose the access relation and the index expression associated
3714 * to "expr" with the function pointed to by "user",
3715 * thereby embedding the access relation in the domain of this function.
3716 * The initial domain of the access relation and the index expression
3717 * is the zero-dimensional domain.
3719 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr, void *user)
3721 isl_multi_aff *ma = (isl_multi_aff *) user;
3723 return pet_expr_access_pullback_multi_aff(expr, isl_multi_aff_copy(ma));
3726 /* Precompose all access relations in "expr" with "ma", thereby
3727 * embedding them in the domain of "ma".
3729 static __isl_give pet_expr *embed(__isl_take pet_expr *expr,
3730 __isl_keep isl_multi_aff *ma)
3732 return pet_expr_map_access(expr, &embed_access, ma);
3735 /* For each nested access parameter in the domain of "stmt",
3736 * construct a corresponding pet_expr, place it before the original
3737 * elements in stmt->args and record its position in "param2pos".
3738 * n is the number of nested access parameters.
3740 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3741 std::map<int,int> &param2pos)
3743 int i;
3744 isl_space *space;
3745 int n_arg;
3746 pet_expr **args;
3748 n_arg = stmt->n_arg;
3749 args = isl_calloc_array(ctx, pet_expr *, n + n_arg);
3750 if (!args)
3751 goto error;
3753 space = isl_set_get_space(stmt->domain);
3754 n_arg = extract_nested(space, 0, args, param2pos);
3755 isl_space_free(space);
3757 if (n_arg < 0)
3758 goto error;
3760 for (i = 0; i < stmt->n_arg; ++i)
3761 args[n_arg + i] = stmt->args[i];
3762 free(stmt->args);
3763 stmt->args = args;
3764 stmt->n_arg += n_arg;
3766 return stmt;
3767 error:
3768 if (args) {
3769 for (i = 0; i < n; ++i)
3770 pet_expr_free(args[i]);
3771 free(args);
3773 pet_stmt_free(stmt);
3774 return NULL;
3777 /* Check whether any of the arguments i of "stmt" starting at position "n"
3778 * is equal to one of the first "n" arguments j.
3779 * If so, combine the constraints on arguments i and j and remove
3780 * argument i.
3782 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3784 int i, j;
3785 isl_map *map;
3787 if (!stmt)
3788 return NULL;
3789 if (n == 0)
3790 return stmt;
3791 if (n == stmt->n_arg)
3792 return stmt;
3794 map = isl_set_unwrap(stmt->domain);
3796 for (i = stmt->n_arg - 1; i >= n; --i) {
3797 for (j = 0; j < n; ++j)
3798 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3799 break;
3800 if (j >= n)
3801 continue;
3803 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3804 map = isl_map_project_out(map, isl_dim_out, i, 1);
3806 pet_expr_free(stmt->args[i]);
3807 for (j = i; j + 1 < stmt->n_arg; ++j)
3808 stmt->args[j] = stmt->args[j + 1];
3809 stmt->n_arg--;
3812 stmt->domain = isl_map_wrap(map);
3813 if (!stmt->domain)
3814 goto error;
3815 return stmt;
3816 error:
3817 pet_stmt_free(stmt);
3818 return NULL;
3821 /* Look for parameters in the iteration domain of "stmt" that
3822 * refer to nested accesses. In particular, these are
3823 * parameters with no name.
3825 * If there are any such parameters, then as many extra variables
3826 * (after identifying identical nested accesses) are inserted in the
3827 * range of the map wrapped inside the domain, before the original variables.
3828 * If the original domain is not a wrapped map, then a new wrapped
3829 * map is created with zero output dimensions.
3830 * The parameters are then equated to the corresponding output dimensions
3831 * and subsequently projected out, from the iteration domain,
3832 * the schedule and the access relations.
3833 * For each of the output dimensions, a corresponding argument
3834 * expression is inserted. Initially they are created with
3835 * a zero-dimensional domain, so they have to be embedded
3836 * in the current iteration domain.
3837 * param2pos maps the position of the parameter to the position
3838 * of the corresponding output dimension in the wrapped map.
3840 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3842 int n;
3843 int nparam;
3844 unsigned n_arg;
3845 isl_map *map;
3846 isl_space *space;
3847 isl_multi_aff *ma;
3848 std::map<int,int> param2pos;
3850 if (!stmt)
3851 return NULL;
3853 n = pet_nested_n_in_set(stmt->domain);
3854 if (n == 0)
3855 return stmt;
3857 n_arg = stmt->n_arg;
3858 stmt = extract_nested(stmt, n, param2pos);
3859 if (!stmt)
3860 return NULL;
3862 n = stmt->n_arg - n_arg;
3863 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3864 if (isl_set_is_wrapping(stmt->domain))
3865 map = isl_set_unwrap(stmt->domain);
3866 else
3867 map = isl_map_from_domain(stmt->domain);
3868 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3870 for (int i = nparam - 1; i >= 0; --i) {
3871 isl_id *id;
3873 if (!pet_nested_in_map(map, i))
3874 continue;
3876 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
3877 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3878 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3879 param2pos[i]);
3880 map = isl_map_project_out(map, isl_dim_param, i, 1);
3883 stmt->domain = isl_map_wrap(map);
3885 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
3886 space = isl_space_from_domain(isl_space_domain(space));
3887 ma = isl_multi_aff_zero(space);
3888 for (int pos = 0; pos < n; ++pos)
3889 stmt->args[pos] = embed(stmt->args[pos], ma);
3890 isl_multi_aff_free(ma);
3892 stmt = pet_stmt_remove_nested_parameters(stmt);
3893 stmt = remove_duplicate_arguments(stmt, n);
3895 return stmt;
3898 /* For each statement in "scop", move the parameters that correspond
3899 * to nested access into the ranges of the domains and create
3900 * corresponding argument expressions.
3902 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3904 if (!scop)
3905 return NULL;
3907 for (int i = 0; i < scop->n_stmt; ++i) {
3908 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3909 if (!scop->stmts[i])
3910 goto error;
3913 return scop;
3914 error:
3915 pet_scop_free(scop);
3916 return NULL;
3919 /* Given an access expression "expr", is the variable accessed by
3920 * "expr" assigned anywhere inside "scop"?
3922 static bool is_assigned(__isl_keep pet_expr *expr, pet_scop *scop)
3924 bool assigned = false;
3925 isl_id *id;
3927 id = pet_expr_access_get_id(expr);
3928 assigned = pet_scop_writes(scop, id);
3929 isl_id_free(id);
3931 return assigned;
3934 /* Are all nested access parameters in "pa" allowed given "scop".
3935 * In particular, is none of them written by anywhere inside "scop".
3937 * If "scop" has any skip conditions, then no nested access parameters
3938 * are allowed. In particular, if there is any nested access in a guard
3939 * for a piece of code containing a "continue", then we want to introduce
3940 * a separate statement for evaluating this guard so that we can express
3941 * that the result is false for all previous iterations.
3943 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3945 int nparam;
3947 if (!scop)
3948 return true;
3950 if (!pet_nested_any_in_pw_aff(pa))
3951 return true;
3953 if (pet_scop_has_skip(scop, pet_skip_now))
3954 return false;
3956 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3957 for (int i = 0; i < nparam; ++i) {
3958 Expr *nested;
3959 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3960 pet_expr *expr;
3961 bool allowed;
3963 if (!pet_nested_in_id(id)) {
3964 isl_id_free(id);
3965 continue;
3968 nested = (Expr *) isl_id_get_user(id);
3969 expr = extract_expr(nested);
3970 allowed = pet_expr_get_type(expr) == pet_expr_access &&
3971 !is_assigned(expr, scop);
3973 pet_expr_free(expr);
3974 isl_id_free(id);
3976 if (!allowed)
3977 return false;
3980 return true;
3983 /* Construct a pet_scop for a non-affine if statement.
3985 * We create a separate statement that writes the result
3986 * of the non-affine condition to a virtual scalar.
3987 * A constraint requiring the value of this virtual scalar to be one
3988 * is added to the iteration domains of the then branch.
3989 * Similarly, a constraint requiring the value of this virtual scalar
3990 * to be zero is added to the iteration domains of the else branch, if any.
3991 * We adjust the schedules to ensure that the virtual scalar is written
3992 * before it is read.
3994 * If there are any breaks or continues in the then and/or else
3995 * branches, then we may have to compute a new skip condition.
3996 * This is handled using a pet_skip_info object.
3997 * On initialization, the object checks if skip conditions need
3998 * to be computed. If so, it does so in pet_skip_info_if_extract_index and
3999 * adds them in pet_skip_info_if_add.
4001 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
4002 struct pet_scop *scop_then, struct pet_scop *scop_else,
4003 bool have_else, int stmt_id)
4005 struct pet_scop *scop;
4006 isl_multi_pw_aff *test_index;
4007 int int_size;
4008 int save_n_stmt = n_stmt;
4010 test_index = pet_create_test_index(ctx, n_test++);
4011 n_stmt = stmt_id;
4012 scop = extract_non_affine_condition(cond, n_stmt++,
4013 isl_multi_pw_aff_copy(test_index));
4014 n_stmt = save_n_stmt;
4015 scop = scop_add_array(scop, test_index, ast_context);
4017 pet_skip_info skip;
4018 pet_skip_info_if_init(&skip, ctx, scop_then, scop_else, have_else, 0);
4019 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
4020 pet_skip_info_if_extract_index(&skip, test_index, int_size,
4021 &n_stmt, &n_test);
4023 scop = pet_scop_prefix(scop, 0);
4024 scop_then = pet_scop_prefix(scop_then, 1);
4025 scop_then = pet_scop_filter(scop_then,
4026 isl_multi_pw_aff_copy(test_index), 1);
4027 if (have_else) {
4028 scop_else = pet_scop_prefix(scop_else, 1);
4029 scop_else = pet_scop_filter(scop_else, test_index, 0);
4030 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
4031 } else
4032 isl_multi_pw_aff_free(test_index);
4034 scop = pet_scop_add_seq(ctx, scop, scop_then);
4036 scop = pet_skip_info_if_add(&skip, scop, 2);
4038 return scop;
4041 /* Construct a pet_scop for an if statement.
4043 * If the condition fits the pattern of a conditional assignment,
4044 * then it is handled by extract_conditional_assignment.
4045 * Otherwise, we do the following.
4047 * If the condition is affine, then the condition is added
4048 * to the iteration domains of the then branch, while the
4049 * opposite of the condition in added to the iteration domains
4050 * of the else branch, if any.
4051 * We allow the condition to be dynamic, i.e., to refer to
4052 * scalars or array elements that may be written to outside
4053 * of the given if statement. These nested accesses are then represented
4054 * as output dimensions in the wrapping iteration domain.
4055 * If it is also written _inside_ the then or else branch, then
4056 * we treat the condition as non-affine.
4057 * As explained in extract_non_affine_if, this will introduce
4058 * an extra statement.
4059 * For aesthetic reasons, we want this statement to have a statement
4060 * number that is lower than those of the then and else branches.
4061 * In order to evaluate if we will need such a statement, however, we
4062 * first construct scops for the then and else branches.
4063 * We therefore reserve a statement number if we might have to
4064 * introduce such an extra statement.
4066 * If the condition is not affine, then the scop is created in
4067 * extract_non_affine_if.
4069 * If there are any breaks or continues in the then and/or else
4070 * branches, then we may have to compute a new skip condition.
4071 * This is handled using a pet_skip_info object.
4072 * On initialization, the object checks if skip conditions need
4073 * to be computed. If so, it does so in pet_skip_info_if_extract_cond and
4074 * adds them in pet_skip_info_if_add.
4076 struct pet_scop *PetScan::extract(IfStmt *stmt)
4078 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4079 isl_pw_aff *cond;
4080 int stmt_id;
4081 int int_size;
4082 isl_set *set;
4083 isl_set *valid;
4085 clear_assignments clear(assigned_value);
4086 clear.TraverseStmt(stmt->getThen());
4087 if (stmt->getElse())
4088 clear.TraverseStmt(stmt->getElse());
4090 scop = extract_conditional_assignment(stmt);
4091 if (scop)
4092 return scop;
4094 cond = try_extract_nested_condition(stmt->getCond());
4095 if (allow_nested && (!cond || pet_nested_any_in_pw_aff(cond)))
4096 stmt_id = n_stmt++;
4099 assigned_value_cache cache(assigned_value);
4100 scop_then = extract(stmt->getThen());
4103 if (stmt->getElse()) {
4104 assigned_value_cache cache(assigned_value);
4105 scop_else = extract(stmt->getElse());
4106 if (options->autodetect) {
4107 if (scop_then && !scop_else) {
4108 partial = true;
4109 isl_pw_aff_free(cond);
4110 return scop_then;
4112 if (!scop_then && scop_else) {
4113 partial = true;
4114 isl_pw_aff_free(cond);
4115 return scop_else;
4120 if (cond &&
4121 (!is_nested_allowed(cond, scop_then) ||
4122 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4123 isl_pw_aff_free(cond);
4124 cond = NULL;
4126 if (allow_nested && !cond)
4127 return extract_non_affine_if(stmt->getCond(), scop_then,
4128 scop_else, stmt->getElse(), stmt_id);
4130 if (!cond)
4131 cond = extract_condition(stmt->getCond());
4133 pet_skip_info skip;
4134 pet_skip_info_if_init(&skip, ctx, scop_then, scop_else,
4135 stmt->getElse() != NULL, 1);
4136 pet_skip_info_if_extract_cond(&skip, cond, int_size, &n_stmt, &n_test);
4138 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4139 set = isl_pw_aff_non_zero_set(cond);
4140 scop = pet_scop_restrict(scop_then, isl_set_copy(set));
4142 if (stmt->getElse()) {
4143 set = isl_set_subtract(isl_set_copy(valid), set);
4144 scop_else = pet_scop_restrict(scop_else, set);
4145 scop = pet_scop_add_par(ctx, scop, scop_else);
4146 } else
4147 isl_set_free(set);
4148 scop = resolve_nested(scop);
4149 scop = pet_scop_restrict_context(scop, valid);
4151 if (pet_skip_info_has_skip(&skip))
4152 scop = pet_scop_prefix(scop, 0);
4153 scop = pet_skip_info_if_add(&skip, scop, 1);
4155 return scop;
4158 /* Try and construct a pet_scop for a label statement.
4159 * We currently only allow labels on expression statements.
4161 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4163 isl_id *label;
4164 Stmt *sub;
4166 sub = stmt->getSubStmt();
4167 if (!isa<Expr>(sub)) {
4168 unsupported(stmt);
4169 return NULL;
4172 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4174 return extract(sub, extract_expr(cast<Expr>(sub)), label);
4177 /* Return a one-dimensional multi piecewise affine expression that is equal
4178 * to the constant 1 and is defined over a zero-dimensional domain.
4180 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
4182 isl_space *space;
4183 isl_local_space *ls;
4184 isl_aff *aff;
4186 space = isl_space_set_alloc(ctx, 0, 0);
4187 ls = isl_local_space_from_space(space);
4188 aff = isl_aff_zero_on_domain(ls);
4189 aff = isl_aff_set_constant_si(aff, 1);
4191 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4194 /* Construct a pet_scop for a continue statement.
4196 * We simply create an empty scop with a universal pet_skip_now
4197 * skip condition. This skip condition will then be taken into
4198 * account by the enclosing loop construct, possibly after
4199 * being incorporated into outer skip conditions.
4201 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4203 pet_scop *scop;
4205 scop = pet_scop_empty(ctx);
4206 if (!scop)
4207 return NULL;
4209 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
4211 return scop;
4214 /* Construct a pet_scop for a break statement.
4216 * We simply create an empty scop with both a universal pet_skip_now
4217 * skip condition and a universal pet_skip_later skip condition.
4218 * These skip conditions will then be taken into
4219 * account by the enclosing loop construct, possibly after
4220 * being incorporated into outer skip conditions.
4222 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4224 pet_scop *scop;
4225 isl_multi_pw_aff *skip;
4227 scop = pet_scop_empty(ctx);
4228 if (!scop)
4229 return NULL;
4231 skip = one_mpa(ctx);
4232 scop = pet_scop_set_skip(scop, pet_skip_now,
4233 isl_multi_pw_aff_copy(skip));
4234 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
4236 return scop;
4239 /* Try and construct a pet_scop corresponding to "stmt".
4241 * If "stmt" is a compound statement, then "skip_declarations"
4242 * indicates whether we should skip initial declarations in the
4243 * compound statement.
4245 * If the constructed pet_scop is not a (possibly) partial representation
4246 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4247 * In particular, if skip_declarations is set, then we may have skipped
4248 * declarations inside "stmt" and so the pet_scop may not represent
4249 * the entire "stmt".
4250 * Note that this function may be called with "stmt" referring to the entire
4251 * body of the function, including the outer braces. In such cases,
4252 * skip_declarations will be set and the braces will not be taken into
4253 * account in scop->start and scop->end.
4255 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
4257 struct pet_scop *scop;
4259 if (isa<Expr>(stmt))
4260 return extract(stmt, extract_expr(cast<Expr>(stmt)));
4262 switch (stmt->getStmtClass()) {
4263 case Stmt::WhileStmtClass:
4264 scop = extract(cast<WhileStmt>(stmt));
4265 break;
4266 case Stmt::ForStmtClass:
4267 scop = extract_for(cast<ForStmt>(stmt));
4268 break;
4269 case Stmt::IfStmtClass:
4270 scop = extract(cast<IfStmt>(stmt));
4271 break;
4272 case Stmt::CompoundStmtClass:
4273 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
4274 break;
4275 case Stmt::LabelStmtClass:
4276 scop = extract(cast<LabelStmt>(stmt));
4277 break;
4278 case Stmt::ContinueStmtClass:
4279 scop = extract(cast<ContinueStmt>(stmt));
4280 break;
4281 case Stmt::BreakStmtClass:
4282 scop = extract(cast<BreakStmt>(stmt));
4283 break;
4284 case Stmt::DeclStmtClass:
4285 scop = extract(cast<DeclStmt>(stmt));
4286 break;
4287 default:
4288 unsupported(stmt);
4289 return NULL;
4292 if (partial || skip_declarations)
4293 return scop;
4295 scop = update_scop_start_end(scop, stmt->getSourceRange(), false);
4297 return scop;
4300 /* Extract a clone of the kill statement in "scop".
4301 * "scop" is expected to have been created from a DeclStmt
4302 * and should have the kill as its first statement.
4304 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
4306 pet_expr *kill;
4307 struct pet_stmt *stmt;
4308 isl_multi_pw_aff *index;
4309 isl_map *access;
4310 pet_expr *arg;
4312 if (!scop)
4313 return NULL;
4314 if (scop->n_stmt < 1)
4315 isl_die(ctx, isl_error_internal,
4316 "expecting at least one statement", return NULL);
4317 stmt = scop->stmts[0];
4318 if (!pet_stmt_is_kill(stmt))
4319 isl_die(ctx, isl_error_internal,
4320 "expecting kill statement", return NULL);
4322 arg = pet_expr_get_arg(stmt->body, 0);
4323 index = pet_expr_access_get_index(arg);
4324 access = pet_expr_access_get_access(arg);
4325 pet_expr_free(arg);
4326 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
4327 access = isl_map_reset_tuple_id(access, isl_dim_in);
4328 kill = pet_expr_kill_from_access_and_index(access, index);
4329 return pet_stmt_from_pet_expr(stmt->line, NULL, n_stmt++, kill);
4332 /* Mark all arrays in "scop" as being exposed.
4334 static struct pet_scop *mark_exposed(struct pet_scop *scop)
4336 if (!scop)
4337 return NULL;
4338 for (int i = 0; i < scop->n_array; ++i)
4339 scop->arrays[i]->exposed = 1;
4340 return scop;
4343 /* Try and construct a pet_scop corresponding to (part of)
4344 * a sequence of statements.
4346 * "block" is set if the sequence respresents the children of
4347 * a compound statement.
4348 * "skip_declarations" is set if we should skip initial declarations
4349 * in the sequence of statements.
4351 * If there are any breaks or continues in the individual statements,
4352 * then we may have to compute a new skip condition.
4353 * This is handled using a pet_skip_info object.
4354 * On initialization, the object checks if skip conditions need
4355 * to be computed. If so, it does so in pet_skip_info_seq_extract and
4356 * adds them in pet_skip_info_seq_add.
4358 * If "block" is set, then we need to insert kill statements at
4359 * the end of the block for any array that has been declared by
4360 * one of the statements in the sequence. Each of these declarations
4361 * results in the construction of a kill statement at the place
4362 * of the declaration, so we simply collect duplicates of
4363 * those kill statements and append these duplicates to the constructed scop.
4365 * If "block" is not set, then any array declared by one of the statements
4366 * in the sequence is marked as being exposed.
4368 * If autodetect is set, then we allow the extraction of only a subrange
4369 * of the sequence of statements. However, if there is at least one statement
4370 * for which we could not construct a scop and the final range contains
4371 * either no statements or at least one kill, then we discard the entire
4372 * range.
4374 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
4375 bool skip_declarations)
4377 pet_scop *scop;
4378 StmtIterator i;
4379 int int_size;
4380 int j;
4381 bool partial_range = false;
4382 set<struct pet_stmt *> kills;
4383 set<struct pet_stmt *>::iterator it;
4385 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
4387 scop = pet_scop_empty(ctx);
4388 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4389 Stmt *child = *i;
4390 struct pet_scop *scop_i;
4392 if (scop->n_stmt == 0 && skip_declarations &&
4393 child->getStmtClass() == Stmt::DeclStmtClass)
4394 continue;
4396 scop_i = extract(child);
4397 if (scop->n_stmt != 0 && partial) {
4398 pet_scop_free(scop_i);
4399 break;
4401 pet_skip_info skip;
4402 pet_skip_info_seq_init(&skip, ctx, scop, scop_i);
4403 pet_skip_info_seq_extract(&skip, int_size, &n_stmt, &n_test);
4404 if (pet_skip_info_has_skip(&skip))
4405 scop_i = pet_scop_prefix(scop_i, 0);
4406 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4407 if (block)
4408 kills.insert(extract_kill(scop_i));
4409 else
4410 scop_i = mark_exposed(scop_i);
4412 scop_i = pet_scop_prefix(scop_i, j);
4413 if (options->autodetect) {
4414 if (scop_i)
4415 scop = pet_scop_add_seq(ctx, scop, scop_i);
4416 else
4417 partial_range = true;
4418 if (scop->n_stmt != 0 && !scop_i)
4419 partial = true;
4420 } else {
4421 scop = pet_scop_add_seq(ctx, scop, scop_i);
4424 scop = pet_skip_info_seq_add(&skip, scop, j);
4426 if (partial || !scop)
4427 break;
4430 for (it = kills.begin(); it != kills.end(); ++it) {
4431 pet_scop *scop_j;
4432 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4433 scop_j = pet_scop_prefix(scop_j, j);
4434 scop = pet_scop_add_seq(ctx, scop, scop_j);
4437 if (scop && partial_range) {
4438 if (scop->n_stmt == 0 || kills.size() != 0) {
4439 pet_scop_free(scop);
4440 return NULL;
4442 partial = true;
4445 return scop;
4448 /* Check if the scop marked by the user is exactly this Stmt
4449 * or part of this Stmt.
4450 * If so, return a pet_scop corresponding to the marked region.
4451 * Otherwise, return NULL.
4453 struct pet_scop *PetScan::scan(Stmt *stmt)
4455 SourceManager &SM = PP.getSourceManager();
4456 unsigned start_off, end_off;
4458 start_off = getExpansionOffset(SM, stmt->getLocStart());
4459 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4461 if (start_off > loc.end)
4462 return NULL;
4463 if (end_off < loc.start)
4464 return NULL;
4465 if (start_off >= loc.start && end_off <= loc.end) {
4466 return extract(stmt);
4469 StmtIterator start;
4470 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4471 Stmt *child = *start;
4472 if (!child)
4473 continue;
4474 start_off = getExpansionOffset(SM, child->getLocStart());
4475 end_off = getExpansionOffset(SM, child->getLocEnd());
4476 if (start_off < loc.start && end_off >= loc.end)
4477 return scan(child);
4478 if (start_off >= loc.start)
4479 break;
4482 StmtIterator end;
4483 for (end = start; end != stmt->child_end(); ++end) {
4484 Stmt *child = *end;
4485 start_off = SM.getFileOffset(child->getLocStart());
4486 if (start_off >= loc.end)
4487 break;
4490 return extract(StmtRange(start, end), false, false);
4493 /* Set the size of index "pos" of "array" to "size".
4494 * In particular, add a constraint of the form
4496 * i_pos < size
4498 * to array->extent and a constraint of the form
4500 * size >= 0
4502 * to array->context.
4504 static struct pet_array *update_size(struct pet_array *array, int pos,
4505 __isl_take isl_pw_aff *size)
4507 isl_set *valid;
4508 isl_set *univ;
4509 isl_set *bound;
4510 isl_space *dim;
4511 isl_aff *aff;
4512 isl_pw_aff *index;
4513 isl_id *id;
4515 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
4516 array->context = isl_set_intersect(array->context, valid);
4518 dim = isl_set_get_space(array->extent);
4519 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
4520 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
4521 univ = isl_set_universe(isl_aff_get_domain_space(aff));
4522 index = isl_pw_aff_alloc(univ, aff);
4524 size = isl_pw_aff_add_dims(size, isl_dim_in,
4525 isl_set_dim(array->extent, isl_dim_set));
4526 id = isl_set_get_tuple_id(array->extent);
4527 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
4528 bound = isl_pw_aff_lt_set(index, size);
4530 array->extent = isl_set_intersect(array->extent, bound);
4532 if (!array->context || !array->extent)
4533 goto error;
4535 return array;
4536 error:
4537 pet_array_free(array);
4538 return NULL;
4541 /* Figure out the size of the array at position "pos" and all
4542 * subsequent positions from "type" and update "array" accordingly.
4544 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
4545 const Type *type, int pos)
4547 const ArrayType *atype;
4548 isl_pw_aff *size;
4550 if (!array)
4551 return NULL;
4553 if (type->isPointerType()) {
4554 type = type->getPointeeType().getTypePtr();
4555 return set_upper_bounds(array, type, pos + 1);
4557 if (!type->isArrayType())
4558 return array;
4560 type = type->getCanonicalTypeInternal().getTypePtr();
4561 atype = cast<ArrayType>(type);
4563 if (type->isConstantArrayType()) {
4564 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
4565 size = extract_affine(ca->getSize());
4566 array = update_size(array, pos, size);
4567 } else if (type->isVariableArrayType()) {
4568 const VariableArrayType *vla = cast<VariableArrayType>(atype);
4569 size = extract_affine(vla->getSizeExpr());
4570 array = update_size(array, pos, size);
4573 type = atype->getElementType().getTypePtr();
4575 return set_upper_bounds(array, type, pos + 1);
4578 /* Is "T" the type of a variable length array with static size?
4580 static bool is_vla_with_static_size(QualType T)
4582 const VariableArrayType *vlatype;
4584 if (!T->isVariableArrayType())
4585 return false;
4586 vlatype = cast<VariableArrayType>(T);
4587 return vlatype->getSizeModifier() == VariableArrayType::Static;
4590 /* Return the type of "decl" as an array.
4592 * In particular, if "decl" is a parameter declaration that
4593 * is a variable length array with a static size, then
4594 * return the original type (i.e., the variable length array).
4595 * Otherwise, return the type of decl.
4597 static QualType get_array_type(ValueDecl *decl)
4599 ParmVarDecl *parm;
4600 QualType T;
4602 parm = dyn_cast<ParmVarDecl>(decl);
4603 if (!parm)
4604 return decl->getType();
4606 T = parm->getOriginalType();
4607 if (!is_vla_with_static_size(T))
4608 return decl->getType();
4609 return T;
4612 /* Does "decl" have definition that we can keep track of in a pet_type?
4614 static bool has_printable_definition(RecordDecl *decl)
4616 if (!decl->getDeclName())
4617 return false;
4618 return decl->getLexicalDeclContext() == decl->getDeclContext();
4621 /* Construct and return a pet_array corresponding to the variable "decl".
4622 * In particular, initialize array->extent to
4624 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4626 * and then call set_upper_bounds to set the upper bounds on the indices
4627 * based on the type of the variable.
4629 * If the base type is that of a record with a top-level definition and
4630 * if "types" is not null, then the RecordDecl corresponding to the type
4631 * is added to "types".
4633 * If the base type is that of a record with no top-level definition,
4634 * then we replace it by "<subfield>".
4636 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
4637 lex_recorddecl_set *types)
4639 struct pet_array *array;
4640 QualType qt = get_array_type(decl);
4641 const Type *type = qt.getTypePtr();
4642 int depth = array_depth(type);
4643 QualType base = pet_clang_base_type(qt);
4644 string name;
4645 isl_id *id;
4646 isl_space *dim;
4648 array = isl_calloc_type(ctx, struct pet_array);
4649 if (!array)
4650 return NULL;
4652 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
4653 dim = isl_space_set_alloc(ctx, 0, depth);
4654 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
4656 array->extent = isl_set_nat_universe(dim);
4658 dim = isl_space_params_alloc(ctx, 0);
4659 array->context = isl_set_universe(dim);
4661 array = set_upper_bounds(array, type, 0);
4662 if (!array)
4663 return NULL;
4665 name = base.getAsString();
4667 if (types && base->isRecordType()) {
4668 RecordDecl *decl = pet_clang_record_decl(base);
4669 if (has_printable_definition(decl))
4670 types->insert(decl);
4671 else
4672 name = "<subfield>";
4675 array->element_type = strdup(name.c_str());
4676 array->element_is_record = base->isRecordType();
4677 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
4679 return array;
4682 /* Construct and return a pet_array corresponding to the sequence
4683 * of declarations "decls".
4684 * If the sequence contains a single declaration, then it corresponds
4685 * to a simple array access. Otherwise, it corresponds to a member access,
4686 * with the declaration for the substructure following that of the containing
4687 * structure in the sequence of declarations.
4688 * We start with the outermost substructure and then combine it with
4689 * information from the inner structures.
4691 * Additionally, keep track of all required types in "types".
4693 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
4694 vector<ValueDecl *> decls, lex_recorddecl_set *types)
4696 struct pet_array *array;
4697 vector<ValueDecl *>::iterator it;
4699 it = decls.begin();
4701 array = extract_array(ctx, *it, types);
4703 for (++it; it != decls.end(); ++it) {
4704 struct pet_array *parent;
4705 const char *base_name, *field_name;
4706 char *product_name;
4708 parent = array;
4709 array = extract_array(ctx, *it, types);
4710 if (!array)
4711 return pet_array_free(parent);
4713 base_name = isl_set_get_tuple_name(parent->extent);
4714 field_name = isl_set_get_tuple_name(array->extent);
4715 product_name = member_access_name(ctx, base_name, field_name);
4717 array->extent = isl_set_product(isl_set_copy(parent->extent),
4718 array->extent);
4719 if (product_name)
4720 array->extent = isl_set_set_tuple_name(array->extent,
4721 product_name);
4722 array->context = isl_set_intersect(array->context,
4723 isl_set_copy(parent->context));
4725 pet_array_free(parent);
4726 free(product_name);
4728 if (!array->extent || !array->context || !product_name)
4729 return pet_array_free(array);
4732 return array;
4735 /* Add a pet_type corresponding to "decl" to "scop, provided
4736 * it is a member of "types" and it has not been added before
4737 * (i.e., it is not a member of "types_done".
4739 * Since we want the user to be able to print the types
4740 * in the order in which they appear in the scop, we need to
4741 * make sure that types of fields in a structure appear before
4742 * that structure. We therefore call ourselves recursively
4743 * on the types of all record subfields.
4745 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
4746 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
4747 lex_recorddecl_set &types_done)
4749 string s;
4750 llvm::raw_string_ostream S(s);
4751 RecordDecl::field_iterator it;
4753 if (types.find(decl) == types.end())
4754 return scop;
4755 if (types_done.find(decl) != types_done.end())
4756 return scop;
4758 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
4759 RecordDecl *record;
4760 QualType type = it->getType();
4762 if (!type->isRecordType())
4763 continue;
4764 record = pet_clang_record_decl(type);
4765 scop = add_type(ctx, scop, record, PP, types, types_done);
4768 if (strlen(decl->getName().str().c_str()) == 0)
4769 return scop;
4771 decl->print(S, PrintingPolicy(PP.getLangOpts()));
4772 S.str();
4774 scop->types[scop->n_type] = pet_type_alloc(ctx,
4775 decl->getName().str().c_str(), s.c_str());
4776 if (!scop->types[scop->n_type])
4777 return pet_scop_free(scop);
4779 types_done.insert(decl);
4781 scop->n_type++;
4783 return scop;
4786 /* Construct a list of pet_arrays, one for each array (or scalar)
4787 * accessed inside "scop", add this list to "scop" and return the result.
4789 * The context of "scop" is updated with the intersection of
4790 * the contexts of all arrays, i.e., constraints on the parameters
4791 * that ensure that the arrays have a valid (non-negative) size.
4793 * If the any of the extracted arrays refers to a member access,
4794 * then also add the required types to "scop".
4796 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
4798 int i;
4799 array_desc_set arrays;
4800 array_desc_set::iterator it;
4801 lex_recorddecl_set types;
4802 lex_recorddecl_set types_done;
4803 lex_recorddecl_set::iterator types_it;
4804 int n_array;
4805 struct pet_array **scop_arrays;
4807 if (!scop)
4808 return NULL;
4810 pet_scop_collect_arrays(scop, arrays);
4811 if (arrays.size() == 0)
4812 return scop;
4814 n_array = scop->n_array;
4816 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
4817 n_array + arrays.size());
4818 if (!scop_arrays)
4819 goto error;
4820 scop->arrays = scop_arrays;
4822 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
4823 struct pet_array *array;
4824 array = extract_array(ctx, *it, &types);
4825 scop->arrays[n_array + i] = array;
4826 if (!scop->arrays[n_array + i])
4827 goto error;
4828 scop->n_array++;
4829 scop->context = isl_set_intersect(scop->context,
4830 isl_set_copy(array->context));
4831 if (!scop->context)
4832 goto error;
4835 if (types.size() == 0)
4836 return scop;
4838 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
4839 if (!scop->types)
4840 goto error;
4842 for (types_it = types.begin(); types_it != types.end(); ++types_it)
4843 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
4845 return scop;
4846 error:
4847 pet_scop_free(scop);
4848 return NULL;
4851 /* Bound all parameters in scop->context to the possible values
4852 * of the corresponding C variable.
4854 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
4856 int n;
4858 if (!scop)
4859 return NULL;
4861 n = isl_set_dim(scop->context, isl_dim_param);
4862 for (int i = 0; i < n; ++i) {
4863 isl_id *id;
4864 ValueDecl *decl;
4866 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
4867 if (pet_nested_in_id(id)) {
4868 isl_id_free(id);
4869 isl_die(isl_set_get_ctx(scop->context),
4870 isl_error_internal,
4871 "unresolved nested parameter", goto error);
4873 decl = (ValueDecl *) isl_id_get_user(id);
4874 isl_id_free(id);
4876 scop->context = set_parameter_bounds(scop->context, i, decl);
4878 if (!scop->context)
4879 goto error;
4882 return scop;
4883 error:
4884 pet_scop_free(scop);
4885 return NULL;
4888 /* Construct a pet_scop from the given function.
4890 * If the scop was delimited by scop and endscop pragmas, then we override
4891 * the file offsets by those derived from the pragmas.
4893 struct pet_scop *PetScan::scan(FunctionDecl *fd)
4895 pet_scop *scop;
4896 Stmt *stmt;
4898 stmt = fd->getBody();
4900 if (options->autodetect)
4901 scop = extract(stmt, true);
4902 else {
4903 scop = scan(stmt);
4904 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
4906 scop = pet_scop_detect_parameter_accesses(scop);
4907 scop = scan_arrays(scop);
4908 scop = add_parameter_bounds(scop);
4909 scop = pet_scop_gist(scop, value_bounds);
4911 return scop;