PetScan::extract(pet_expr*): take explicit source range
[pet.git] / scan.cc
blob936b54587461fe84d2621198cc13ada4ebcff5fb
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 "context.h"
53 #include "expr.h"
54 #include "nest.h"
55 #include "options.h"
56 #include "scan.h"
57 #include "scop.h"
58 #include "scop_plus.h"
59 #include "skip.h"
61 #include "config.h"
63 using namespace std;
64 using namespace clang;
66 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
68 switch (kind) {
69 case UO_Minus:
70 return pet_op_minus;
71 case UO_Not:
72 return pet_op_not;
73 case UO_LNot:
74 return pet_op_lnot;
75 case UO_PostInc:
76 return pet_op_post_inc;
77 case UO_PostDec:
78 return pet_op_post_dec;
79 case UO_PreInc:
80 return pet_op_pre_inc;
81 case UO_PreDec:
82 return pet_op_pre_dec;
83 default:
84 return pet_op_last;
88 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
90 switch (kind) {
91 case BO_AddAssign:
92 return pet_op_add_assign;
93 case BO_SubAssign:
94 return pet_op_sub_assign;
95 case BO_MulAssign:
96 return pet_op_mul_assign;
97 case BO_DivAssign:
98 return pet_op_div_assign;
99 case BO_Assign:
100 return pet_op_assign;
101 case BO_Add:
102 return pet_op_add;
103 case BO_Sub:
104 return pet_op_sub;
105 case BO_Mul:
106 return pet_op_mul;
107 case BO_Div:
108 return pet_op_div;
109 case BO_Rem:
110 return pet_op_mod;
111 case BO_Shl:
112 return pet_op_shl;
113 case BO_Shr:
114 return pet_op_shr;
115 case BO_EQ:
116 return pet_op_eq;
117 case BO_NE:
118 return pet_op_ne;
119 case BO_LE:
120 return pet_op_le;
121 case BO_GE:
122 return pet_op_ge;
123 case BO_LT:
124 return pet_op_lt;
125 case BO_GT:
126 return pet_op_gt;
127 case BO_And:
128 return pet_op_and;
129 case BO_Xor:
130 return pet_op_xor;
131 case BO_Or:
132 return pet_op_or;
133 case BO_LAnd:
134 return pet_op_land;
135 case BO_LOr:
136 return pet_op_lor;
137 default:
138 return pet_op_last;
142 #if defined(DECLREFEXPR_CREATE_REQUIRES_BOOL)
143 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
145 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
146 SourceLocation(), var, false, var->getInnerLocStart(),
147 var->getType(), VK_LValue);
149 #elif defined(DECLREFEXPR_CREATE_REQUIRES_SOURCELOCATION)
150 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
152 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
153 SourceLocation(), var, var->getInnerLocStart(), var->getType(),
154 VK_LValue);
156 #else
157 static DeclRefExpr *create_DeclRefExpr(VarDecl *var)
159 return DeclRefExpr::Create(var->getASTContext(), var->getQualifierLoc(),
160 var, var->getInnerLocStart(), var->getType(), VK_LValue);
162 #endif
164 /* Check if the element type corresponding to the given array type
165 * has a const qualifier.
167 static bool const_base(QualType qt)
169 const Type *type = qt.getTypePtr();
171 if (type->isPointerType())
172 return const_base(type->getPointeeType());
173 if (type->isArrayType()) {
174 const ArrayType *atype;
175 type = type->getCanonicalTypeInternal().getTypePtr();
176 atype = cast<ArrayType>(type);
177 return const_base(atype->getElementType());
180 return qt.isConstQualified();
183 /* Create an isl_id that refers to the named declarator "decl".
185 static __isl_give isl_id *create_decl_id(isl_ctx *ctx, NamedDecl *decl)
187 return isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
190 /* Mark "decl" as having an unknown value in "assigned_value".
192 * If no (known or unknown) value was assigned to "decl" before,
193 * then it may have been treated as a parameter before and may
194 * therefore appear in a value assigned to another variable.
195 * If so, this assignment needs to be turned into an unknown value too.
197 static void clear_assignment(map<ValueDecl *, isl_pw_aff *> &assigned_value,
198 ValueDecl *decl)
200 map<ValueDecl *, isl_pw_aff *>::iterator it;
202 it = assigned_value.find(decl);
204 assigned_value[decl] = NULL;
206 if (it != assigned_value.end())
207 return;
209 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
210 isl_pw_aff *pa = it->second;
211 int nparam = isl_pw_aff_dim(pa, isl_dim_param);
213 for (int i = 0; i < nparam; ++i) {
214 isl_id *id;
216 if (!isl_pw_aff_has_dim_id(pa, isl_dim_param, i))
217 continue;
218 id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
219 if (isl_id_get_user(id) == decl)
220 it->second = NULL;
221 isl_id_free(id);
226 /* Look for any assignments to scalar variables in part of the parse
227 * tree and set assigned_value to NULL for each of them.
228 * Also reset assigned_value if the address of a scalar variable
229 * is being taken. As an exception, if the address is passed to a function
230 * that is declared to receive a const pointer, then assigned_value is
231 * not reset.
233 * This ensures that we won't use any previously stored value
234 * in the current subtree and its parents.
236 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
237 map<ValueDecl *, isl_pw_aff *> &assigned_value;
238 set<UnaryOperator *> skip;
240 clear_assignments(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
241 assigned_value(assigned_value) {}
243 /* Check for "address of" operators whose value is passed
244 * to a const pointer argument and add them to "skip", so that
245 * we can skip them in VisitUnaryOperator.
247 bool VisitCallExpr(CallExpr *expr) {
248 FunctionDecl *fd;
249 fd = expr->getDirectCallee();
250 if (!fd)
251 return true;
252 for (int i = 0; i < expr->getNumArgs(); ++i) {
253 Expr *arg = expr->getArg(i);
254 UnaryOperator *op;
255 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
256 ImplicitCastExpr *ice;
257 ice = cast<ImplicitCastExpr>(arg);
258 arg = ice->getSubExpr();
260 if (arg->getStmtClass() != Stmt::UnaryOperatorClass)
261 continue;
262 op = cast<UnaryOperator>(arg);
263 if (op->getOpcode() != UO_AddrOf)
264 continue;
265 if (const_base(fd->getParamDecl(i)->getType()))
266 skip.insert(op);
268 return true;
271 bool VisitUnaryOperator(UnaryOperator *expr) {
272 Expr *arg;
273 DeclRefExpr *ref;
274 ValueDecl *decl;
276 switch (expr->getOpcode()) {
277 case UO_AddrOf:
278 case UO_PostInc:
279 case UO_PostDec:
280 case UO_PreInc:
281 case UO_PreDec:
282 break;
283 default:
284 return true;
286 if (skip.find(expr) != skip.end())
287 return true;
289 arg = expr->getSubExpr();
290 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
291 return true;
292 ref = cast<DeclRefExpr>(arg);
293 decl = ref->getDecl();
294 clear_assignment(assigned_value, decl);
295 return true;
298 bool VisitBinaryOperator(BinaryOperator *expr) {
299 Expr *lhs;
300 DeclRefExpr *ref;
301 ValueDecl *decl;
303 if (!expr->isAssignmentOp())
304 return true;
305 lhs = expr->getLHS();
306 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
307 return true;
308 ref = cast<DeclRefExpr>(lhs);
309 decl = ref->getDecl();
310 clear_assignment(assigned_value, decl);
311 return true;
315 /* Keep a copy of the currently assigned values.
317 * Any variable that is assigned a value inside the current scope
318 * is removed again when we leave the scope (either because it wasn't
319 * stored in the cache or because it has a different value in the cache).
321 struct assigned_value_cache {
322 map<ValueDecl *, isl_pw_aff *> &assigned_value;
323 map<ValueDecl *, isl_pw_aff *> cache;
325 assigned_value_cache(map<ValueDecl *, isl_pw_aff *> &assigned_value) :
326 assigned_value(assigned_value), cache(assigned_value) {}
327 ~assigned_value_cache() {
328 map<ValueDecl *, isl_pw_aff *>::iterator it = cache.begin();
329 for (it = assigned_value.begin(); it != assigned_value.end();
330 ++it) {
331 if (!it->second ||
332 (cache.find(it->first) != cache.end() &&
333 cache[it->first] != it->second))
334 cache[it->first] = NULL;
336 assigned_value = cache;
340 /* Convert the mapping from identifiers to values in "assigned_value"
341 * to a pet_context to be used by pet_expr_extract_*.
342 * In particular, the clang identifiers are wrapped in an isl_id and
343 * a NULL value (representing an unknown value) is replaced by a NaN.
345 static __isl_give pet_context *convert_assignments(isl_ctx *ctx,
346 map<ValueDecl *, isl_pw_aff *> &assigned_value)
348 pet_context *pc;
349 map<ValueDecl *, isl_pw_aff *>::iterator it;
351 pc = pet_context_alloc(isl_space_set_alloc(ctx, 0, 0));
353 for (it = assigned_value.begin(); it != assigned_value.end(); ++it) {
354 ValueDecl *decl = it->first;
355 isl_pw_aff *pa = it->second;
356 isl_id *id;
358 id = create_decl_id(ctx, decl);
359 if (pa)
360 pc = pet_context_set_value(pc, id, isl_pw_aff_copy(pa));
361 else
362 pc = pet_context_mark_unknown(pc, id);
365 return pc;
368 /* Insert an expression into the collection of expressions,
369 * provided it is not already in there.
370 * The isl_pw_affs are freed in the destructor.
372 void PetScan::insert_expression(__isl_take isl_pw_aff *expr)
374 std::set<isl_pw_aff *>::iterator it;
376 if (expressions.find(expr) == expressions.end())
377 expressions.insert(expr);
378 else
379 isl_pw_aff_free(expr);
382 PetScan::~PetScan()
384 std::set<isl_pw_aff *>::iterator it;
386 for (it = expressions.begin(); it != expressions.end(); ++it)
387 isl_pw_aff_free(*it);
389 isl_union_map_free(value_bounds);
392 /* Report a diagnostic, unless autodetect is set.
394 void PetScan::report(Stmt *stmt, unsigned id)
396 if (options->autodetect)
397 return;
399 SourceLocation loc = stmt->getLocStart();
400 DiagnosticsEngine &diag = PP.getDiagnostics();
401 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
404 /* Called if we found something we (currently) cannot handle.
405 * We'll provide more informative warnings later.
407 * We only actually complain if autodetect is false.
409 void PetScan::unsupported(Stmt *stmt)
411 DiagnosticsEngine &diag = PP.getDiagnostics();
412 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
413 "unsupported");
414 report(stmt, id);
417 /* Report a missing prototype, unless autodetect is set.
419 void PetScan::report_prototype_required(Stmt *stmt)
421 DiagnosticsEngine &diag = PP.getDiagnostics();
422 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
423 "prototype required");
424 report(stmt, id);
427 /* Report a missing increment, unless autodetect is set.
429 void PetScan::report_missing_increment(Stmt *stmt)
431 DiagnosticsEngine &diag = PP.getDiagnostics();
432 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
433 "missing increment");
434 report(stmt, id);
437 /* Extract an integer from "expr".
439 __isl_give isl_val *PetScan::extract_int(isl_ctx *ctx, IntegerLiteral *expr)
441 const Type *type = expr->getType().getTypePtr();
442 int is_signed = type->hasSignedIntegerRepresentation();
443 llvm::APInt val = expr->getValue();
444 int is_negative = is_signed && val.isNegative();
445 isl_val *v;
447 if (is_negative)
448 val = -val;
450 v = extract_unsigned(ctx, val);
452 if (is_negative)
453 v = isl_val_neg(v);
454 return v;
457 /* Extract an integer from "val", which is assumed to be non-negative.
459 __isl_give isl_val *PetScan::extract_unsigned(isl_ctx *ctx,
460 const llvm::APInt &val)
462 unsigned n;
463 const uint64_t *data;
465 data = val.getRawData();
466 n = val.getNumWords();
467 return isl_val_int_from_chunks(ctx, n, sizeof(uint64_t), data);
470 /* Extract an integer from "expr".
471 * Return NULL if "expr" does not (obviously) represent an integer.
473 __isl_give isl_val *PetScan::extract_int(clang::ParenExpr *expr)
475 return extract_int(expr->getSubExpr());
478 /* Extract an integer from "expr".
479 * Return NULL if "expr" does not (obviously) represent an integer.
481 __isl_give isl_val *PetScan::extract_int(clang::Expr *expr)
483 if (expr->getStmtClass() == Stmt::IntegerLiteralClass)
484 return extract_int(ctx, cast<IntegerLiteral>(expr));
485 if (expr->getStmtClass() == Stmt::ParenExprClass)
486 return extract_int(cast<ParenExpr>(expr));
488 unsupported(expr);
489 return NULL;
492 /* Extract an affine expression from the IntegerLiteral "expr".
493 * If the value of "expr" is "v", then the returned expression
494 * is
496 * { [] -> [v] }
498 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
500 isl_space *space = isl_space_set_alloc(ctx, 0, 0);
501 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(space));
502 isl_aff *aff = isl_aff_zero_on_domain(ls);
503 isl_set *dom = isl_set_universe(space);
504 isl_val *v;
506 v = extract_int(expr);
507 aff = isl_aff_add_constant_val(aff, v);
509 return isl_pw_aff_alloc(dom, aff);
512 /* Extract an affine expression from the APInt "val", which is assumed
513 * to be non-negative.
514 * If the value of "val" is "v", then the returned expression
515 * is
517 * { [] -> [v] }
519 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
521 isl_space *space = isl_space_set_alloc(ctx, 0, 0);
522 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(space));
523 isl_aff *aff = isl_aff_zero_on_domain(ls);
524 isl_set *dom = isl_set_universe(space);
525 isl_val *v;
527 v = extract_unsigned(ctx, val);
528 aff = isl_aff_add_constant_val(aff, v);
530 return isl_pw_aff_alloc(dom, aff);
533 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
535 return extract_affine(expr->getSubExpr());
538 /* Return the number of bits needed to represent the type "qt",
539 * if it is an integer type. Otherwise return 0.
540 * If qt is signed then return the opposite of the number of bits.
542 static int get_type_size(QualType qt, ASTContext &ast_context)
544 int size;
546 if (!qt->isIntegerType())
547 return 0;
549 size = ast_context.getIntWidth(qt);
550 if (!qt->isUnsignedIntegerType())
551 size = -size;
553 return size;
556 /* Return the number of bits needed to represent the type of "decl",
557 * if it is an integer type. Otherwise return 0.
558 * If qt is signed then return the opposite of the number of bits.
560 static int get_type_size(ValueDecl *decl)
562 return get_type_size(decl->getType(), decl->getASTContext());
565 /* Bound parameter "pos" of "set" to the possible values of "decl".
567 static __isl_give isl_set *set_parameter_bounds(__isl_take isl_set *set,
568 unsigned pos, ValueDecl *decl)
570 int type_size;
571 isl_ctx *ctx;
572 isl_val *bound;
574 ctx = isl_set_get_ctx(set);
575 type_size = get_type_size(decl);
576 if (type_size == 0)
577 isl_die(ctx, isl_error_invalid, "not an integer type",
578 return isl_set_free(set));
579 if (type_size > 0) {
580 set = isl_set_lower_bound_si(set, isl_dim_param, pos, 0);
581 bound = isl_val_int_from_ui(ctx, type_size);
582 bound = isl_val_2exp(bound);
583 bound = isl_val_sub_ui(bound, 1);
584 set = isl_set_upper_bound_val(set, isl_dim_param, pos, bound);
585 } else {
586 bound = isl_val_int_from_ui(ctx, -type_size - 1);
587 bound = isl_val_2exp(bound);
588 bound = isl_val_sub_ui(bound, 1);
589 set = isl_set_upper_bound_val(set, isl_dim_param, pos,
590 isl_val_copy(bound));
591 bound = isl_val_neg(bound);
592 bound = isl_val_sub_ui(bound, 1);
593 set = isl_set_lower_bound_val(set, isl_dim_param, pos, bound);
596 return set;
599 /* Extract an affine expression from the DeclRefExpr "expr".
601 * If the variable has been assigned a value, then we check whether
602 * we know what (affine) value was assigned.
603 * If so, we return this value. Otherwise we convert "expr"
604 * to an extra parameter (provided nesting_enabled is set).
606 * Otherwise, we simply return an expression that is equal
607 * to a parameter corresponding to the referenced variable.
609 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
611 ValueDecl *decl = expr->getDecl();
612 const Type *type = decl->getType().getTypePtr();
613 isl_id *id;
614 isl_space *space;
615 isl_aff *aff;
616 isl_set *dom;
618 if (!type->isIntegerType()) {
619 unsupported(expr);
620 return NULL;
623 if (assigned_value.find(decl) != assigned_value.end()) {
624 if (assigned_value[decl])
625 return isl_pw_aff_copy(assigned_value[decl]);
626 else
627 return nested_access(expr);
630 id = create_decl_id(ctx, decl);
631 space = isl_space_set_alloc(ctx, 1, 0);
633 space = isl_space_set_dim_id(space, isl_dim_param, 0, id);
635 dom = isl_set_universe(isl_space_copy(space));
636 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
637 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
639 return isl_pw_aff_alloc(dom, aff);
642 /* Extract an affine expression from an integer division operation.
643 * In particular, if "expr" is lhs/rhs, then return
645 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
647 * The second argument (rhs) is required to be a (positive) integer constant.
649 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
651 int is_cst;
652 isl_pw_aff *rhs, *lhs;
654 rhs = extract_affine(expr->getRHS());
655 is_cst = isl_pw_aff_is_cst(rhs);
656 if (is_cst < 0 || !is_cst) {
657 isl_pw_aff_free(rhs);
658 if (!is_cst)
659 unsupported(expr);
660 return NULL;
663 lhs = extract_affine(expr->getLHS());
665 return isl_pw_aff_tdiv_q(lhs, rhs);
668 /* Extract an affine expression from a modulo operation.
669 * In particular, if "expr" is lhs/rhs, then return
671 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
673 * The second argument (rhs) is required to be a (positive) integer constant.
675 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
677 int is_cst;
678 isl_pw_aff *rhs, *lhs;
680 rhs = extract_affine(expr->getRHS());
681 is_cst = isl_pw_aff_is_cst(rhs);
682 if (is_cst < 0 || !is_cst) {
683 isl_pw_aff_free(rhs);
684 if (!is_cst)
685 unsupported(expr);
686 return NULL;
689 lhs = extract_affine(expr->getLHS());
691 return isl_pw_aff_tdiv_r(lhs, rhs);
694 /* Extract an affine expression from a multiplication operation.
695 * This is only allowed if at least one of the two arguments
696 * is a (piecewise) constant.
698 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
700 isl_pw_aff *lhs;
701 isl_pw_aff *rhs;
703 lhs = extract_affine(expr->getLHS());
704 rhs = extract_affine(expr->getRHS());
706 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
707 isl_pw_aff_free(lhs);
708 isl_pw_aff_free(rhs);
709 unsupported(expr);
710 return NULL;
713 return isl_pw_aff_mul(lhs, rhs);
716 /* Extract an affine expression from an addition or subtraction operation.
718 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
720 isl_pw_aff *lhs;
721 isl_pw_aff *rhs;
723 lhs = extract_affine(expr->getLHS());
724 rhs = extract_affine(expr->getRHS());
726 switch (expr->getOpcode()) {
727 case BO_Add:
728 return isl_pw_aff_add(lhs, rhs);
729 case BO_Sub:
730 return isl_pw_aff_sub(lhs, rhs);
731 default:
732 isl_pw_aff_free(lhs);
733 isl_pw_aff_free(rhs);
734 return NULL;
739 /* Compute
741 * pwaff mod 2^width
743 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
744 unsigned width)
746 isl_ctx *ctx;
747 isl_val *mod;
749 ctx = isl_pw_aff_get_ctx(pwaff);
750 mod = isl_val_int_from_ui(ctx, width);
751 mod = isl_val_2exp(mod);
753 pwaff = isl_pw_aff_mod_val(pwaff, mod);
755 return pwaff;
758 /* Limit the domain of "pwaff" to those elements where the function
759 * value satisfies
761 * 2^{width-1} <= pwaff < 2^{width-1}
763 static __isl_give isl_pw_aff *avoid_overflow(__isl_take isl_pw_aff *pwaff,
764 unsigned width)
766 isl_ctx *ctx;
767 isl_val *v;
768 isl_space *space = isl_pw_aff_get_domain_space(pwaff);
769 isl_local_space *ls = isl_local_space_from_space(space);
770 isl_aff *bound;
771 isl_set *dom;
772 isl_pw_aff *b;
774 ctx = isl_pw_aff_get_ctx(pwaff);
775 v = isl_val_int_from_ui(ctx, width - 1);
776 v = isl_val_2exp(v);
778 bound = isl_aff_zero_on_domain(ls);
779 bound = isl_aff_add_constant_val(bound, v);
780 b = isl_pw_aff_from_aff(bound);
782 dom = isl_pw_aff_lt_set(isl_pw_aff_copy(pwaff), isl_pw_aff_copy(b));
783 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
785 b = isl_pw_aff_neg(b);
786 dom = isl_pw_aff_ge_set(isl_pw_aff_copy(pwaff), b);
787 pwaff = isl_pw_aff_intersect_domain(pwaff, dom);
789 return pwaff;
792 /* Handle potential overflows on signed computations.
794 * If options->signed_overflow is set to PET_OVERFLOW_AVOID,
795 * the we adjust the domain of "pa" to avoid overflows.
797 __isl_give isl_pw_aff *PetScan::signed_overflow(__isl_take isl_pw_aff *pa,
798 unsigned width)
800 if (options->signed_overflow == PET_OVERFLOW_AVOID)
801 pa = avoid_overflow(pa, width);
803 return pa;
806 /* Return the piecewise affine expression "set ? 1 : 0" defined on "dom".
808 static __isl_give isl_pw_aff *indicator_function(__isl_take isl_set *set,
809 __isl_take isl_set *dom)
811 isl_pw_aff *pa;
812 pa = isl_set_indicator_function(set);
813 pa = isl_pw_aff_intersect_domain(pa, isl_set_coalesce(dom));
814 return pa;
817 /* Extract an affine expression from some binary operations.
818 * If the result of the expression is unsigned, then we wrap it
819 * based on the size of the type. Otherwise, we ensure that
820 * no overflow occurs.
822 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
824 isl_pw_aff *res;
825 unsigned width;
827 switch (expr->getOpcode()) {
828 case BO_Add:
829 case BO_Sub:
830 res = extract_affine_add(expr);
831 break;
832 case BO_Div:
833 res = extract_affine_div(expr);
834 break;
835 case BO_Rem:
836 res = extract_affine_mod(expr);
837 break;
838 case BO_Mul:
839 res = extract_affine_mul(expr);
840 break;
841 case BO_LT:
842 case BO_LE:
843 case BO_GT:
844 case BO_GE:
845 case BO_EQ:
846 case BO_NE:
847 case BO_LAnd:
848 case BO_LOr:
849 return extract_condition(expr);
850 default:
851 unsupported(expr);
852 return NULL;
855 width = ast_context.getIntWidth(expr->getType());
856 if (expr->getType()->isUnsignedIntegerType())
857 res = wrap(res, width);
858 else
859 res = signed_overflow(res, width);
861 return res;
864 /* Extract an affine expression from a negation operation.
866 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
868 if (expr->getOpcode() == UO_Minus)
869 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
870 if (expr->getOpcode() == UO_LNot)
871 return extract_condition(expr);
873 unsupported(expr);
874 return NULL;
877 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
879 return extract_affine(expr->getSubExpr());
882 /* Extract an affine expression from some special function calls.
883 * In particular, we handle "min", "max", "ceild", "floord",
884 * "intMod", "intFloor" and "intCeil".
885 * In case of the latter five, the second argument needs to be
886 * a (positive) integer constant.
888 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
890 FunctionDecl *fd;
891 string name;
892 isl_pw_aff *aff1, *aff2;
894 fd = expr->getDirectCallee();
895 if (!fd) {
896 unsupported(expr);
897 return NULL;
900 name = fd->getDeclName().getAsString();
901 if (!(expr->getNumArgs() == 2 && name == "min") &&
902 !(expr->getNumArgs() == 2 && name == "max") &&
903 !(expr->getNumArgs() == 2 && name == "intMod") &&
904 !(expr->getNumArgs() == 2 && name == "intFloor") &&
905 !(expr->getNumArgs() == 2 && name == "intCeil") &&
906 !(expr->getNumArgs() == 2 && name == "floord") &&
907 !(expr->getNumArgs() == 2 && name == "ceild")) {
908 unsupported(expr);
909 return NULL;
912 if (name == "min" || name == "max") {
913 aff1 = extract_affine(expr->getArg(0));
914 aff2 = extract_affine(expr->getArg(1));
916 if (name == "min")
917 aff1 = isl_pw_aff_min(aff1, aff2);
918 else
919 aff1 = isl_pw_aff_max(aff1, aff2);
920 } else if (name == "intMod") {
921 isl_val *v;
922 Expr *arg2 = expr->getArg(1);
924 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
925 unsupported(expr);
926 return NULL;
928 aff1 = extract_affine(expr->getArg(0));
929 v = extract_int(cast<IntegerLiteral>(arg2));
930 aff1 = isl_pw_aff_mod_val(aff1, v);
931 } else if (name == "floord" || name == "ceild" ||
932 name == "intFloor" || name == "intCeil") {
933 isl_val *v;
934 Expr *arg2 = expr->getArg(1);
936 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
937 unsupported(expr);
938 return NULL;
940 aff1 = extract_affine(expr->getArg(0));
941 v = extract_int(cast<IntegerLiteral>(arg2));
942 aff1 = isl_pw_aff_scale_down_val(aff1, v);
943 if (name == "floord" || name == "intFloor")
944 aff1 = isl_pw_aff_floor(aff1);
945 else
946 aff1 = isl_pw_aff_ceil(aff1);
947 } else {
948 unsupported(expr);
949 return NULL;
952 return aff1;
955 /* This method is called when we come across an access that is
956 * nested in what is supposed to be an affine expression.
957 * If nesting is allowed, we return a new parameter that corresponds
958 * to this nested access. Otherwise, we simply complain.
960 * Note that we currently don't allow nested accesses themselves
961 * to contain any nested accesses, so we check if we can extract
962 * the access without any nesting and complain if we can't.
964 * The new parameter is resolved in resolve_nested.
966 isl_pw_aff *PetScan::nested_access(Expr *expr)
968 isl_id *id;
969 isl_space *space;
970 isl_aff *aff;
971 isl_set *dom;
972 isl_multi_pw_aff *index;
974 if (!nesting_enabled) {
975 unsupported(expr);
976 return NULL;
979 allow_nested = false;
980 index = extract_index(expr);
981 allow_nested = true;
982 if (!index) {
983 unsupported(expr);
984 return NULL;
986 isl_multi_pw_aff_free(index);
988 id = pet_nested_clang_expr(ctx, expr);
989 space = isl_space_set_alloc(ctx, 1, 0);
991 space = isl_space_set_dim_id(space, isl_dim_param, 0, id);
993 dom = isl_set_universe(isl_space_copy(space));
994 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
995 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
997 return isl_pw_aff_alloc(dom, aff);
1000 /* Affine expressions are not supposed to contain array accesses,
1001 * but if nesting is allowed, we return a parameter corresponding
1002 * to the array access.
1004 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
1006 return nested_access(expr);
1009 /* Affine expressions are not supposed to contain member accesses,
1010 * but if nesting is allowed, we return a parameter corresponding
1011 * to the member access.
1013 __isl_give isl_pw_aff *PetScan::extract_affine(MemberExpr *expr)
1015 return nested_access(expr);
1018 /* Extract an affine expression from a conditional operation.
1020 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
1022 isl_pw_aff *cond, *lhs, *rhs;
1024 cond = extract_condition(expr->getCond());
1025 lhs = extract_affine(expr->getTrueExpr());
1026 rhs = extract_affine(expr->getFalseExpr());
1028 return isl_pw_aff_cond(cond, lhs, rhs);
1031 /* Extract an affine expression, if possible, from "expr".
1032 * Otherwise return NULL.
1034 * The result has an anonymous zero-dimensional domain.
1036 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
1038 switch (expr->getStmtClass()) {
1039 case Stmt::ImplicitCastExprClass:
1040 return extract_affine(cast<ImplicitCastExpr>(expr));
1041 case Stmt::IntegerLiteralClass:
1042 return extract_affine(cast<IntegerLiteral>(expr));
1043 case Stmt::DeclRefExprClass:
1044 return extract_affine(cast<DeclRefExpr>(expr));
1045 case Stmt::BinaryOperatorClass:
1046 return extract_affine(cast<BinaryOperator>(expr));
1047 case Stmt::UnaryOperatorClass:
1048 return extract_affine(cast<UnaryOperator>(expr));
1049 case Stmt::ParenExprClass:
1050 return extract_affine(cast<ParenExpr>(expr));
1051 case Stmt::CallExprClass:
1052 return extract_affine(cast<CallExpr>(expr));
1053 case Stmt::ArraySubscriptExprClass:
1054 return extract_affine(cast<ArraySubscriptExpr>(expr));
1055 case Stmt::MemberExprClass:
1056 return extract_affine(cast<MemberExpr>(expr));
1057 case Stmt::ConditionalOperatorClass:
1058 return extract_affine(cast<ConditionalOperator>(expr));
1059 default:
1060 unsupported(expr);
1062 return NULL;
1065 __isl_give isl_multi_pw_aff *PetScan::extract_index(ImplicitCastExpr *expr)
1067 return extract_index(expr->getSubExpr());
1070 /* Return the depth of an array of the given type.
1072 static int array_depth(const Type *type)
1074 if (type->isPointerType())
1075 return 1 + array_depth(type->getPointeeType().getTypePtr());
1076 if (type->isArrayType()) {
1077 const ArrayType *atype;
1078 type = type->getCanonicalTypeInternal().getTypePtr();
1079 atype = cast<ArrayType>(type);
1080 return 1 + array_depth(atype->getElementType().getTypePtr());
1082 return 0;
1085 /* Return the depth of the array accessed by the index expression "index".
1086 * If "index" is an affine expression, i.e., if it does not access
1087 * any array, then return 1.
1088 * If "index" represent a member access, i.e., if its range is a wrapped
1089 * relation, then return the sum of the depth of the array of structures
1090 * and that of the member inside the structure.
1092 static int extract_depth(__isl_keep isl_multi_pw_aff *index)
1094 isl_id *id;
1095 ValueDecl *decl;
1097 if (!index)
1098 return -1;
1100 if (isl_multi_pw_aff_range_is_wrapping(index)) {
1101 int domain_depth, range_depth;
1102 isl_multi_pw_aff *domain, *range;
1104 domain = isl_multi_pw_aff_copy(index);
1105 domain = isl_multi_pw_aff_range_factor_domain(domain);
1106 domain_depth = extract_depth(domain);
1107 isl_multi_pw_aff_free(domain);
1108 range = isl_multi_pw_aff_copy(index);
1109 range = isl_multi_pw_aff_range_factor_range(range);
1110 range_depth = extract_depth(range);
1111 isl_multi_pw_aff_free(range);
1113 return domain_depth + range_depth;
1116 if (!isl_multi_pw_aff_has_tuple_id(index, isl_dim_out))
1117 return 1;
1119 id = isl_multi_pw_aff_get_tuple_id(index, isl_dim_out);
1120 if (!id)
1121 return -1;
1122 decl = (ValueDecl *) isl_id_get_user(id);
1123 isl_id_free(id);
1125 return array_depth(decl->getType().getTypePtr());
1128 /* Extract an index expression from a reference to a variable.
1129 * If the variable has name "A", then the returned index expression
1130 * is of the form
1132 * { [] -> A[] }
1134 __isl_give isl_multi_pw_aff *PetScan::extract_index(DeclRefExpr *expr)
1136 return extract_index(expr->getDecl());
1139 /* Extract an index expression from a variable.
1140 * If the variable has name "A", then the returned index expression
1141 * is of the form
1143 * { [] -> A[] }
1145 __isl_give isl_multi_pw_aff *PetScan::extract_index(ValueDecl *decl)
1147 isl_id *id = create_decl_id(ctx, decl);
1148 isl_space *space = isl_space_alloc(ctx, 0, 0, 0);
1150 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1152 return isl_multi_pw_aff_zero(space);
1155 /* Extract an index expression from an integer contant.
1156 * If the value of the constant is "v", then the returned access relation
1157 * is
1159 * { [] -> [v] }
1161 __isl_give isl_multi_pw_aff *PetScan::extract_index(IntegerLiteral *expr)
1163 isl_multi_pw_aff *mpa;
1165 mpa = isl_multi_pw_aff_from_pw_aff(extract_affine(expr));
1166 return mpa;
1169 /* Try and extract an index expression from the given Expr.
1170 * Return NULL if it doesn't work out.
1172 __isl_give isl_multi_pw_aff *PetScan::extract_index(Expr *expr)
1174 switch (expr->getStmtClass()) {
1175 case Stmt::ImplicitCastExprClass:
1176 return extract_index(cast<ImplicitCastExpr>(expr));
1177 case Stmt::DeclRefExprClass:
1178 return extract_index(cast<DeclRefExpr>(expr));
1179 case Stmt::ArraySubscriptExprClass:
1180 return extract_index(cast<ArraySubscriptExpr>(expr));
1181 case Stmt::IntegerLiteralClass:
1182 return extract_index(cast<IntegerLiteral>(expr));
1183 case Stmt::MemberExprClass:
1184 return extract_index(cast<MemberExpr>(expr));
1185 default:
1186 unsupported(expr);
1188 return NULL;
1191 /* Given a partial index expression "base" and an extra index "index",
1192 * append the extra index to "base" and return the result.
1193 * Additionally, add the constraints that the extra index is non-negative.
1194 * If "index" represent a member access, i.e., if its range is a wrapped
1195 * relation, then we recursively extend the range of this nested relation.
1197 * The inputs "base" and "index", as well as the result, all have
1198 * an anonymous zero-dimensional domain.
1200 static __isl_give isl_multi_pw_aff *subscript(__isl_take isl_multi_pw_aff *base,
1201 __isl_take isl_pw_aff *index)
1203 isl_id *id;
1204 isl_set *domain;
1205 isl_multi_pw_aff *access;
1206 int member_access;
1208 member_access = isl_multi_pw_aff_range_is_wrapping(base);
1209 if (member_access < 0)
1210 goto error;
1211 if (member_access) {
1212 isl_multi_pw_aff *domain, *range;
1213 isl_id *id;
1215 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_out);
1216 domain = isl_multi_pw_aff_copy(base);
1217 domain = isl_multi_pw_aff_range_factor_domain(domain);
1218 range = isl_multi_pw_aff_range_factor_range(base);
1219 range = subscript(range, index);
1220 access = isl_multi_pw_aff_range_product(domain, range);
1221 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_out, id);
1222 return access;
1225 id = isl_multi_pw_aff_get_tuple_id(base, isl_dim_set);
1226 domain = isl_pw_aff_nonneg_set(isl_pw_aff_copy(index));
1227 index = isl_pw_aff_intersect_domain(index, domain);
1228 access = isl_multi_pw_aff_from_pw_aff(index);
1229 access = isl_multi_pw_aff_flat_range_product(base, access);
1230 access = isl_multi_pw_aff_set_tuple_id(access, isl_dim_set, id);
1232 return access;
1233 error:
1234 isl_multi_pw_aff_free(base);
1235 isl_pw_aff_free(index);
1236 return NULL;
1239 /* Extract an index expression from the given array subscript expression.
1240 * If nesting is allowed in general, then we turn it on while
1241 * examining the index expression.
1243 * We first extract an index expression from the base.
1244 * This will result in an index expression with a range that corresponds
1245 * to the earlier indices.
1246 * We then extract the current index, restrict its domain
1247 * to those values that result in a non-negative index and
1248 * append the index to the base index expression.
1250 __isl_give isl_multi_pw_aff *PetScan::extract_index(ArraySubscriptExpr *expr)
1252 Expr *base = expr->getBase();
1253 Expr *idx = expr->getIdx();
1254 isl_pw_aff *index;
1255 isl_multi_pw_aff *base_access;
1256 isl_multi_pw_aff *access;
1257 bool save_nesting = nesting_enabled;
1259 nesting_enabled = allow_nested;
1261 base_access = extract_index(base);
1262 index = extract_affine(idx);
1264 nesting_enabled = save_nesting;
1266 access = subscript(base_access, index);
1268 return access;
1271 /* Construct a name for a member access by concatenating the name
1272 * of the array of structures and the member, separated by an underscore.
1274 * The caller is responsible for freeing the result.
1276 static char *member_access_name(isl_ctx *ctx, const char *base,
1277 const char *field)
1279 int len;
1280 char *name;
1282 len = strlen(base) + 1 + strlen(field);
1283 name = isl_alloc_array(ctx, char, len + 1);
1284 if (!name)
1285 return NULL;
1286 snprintf(name, len + 1, "%s_%s", base, field);
1288 return name;
1291 /* Given an index expression "base" for an element of an array of structures
1292 * and an expression "field" for the field member being accessed, construct
1293 * an index expression for an access to that member of the given structure.
1294 * In particular, take the range product of "base" and "field" and
1295 * attach a name to the result.
1297 static __isl_give isl_multi_pw_aff *member(__isl_take isl_multi_pw_aff *base,
1298 __isl_take isl_multi_pw_aff *field)
1300 isl_ctx *ctx;
1301 isl_multi_pw_aff *access;
1302 const char *base_name, *field_name;
1303 char *name;
1305 ctx = isl_multi_pw_aff_get_ctx(base);
1307 base_name = isl_multi_pw_aff_get_tuple_name(base, isl_dim_out);
1308 field_name = isl_multi_pw_aff_get_tuple_name(field, isl_dim_out);
1309 name = member_access_name(ctx, base_name, field_name);
1311 access = isl_multi_pw_aff_range_product(base, field);
1313 access = isl_multi_pw_aff_set_tuple_name(access, isl_dim_out, name);
1314 free(name);
1316 return access;
1319 /* Extract an index expression from a member expression.
1321 * If the base access (to the structure containing the member)
1322 * is of the form
1324 * [] -> A[..]
1326 * and the member is called "f", then the member access is of
1327 * the form
1329 * [] -> A_f[A[..] -> f[]]
1331 * If the member access is to an anonymous struct, then simply return
1333 * [] -> A[..]
1335 * If the member access in the source code is of the form
1337 * A->f
1339 * then it is treated as
1341 * A[0].f
1343 __isl_give isl_multi_pw_aff *PetScan::extract_index(MemberExpr *expr)
1345 Expr *base = expr->getBase();
1346 FieldDecl *field = cast<FieldDecl>(expr->getMemberDecl());
1347 isl_multi_pw_aff *base_access, *field_access;
1348 isl_id *id;
1349 isl_space *space;
1351 base_access = extract_index(base);
1353 if (expr->isArrow()) {
1354 isl_space *space = isl_space_set_alloc(ctx, 0, 0);
1355 isl_local_space *ls = isl_local_space_from_space(space);
1356 isl_aff *aff = isl_aff_zero_on_domain(ls);
1357 isl_pw_aff *index = isl_pw_aff_from_aff(aff);
1358 base_access = subscript(base_access, index);
1361 if (field->isAnonymousStructOrUnion())
1362 return base_access;
1364 id = create_decl_id(ctx, field);
1365 space = isl_multi_pw_aff_get_domain_space(base_access);
1366 space = isl_space_from_domain(space);
1367 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1368 field_access = isl_multi_pw_aff_zero(space);
1370 return member(base_access, field_access);
1373 /* Check if "expr" calls function "minmax" with two arguments and if so
1374 * make lhs and rhs refer to these two arguments.
1376 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
1378 CallExpr *call;
1379 FunctionDecl *fd;
1380 string name;
1382 if (expr->getStmtClass() != Stmt::CallExprClass)
1383 return false;
1385 call = cast<CallExpr>(expr);
1386 fd = call->getDirectCallee();
1387 if (!fd)
1388 return false;
1390 if (call->getNumArgs() != 2)
1391 return false;
1393 name = fd->getDeclName().getAsString();
1394 if (name != minmax)
1395 return false;
1397 lhs = call->getArg(0);
1398 rhs = call->getArg(1);
1400 return true;
1403 /* Check if "expr" is of the form min(lhs, rhs) and if so make
1404 * lhs and rhs refer to the two arguments.
1406 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
1408 return is_minmax(expr, "min", lhs, rhs);
1411 /* Check if "expr" is of the form max(lhs, rhs) and if so make
1412 * lhs and rhs refer to the two arguments.
1414 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
1416 return is_minmax(expr, "max", lhs, rhs);
1419 /* Extract an affine expressions representing the comparison "LHS op RHS"
1420 * "comp" is the original statement that "LHS op RHS" is derived from
1421 * and is used for diagnostics.
1423 * If the comparison is of the form
1425 * a <= min(b,c)
1427 * then the expression is constructed as the conjunction of
1428 * the comparisons
1430 * a <= b and a <= c
1432 * A similar optimization is performed for max(a,b) <= c.
1433 * We do this because that will lead to simpler representations
1434 * of the expression.
1435 * If isl is ever enhanced to explicitly deal with min and max expressions,
1436 * this optimization can be removed.
1438 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperatorKind op,
1439 Expr *LHS, Expr *RHS, Stmt *comp)
1441 isl_pw_aff *lhs;
1442 isl_pw_aff *rhs;
1443 isl_pw_aff *res;
1444 isl_set *cond;
1445 isl_set *dom;
1446 enum pet_op_type type;
1448 if (op == BO_GT)
1449 return extract_comparison(BO_LT, RHS, LHS, comp);
1450 if (op == BO_GE)
1451 return extract_comparison(BO_LE, RHS, LHS, comp);
1453 if (op == BO_LT || op == BO_LE) {
1454 Expr *expr1, *expr2;
1455 if (is_min(RHS, expr1, expr2)) {
1456 lhs = extract_comparison(op, LHS, expr1, comp);
1457 rhs = extract_comparison(op, LHS, expr2, comp);
1458 return pet_and(lhs, rhs);
1460 if (is_max(LHS, expr1, expr2)) {
1461 lhs = extract_comparison(op, expr1, RHS, comp);
1462 rhs = extract_comparison(op, expr2, RHS, comp);
1463 return pet_and(lhs, rhs);
1467 lhs = extract_affine(LHS);
1468 rhs = extract_affine(RHS);
1470 type = BinaryOperatorKind2pet_op_type(op);
1471 return pet_comparison(type, lhs, rhs);
1474 __isl_give isl_pw_aff *PetScan::extract_comparison(BinaryOperator *comp)
1476 return extract_comparison(comp->getOpcode(), comp->getLHS(),
1477 comp->getRHS(), comp);
1480 /* Extract an affine expression from a boolean expression.
1481 * In particular, return the expression "expr ? 1 : 0".
1482 * Return NULL if we are unable to extract an affine expression.
1484 * We first convert the clang::Expr to a pet_expr and
1485 * then extract an affine expression from that pet_expr.
1487 __isl_give isl_pw_aff *PetScan::extract_condition(Expr *expr)
1489 isl_pw_aff *cond;
1490 pet_expr *pe;
1491 pet_context *pc;
1493 if (!expr) {
1494 isl_set *u = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
1495 return indicator_function(u, isl_set_copy(u));
1498 pe = extract_expr(expr);
1499 pc = convert_assignments(ctx, assigned_value);
1500 pc = pet_context_set_allow_nested(pc, nesting_enabled);
1501 cond = pet_expr_extract_affine_condition(pe, pc);
1502 if (isl_pw_aff_involves_nan(cond))
1503 cond = isl_pw_aff_free(cond);
1504 pet_context_free(pc);
1505 pet_expr_free(pe);
1506 return cond;
1509 /* Construct a pet_expr representing a unary operator expression.
1511 __isl_give pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1513 pet_expr *arg;
1514 enum pet_op_type op;
1516 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1517 if (op == pet_op_last) {
1518 unsupported(expr);
1519 return NULL;
1522 arg = extract_expr(expr->getSubExpr());
1524 if (expr->isIncrementDecrementOp() &&
1525 pet_expr_get_type(arg) == pet_expr_access) {
1526 arg = mark_write(arg);
1527 arg = pet_expr_access_set_read(arg, 1);
1530 return pet_expr_new_unary(op, arg);
1533 /* Mark the given access pet_expr as a write.
1534 * If a scalar is being accessed, then mark its value
1535 * as unknown in assigned_value.
1537 __isl_give pet_expr *PetScan::mark_write(__isl_take pet_expr *access)
1539 isl_id *id;
1540 ValueDecl *decl;
1542 access = pet_expr_access_set_write(access, 1);
1543 access = pet_expr_access_set_read(access, 0);
1545 if (!access || !pet_expr_is_scalar_access(access))
1546 return access;
1548 id = pet_expr_access_get_id(access);
1549 decl = (ValueDecl *) isl_id_get_user(id);
1550 clear_assignment(assigned_value, decl);
1551 isl_id_free(id);
1553 return access;
1556 /* Assign "rhs" to "lhs".
1558 * In particular, if "lhs" is a scalar variable, then mark
1559 * the variable as having been assigned. If, furthermore, "rhs"
1560 * is an affine expression, then keep track of this value in assigned_value
1561 * so that we can plug it in when we later come across the same variable.
1563 void PetScan::assign(__isl_keep pet_expr *lhs, Expr *rhs)
1565 isl_id *id;
1566 ValueDecl *decl;
1567 isl_pw_aff *pa;
1569 if (!lhs)
1570 return;
1571 if (!pet_expr_is_scalar_access(lhs))
1572 return;
1574 id = pet_expr_access_get_id(lhs);
1575 decl = (ValueDecl *) isl_id_get_user(id);
1576 isl_id_free(id);
1578 pa = try_extract_affine(rhs);
1579 clear_assignment(assigned_value, decl);
1580 if (!pa)
1581 return;
1582 assigned_value[decl] = pa;
1583 insert_expression(pa);
1586 /* Construct a pet_expr representing a binary operator expression.
1588 * If the top level operator is an assignment and the LHS is an access,
1589 * then we mark that access as a write. If the operator is a compound
1590 * assignment, the access is marked as both a read and a write.
1592 * If "expr" assigns something to a scalar variable, then we mark
1593 * the variable as having been assigned. If, furthermore, the expression
1594 * is affine, then keep track of this value in assigned_value
1595 * so that we can plug it in when we later come across the same variable.
1597 __isl_give pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1599 int type_size;
1600 pet_expr *lhs, *rhs;
1601 enum pet_op_type op;
1603 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1604 if (op == pet_op_last) {
1605 unsupported(expr);
1606 return NULL;
1609 lhs = extract_expr(expr->getLHS());
1610 rhs = extract_expr(expr->getRHS());
1612 if (expr->isAssignmentOp() &&
1613 pet_expr_get_type(lhs) == pet_expr_access) {
1614 lhs = mark_write(lhs);
1615 if (expr->isCompoundAssignmentOp())
1616 lhs = pet_expr_access_set_read(lhs, 1);
1619 if (expr->getOpcode() == BO_Assign)
1620 assign(lhs, expr->getRHS());
1622 type_size = get_type_size(expr->getType(), ast_context);
1623 return pet_expr_new_binary(type_size, op, lhs, rhs);
1626 /* Construct a pet_scop with a single statement killing the entire
1627 * array "array".
1629 struct pet_scop *PetScan::kill(Stmt *stmt, struct pet_array *array)
1631 isl_id *id;
1632 isl_space *space;
1633 isl_multi_pw_aff *index;
1634 isl_map *access;
1635 pet_expr *expr;
1637 if (!array)
1638 return NULL;
1639 access = isl_map_from_range(isl_set_copy(array->extent));
1640 id = isl_set_get_tuple_id(array->extent);
1641 space = isl_space_alloc(ctx, 0, 0, 0);
1642 space = isl_space_set_tuple_id(space, isl_dim_out, id);
1643 index = isl_multi_pw_aff_zero(space);
1644 expr = pet_expr_kill_from_access_and_index(access, index);
1645 return extract(expr, stmt->getSourceRange(), false);
1648 /* Construct a pet_scop for a (single) variable declaration.
1650 * The scop contains the variable being declared (as an array)
1651 * and a statement killing the array.
1653 * If the variable is initialized in the AST, then the scop
1654 * also contains an assignment to the variable.
1656 struct pet_scop *PetScan::extract(DeclStmt *stmt)
1658 int type_size;
1659 Decl *decl;
1660 VarDecl *vd;
1661 pet_expr *lhs, *rhs, *pe;
1662 struct pet_scop *scop_decl, *scop;
1663 struct pet_array *array;
1665 if (!stmt->isSingleDecl()) {
1666 unsupported(stmt);
1667 return NULL;
1670 decl = stmt->getSingleDecl();
1671 vd = cast<VarDecl>(decl);
1673 array = extract_array(ctx, vd, NULL);
1674 if (array)
1675 array->declared = 1;
1676 scop_decl = kill(stmt, array);
1677 scop_decl = pet_scop_add_array(scop_decl, array);
1679 if (!vd->getInit())
1680 return scop_decl;
1682 lhs = extract_access_expr(vd);
1683 rhs = extract_expr(vd->getInit());
1685 lhs = mark_write(lhs);
1686 assign(lhs, vd->getInit());
1688 type_size = get_type_size(vd->getType(), ast_context);
1689 pe = pet_expr_new_binary(type_size, pet_op_assign, lhs, rhs);
1690 scop = extract(pe, stmt->getSourceRange(), false);
1692 scop_decl = pet_scop_prefix(scop_decl, 0);
1693 scop = pet_scop_prefix(scop, 1);
1695 scop = pet_scop_add_seq(ctx, scop_decl, scop);
1697 return scop;
1700 /* Construct a pet_expr representing a conditional operation.
1702 * We first try to extract the condition as an affine expression.
1703 * If that fails, we construct a pet_expr tree representing the condition.
1705 __isl_give pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1707 pet_expr *cond, *lhs, *rhs;
1708 isl_pw_aff *pa;
1710 pa = try_extract_affine(expr->getCond());
1711 if (pa) {
1712 isl_multi_pw_aff *test = isl_multi_pw_aff_from_pw_aff(pa);
1713 cond = pet_expr_from_index(test);
1714 } else
1715 cond = extract_expr(expr->getCond());
1716 lhs = extract_expr(expr->getTrueExpr());
1717 rhs = extract_expr(expr->getFalseExpr());
1719 return pet_expr_new_ternary(cond, lhs, rhs);
1722 __isl_give pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1724 return extract_expr(expr->getSubExpr());
1727 /* Construct a pet_expr representing a floating point value.
1729 * If the floating point literal does not appear in a macro,
1730 * then we use the original representation in the source code
1731 * as the string representation. Otherwise, we use the pretty
1732 * printer to produce a string representation.
1734 __isl_give pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1736 double d;
1737 string s;
1738 const LangOptions &LO = PP.getLangOpts();
1739 SourceLocation loc = expr->getLocation();
1741 if (!loc.isMacroID()) {
1742 SourceManager &SM = PP.getSourceManager();
1743 unsigned len = Lexer::MeasureTokenLength(loc, SM, LO);
1744 s = string(SM.getCharacterData(loc), len);
1745 } else {
1746 llvm::raw_string_ostream S(s);
1747 expr->printPretty(S, 0, PrintingPolicy(LO));
1748 S.str();
1750 d = expr->getValueAsApproximateDouble();
1751 return pet_expr_new_double(ctx, d, s.c_str());
1754 /* Convert the index expression "index" into an access pet_expr of type "qt".
1756 __isl_give pet_expr *PetScan::extract_access_expr(QualType qt,
1757 __isl_take isl_multi_pw_aff *index)
1759 pet_expr *pe;
1760 int depth;
1761 int type_size;
1763 depth = extract_depth(index);
1764 type_size = get_type_size(qt, ast_context);
1766 pe = pet_expr_from_index_and_depth(type_size, index, depth);
1768 return pe;
1771 /* Extract an index expression from "expr" and then convert it into
1772 * an access pet_expr.
1774 __isl_give pet_expr *PetScan::extract_access_expr(Expr *expr)
1776 return extract_access_expr(expr->getType(), extract_index(expr));
1779 /* Extract an index expression from "decl" and then convert it into
1780 * an access pet_expr.
1782 __isl_give pet_expr *PetScan::extract_access_expr(ValueDecl *decl)
1784 return extract_access_expr(decl->getType(), extract_index(decl));
1787 __isl_give pet_expr *PetScan::extract_expr(ParenExpr *expr)
1789 return extract_expr(expr->getSubExpr());
1792 /* Extract an assume statement from the argument "expr"
1793 * of a __pencil_assume statement.
1795 __isl_give pet_expr *PetScan::extract_assume(Expr *expr)
1797 isl_pw_aff *cond;
1798 pet_expr *res;
1800 cond = try_extract_affine_condition(expr);
1801 if (!cond) {
1802 res = extract_expr(expr);
1803 } else {
1804 isl_multi_pw_aff *index;
1805 index = isl_multi_pw_aff_from_pw_aff(cond);
1806 res = pet_expr_from_index(index);
1808 return pet_expr_new_unary(pet_op_assume, res);
1811 /* Construct a pet_expr corresponding to the function call argument "expr".
1812 * The argument appears in position "pos" of a call to function "fd".
1814 * If we are passing along a pointer to an array element
1815 * or an entire row or even higher dimensional slice of an array,
1816 * then the function being called may write into the array.
1818 * We assume here that if the function is declared to take a pointer
1819 * to a const type, then the function will perform a read
1820 * and that otherwise, it will perform a write.
1822 __isl_give pet_expr *PetScan::extract_argument(FunctionDecl *fd, int pos,
1823 Expr *expr)
1825 pet_expr *res;
1826 int is_addr = 0, is_partial = 0;
1827 Stmt::StmtClass sc;
1829 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
1830 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(expr);
1831 expr = ice->getSubExpr();
1833 if (expr->getStmtClass() == Stmt::UnaryOperatorClass) {
1834 UnaryOperator *op = cast<UnaryOperator>(expr);
1835 if (op->getOpcode() == UO_AddrOf) {
1836 is_addr = 1;
1837 expr = op->getSubExpr();
1840 res = extract_expr(expr);
1841 if (!res)
1842 return NULL;
1843 sc = expr->getStmtClass();
1844 if ((sc == Stmt::ArraySubscriptExprClass ||
1845 sc == Stmt::MemberExprClass) &&
1846 array_depth(expr->getType().getTypePtr()) > 0)
1847 is_partial = 1;
1848 if ((is_addr || is_partial) &&
1849 pet_expr_get_type(res) == pet_expr_access) {
1850 ParmVarDecl *parm;
1851 if (!fd->hasPrototype()) {
1852 report_prototype_required(expr);
1853 return pet_expr_free(res);
1855 parm = fd->getParamDecl(pos);
1856 if (!const_base(parm->getType()))
1857 res = mark_write(res);
1860 if (is_addr)
1861 res = pet_expr_new_unary(pet_op_address_of, res);
1862 return res;
1865 /* Construct a pet_expr representing a function call.
1867 * In the special case of a "call" to __pencil_assume,
1868 * construct an assume expression instead.
1870 __isl_give pet_expr *PetScan::extract_expr(CallExpr *expr)
1872 pet_expr *res = NULL;
1873 FunctionDecl *fd;
1874 string name;
1875 unsigned n_arg;
1877 fd = expr->getDirectCallee();
1878 if (!fd) {
1879 unsupported(expr);
1880 return NULL;
1883 name = fd->getDeclName().getAsString();
1884 n_arg = expr->getNumArgs();
1886 if (n_arg == 1 && name == "__pencil_assume")
1887 return extract_assume(expr->getArg(0));
1889 res = pet_expr_new_call(ctx, name.c_str(), n_arg);
1890 if (!res)
1891 return NULL;
1893 for (int i = 0; i < n_arg; ++i) {
1894 Expr *arg = expr->getArg(i);
1895 res = pet_expr_set_arg(res, i,
1896 PetScan::extract_argument(fd, i, arg));
1899 return res;
1902 /* Construct a pet_expr representing a (C style) cast.
1904 __isl_give pet_expr *PetScan::extract_expr(CStyleCastExpr *expr)
1906 pet_expr *arg;
1907 QualType type;
1909 arg = extract_expr(expr->getSubExpr());
1910 if (!arg)
1911 return NULL;
1913 type = expr->getTypeAsWritten();
1914 return pet_expr_new_cast(type.getAsString().c_str(), arg);
1917 /* Construct a pet_expr representing an integer.
1919 __isl_give pet_expr *PetScan::extract_expr(IntegerLiteral *expr)
1921 return pet_expr_new_int(extract_int(expr));
1924 /* Try and construct a pet_expr representing "expr".
1926 __isl_give pet_expr *PetScan::extract_expr(Expr *expr)
1928 switch (expr->getStmtClass()) {
1929 case Stmt::UnaryOperatorClass:
1930 return extract_expr(cast<UnaryOperator>(expr));
1931 case Stmt::CompoundAssignOperatorClass:
1932 case Stmt::BinaryOperatorClass:
1933 return extract_expr(cast<BinaryOperator>(expr));
1934 case Stmt::ImplicitCastExprClass:
1935 return extract_expr(cast<ImplicitCastExpr>(expr));
1936 case Stmt::ArraySubscriptExprClass:
1937 case Stmt::DeclRefExprClass:
1938 case Stmt::MemberExprClass:
1939 return extract_access_expr(expr);
1940 case Stmt::IntegerLiteralClass:
1941 return extract_expr(cast<IntegerLiteral>(expr));
1942 case Stmt::FloatingLiteralClass:
1943 return extract_expr(cast<FloatingLiteral>(expr));
1944 case Stmt::ParenExprClass:
1945 return extract_expr(cast<ParenExpr>(expr));
1946 case Stmt::ConditionalOperatorClass:
1947 return extract_expr(cast<ConditionalOperator>(expr));
1948 case Stmt::CallExprClass:
1949 return extract_expr(cast<CallExpr>(expr));
1950 case Stmt::CStyleCastExprClass:
1951 return extract_expr(cast<CStyleCastExpr>(expr));
1952 default:
1953 unsupported(expr);
1955 return NULL;
1958 /* Check if the given initialization statement is an assignment.
1959 * If so, return that assignment. Otherwise return NULL.
1961 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1963 BinaryOperator *ass;
1965 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1966 return NULL;
1968 ass = cast<BinaryOperator>(init);
1969 if (ass->getOpcode() != BO_Assign)
1970 return NULL;
1972 return ass;
1975 /* Check if the given initialization statement is a declaration
1976 * of a single variable.
1977 * If so, return that declaration. Otherwise return NULL.
1979 Decl *PetScan::initialization_declaration(Stmt *init)
1981 DeclStmt *decl;
1983 if (init->getStmtClass() != Stmt::DeclStmtClass)
1984 return NULL;
1986 decl = cast<DeclStmt>(init);
1988 if (!decl->isSingleDecl())
1989 return NULL;
1991 return decl->getSingleDecl();
1994 /* Given the assignment operator in the initialization of a for loop,
1995 * extract the induction variable, i.e., the (integer)variable being
1996 * assigned.
1998 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
2000 Expr *lhs;
2001 DeclRefExpr *ref;
2002 ValueDecl *decl;
2003 const Type *type;
2005 lhs = init->getLHS();
2006 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2007 unsupported(init);
2008 return NULL;
2011 ref = cast<DeclRefExpr>(lhs);
2012 decl = ref->getDecl();
2013 type = decl->getType().getTypePtr();
2015 if (!type->isIntegerType()) {
2016 unsupported(lhs);
2017 return NULL;
2020 return decl;
2023 /* Given the initialization statement of a for loop and the single
2024 * declaration in this initialization statement,
2025 * extract the induction variable, i.e., the (integer) variable being
2026 * declared.
2028 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
2030 VarDecl *vd;
2032 vd = cast<VarDecl>(decl);
2034 const QualType type = vd->getType();
2035 if (!type->isIntegerType()) {
2036 unsupported(init);
2037 return NULL;
2040 if (!vd->getInit()) {
2041 unsupported(init);
2042 return NULL;
2045 return vd;
2048 /* Check that op is of the form iv++ or iv--.
2049 * Return an affine expression "1" or "-1" accordingly.
2051 __isl_give isl_pw_aff *PetScan::extract_unary_increment(
2052 clang::UnaryOperator *op, clang::ValueDecl *iv)
2054 Expr *sub;
2055 DeclRefExpr *ref;
2056 isl_space *space;
2057 isl_aff *aff;
2059 if (!op->isIncrementDecrementOp()) {
2060 unsupported(op);
2061 return NULL;
2064 sub = op->getSubExpr();
2065 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
2066 unsupported(op);
2067 return NULL;
2070 ref = cast<DeclRefExpr>(sub);
2071 if (ref->getDecl() != iv) {
2072 unsupported(op);
2073 return NULL;
2076 space = isl_space_set_alloc(ctx, 0, 0);
2077 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2079 if (op->isIncrementOp())
2080 aff = isl_aff_add_constant_si(aff, 1);
2081 else
2082 aff = isl_aff_add_constant_si(aff, -1);
2084 return isl_pw_aff_from_aff(aff);
2087 /* Check if op is of the form
2089 * iv = iv + inc
2091 * and return inc as an affine expression.
2093 * We extract an affine expression from the RHS, subtract iv and return
2094 * the result.
2096 __isl_give isl_pw_aff *PetScan::extract_binary_increment(BinaryOperator *op,
2097 clang::ValueDecl *iv)
2099 Expr *lhs;
2100 DeclRefExpr *ref;
2101 isl_id *id;
2102 isl_space *space;
2103 isl_aff *aff;
2104 isl_pw_aff *val;
2106 if (op->getOpcode() != BO_Assign) {
2107 unsupported(op);
2108 return NULL;
2111 lhs = op->getLHS();
2112 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2113 unsupported(op);
2114 return NULL;
2117 ref = cast<DeclRefExpr>(lhs);
2118 if (ref->getDecl() != iv) {
2119 unsupported(op);
2120 return NULL;
2123 val = extract_affine(op->getRHS());
2125 id = create_decl_id(ctx, iv);
2127 space = isl_space_set_alloc(ctx, 1, 0);
2128 space = isl_space_set_dim_id(space, isl_dim_param, 0, id);
2129 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2130 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2132 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
2134 return val;
2137 /* Check that op is of the form iv += cst or iv -= cst
2138 * and return an affine expression corresponding oto cst or -cst accordingly.
2140 __isl_give isl_pw_aff *PetScan::extract_compound_increment(
2141 CompoundAssignOperator *op, clang::ValueDecl *iv)
2143 Expr *lhs;
2144 DeclRefExpr *ref;
2145 bool neg = false;
2146 isl_pw_aff *val;
2147 BinaryOperatorKind opcode;
2149 opcode = op->getOpcode();
2150 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
2151 unsupported(op);
2152 return NULL;
2154 if (opcode == BO_SubAssign)
2155 neg = true;
2157 lhs = op->getLHS();
2158 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
2159 unsupported(op);
2160 return NULL;
2163 ref = cast<DeclRefExpr>(lhs);
2164 if (ref->getDecl() != iv) {
2165 unsupported(op);
2166 return NULL;
2169 val = extract_affine(op->getRHS());
2170 if (neg)
2171 val = isl_pw_aff_neg(val);
2173 return val;
2176 /* Check that the increment of the given for loop increments
2177 * (or decrements) the induction variable "iv" and return
2178 * the increment as an affine expression if successful.
2180 __isl_give isl_pw_aff *PetScan::extract_increment(clang::ForStmt *stmt,
2181 ValueDecl *iv)
2183 Stmt *inc = stmt->getInc();
2185 if (!inc) {
2186 report_missing_increment(stmt);
2187 return NULL;
2190 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
2191 return extract_unary_increment(cast<UnaryOperator>(inc), iv);
2192 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
2193 return extract_compound_increment(
2194 cast<CompoundAssignOperator>(inc), iv);
2195 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
2196 return extract_binary_increment(cast<BinaryOperator>(inc), iv);
2198 unsupported(inc);
2199 return NULL;
2202 /* Embed the given iteration domain in an extra outer loop
2203 * with induction variable "var".
2204 * If this variable appeared as a parameter in the constraints,
2205 * it is replaced by the new outermost dimension.
2207 static __isl_give isl_set *embed(__isl_take isl_set *set,
2208 __isl_take isl_id *var)
2210 int pos;
2212 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
2213 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
2214 if (pos >= 0) {
2215 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
2216 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2219 isl_id_free(var);
2220 return set;
2223 /* Return those elements in the space of "cond" that come after
2224 * (based on "sign") an element in "cond".
2226 static __isl_give isl_set *after(__isl_take isl_set *cond, int sign)
2228 isl_map *previous_to_this;
2230 if (sign > 0)
2231 previous_to_this = isl_map_lex_lt(isl_set_get_space(cond));
2232 else
2233 previous_to_this = isl_map_lex_gt(isl_set_get_space(cond));
2235 cond = isl_set_apply(cond, previous_to_this);
2237 return cond;
2240 /* Create the infinite iteration domain
2242 * { [id] : id >= 0 }
2244 * If "scop" has an affine skip of type pet_skip_later,
2245 * then remove those iterations i that have an earlier iteration
2246 * where the skip condition is satisfied, meaning that iteration i
2247 * is not executed.
2248 * Since we are dealing with a loop without loop iterator,
2249 * the skip condition cannot refer to the current loop iterator and
2250 * so effectively, the returned set is of the form
2252 * { [0]; [id] : id >= 1 and not skip }
2254 static __isl_give isl_set *infinite_domain(__isl_take isl_id *id,
2255 struct pet_scop *scop)
2257 isl_ctx *ctx = isl_id_get_ctx(id);
2258 isl_set *domain;
2259 isl_set *skip;
2261 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
2262 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, id);
2264 if (!pet_scop_has_affine_skip(scop, pet_skip_later))
2265 return domain;
2267 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
2268 skip = embed(skip, isl_id_copy(id));
2269 skip = isl_set_intersect(skip , isl_set_copy(domain));
2270 domain = isl_set_subtract(domain, after(skip, 1));
2272 return domain;
2275 /* Create an identity affine expression on the space containing "domain",
2276 * which is assumed to be one-dimensional.
2278 static __isl_give isl_aff *identity_aff(__isl_keep isl_set *domain)
2280 isl_local_space *ls;
2282 ls = isl_local_space_from_space(isl_set_get_space(domain));
2283 return isl_aff_var_on_domain(ls, isl_dim_set, 0);
2286 /* Create an affine expression that maps elements
2287 * of a single-dimensional array "id_test" to the previous element
2288 * (according to "inc"), provided this element belongs to "domain".
2289 * That is, create the affine expression
2291 * { id[x] -> id[x - inc] : x - inc in domain }
2293 static __isl_give isl_multi_pw_aff *map_to_previous(__isl_take isl_id *id_test,
2294 __isl_take isl_set *domain, __isl_take isl_val *inc)
2296 isl_space *space;
2297 isl_local_space *ls;
2298 isl_aff *aff;
2299 isl_multi_pw_aff *prev;
2301 space = isl_set_get_space(domain);
2302 ls = isl_local_space_from_space(space);
2303 aff = isl_aff_var_on_domain(ls, isl_dim_set, 0);
2304 aff = isl_aff_add_constant_val(aff, isl_val_neg(inc));
2305 prev = isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
2306 domain = isl_set_preimage_multi_pw_aff(domain,
2307 isl_multi_pw_aff_copy(prev));
2308 prev = isl_multi_pw_aff_intersect_domain(prev, domain);
2309 prev = isl_multi_pw_aff_set_tuple_id(prev, isl_dim_out, id_test);
2311 return prev;
2314 /* Add an implication to "scop" expressing that if an element of
2315 * virtual array "id_test" has value "satisfied" then all previous elements
2316 * of this array also have that value. The set of previous elements
2317 * is bounded by "domain". If "sign" is negative then the iterator
2318 * is decreasing and we express that all subsequent array elements
2319 * (but still defined previously) have the same value.
2321 static struct pet_scop *add_implication(struct pet_scop *scop,
2322 __isl_take isl_id *id_test, __isl_take isl_set *domain, int sign,
2323 int satisfied)
2325 isl_space *space;
2326 isl_map *map;
2328 domain = isl_set_set_tuple_id(domain, id_test);
2329 space = isl_set_get_space(domain);
2330 if (sign > 0)
2331 map = isl_map_lex_ge(space);
2332 else
2333 map = isl_map_lex_le(space);
2334 map = isl_map_intersect_range(map, domain);
2335 scop = pet_scop_add_implication(scop, map, satisfied);
2337 return scop;
2340 /* Add a filter to "scop" that imposes that it is only executed
2341 * when the variable identified by "id_test" has a zero value
2342 * for all previous iterations of "domain".
2344 * In particular, add a filter that imposes that the array
2345 * has a zero value at the previous iteration of domain and
2346 * add an implication that implies that it then has that
2347 * value for all previous iterations.
2349 static struct pet_scop *scop_add_break(struct pet_scop *scop,
2350 __isl_take isl_id *id_test, __isl_take isl_set *domain,
2351 __isl_take isl_val *inc)
2353 isl_multi_pw_aff *prev;
2354 int sign = isl_val_sgn(inc);
2356 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2357 scop = add_implication(scop, id_test, domain, sign, 0);
2358 scop = pet_scop_filter(scop, prev, 0);
2360 return scop;
2363 /* Construct a pet_scop for an infinite loop around the given body.
2365 * We extract a pet_scop for the body and then embed it in a loop with
2366 * iteration domain
2368 * { [t] : t >= 0 }
2370 * and schedule
2372 * { [t] -> [t] }
2374 * If the body contains any break, then it is taken into
2375 * account in infinite_domain (if the skip condition is affine)
2376 * or in scop_add_break (if the skip condition is not affine).
2378 * If we were only able to extract part of the body, then simply
2379 * return that part.
2381 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
2383 isl_id *id, *id_test;
2384 isl_set *domain;
2385 isl_aff *ident;
2386 struct pet_scop *scop;
2387 bool has_var_break;
2389 scop = extract(body);
2390 if (!scop)
2391 return NULL;
2392 if (partial)
2393 return scop;
2395 id = isl_id_alloc(ctx, "t", NULL);
2396 domain = infinite_domain(isl_id_copy(id), scop);
2397 ident = identity_aff(domain);
2399 has_var_break = pet_scop_has_var_skip(scop, pet_skip_later);
2400 if (has_var_break)
2401 id_test = pet_scop_get_skip_id(scop, pet_skip_later);
2403 scop = pet_scop_embed(scop, isl_set_copy(domain),
2404 isl_aff_copy(ident), ident, id);
2405 if (has_var_break)
2406 scop = scop_add_break(scop, id_test, domain, isl_val_one(ctx));
2407 else
2408 isl_set_free(domain);
2410 return scop;
2413 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
2415 * for (;;)
2416 * body
2419 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
2421 clear_assignments clear(assigned_value);
2422 clear.TraverseStmt(stmt->getBody());
2424 return extract_infinite_loop(stmt->getBody());
2427 /* Add an array with the given extent (range of "index") to the list
2428 * of arrays in "scop" and return the extended pet_scop.
2429 * The array is marked as attaining values 0 and 1 only and
2430 * as each element being assigned at most once.
2432 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2433 __isl_keep isl_multi_pw_aff *index, clang::ASTContext &ast_ctx)
2435 int int_size = ast_ctx.getTypeInfo(ast_ctx.IntTy).first / 8;
2437 return pet_scop_add_boolean_array(scop, isl_multi_pw_aff_copy(index),
2438 int_size);
2441 /* Construct a pet_scop for a while loop of the form
2443 * while (pa)
2444 * body
2446 * In particular, construct a scop for an infinite loop around body and
2447 * intersect the domain with the affine expression.
2448 * Note that this intersection may result in an empty loop.
2450 struct pet_scop *PetScan::extract_affine_while(__isl_take isl_pw_aff *pa,
2451 Stmt *body)
2453 struct pet_scop *scop;
2454 isl_set *dom;
2455 isl_set *valid;
2457 valid = isl_pw_aff_domain(isl_pw_aff_copy(pa));
2458 dom = isl_pw_aff_non_zero_set(pa);
2459 scop = extract_infinite_loop(body);
2460 scop = pet_scop_restrict(scop, isl_set_params(dom));
2461 scop = pet_scop_restrict_context(scop, isl_set_params(valid));
2463 return scop;
2466 /* Construct a scop for a while, given the scops for the condition
2467 * and the body, the filter identifier and the iteration domain of
2468 * the while loop.
2470 * In particular, the scop for the condition is filtered to depend
2471 * on "id_test" evaluating to true for all previous iterations
2472 * of the loop, while the scop for the body is filtered to depend
2473 * on "id_test" evaluating to true for all iterations up to the
2474 * current iteration.
2475 * The actual filter only imposes that this virtual array has
2476 * value one on the previous or the current iteration.
2477 * The fact that this condition also applies to the previous
2478 * iterations is enforced by an implication.
2480 * These filtered scops are then combined into a single scop.
2482 * "sign" is positive if the iterator increases and negative
2483 * if it decreases.
2485 static struct pet_scop *scop_add_while(struct pet_scop *scop_cond,
2486 struct pet_scop *scop_body, __isl_take isl_id *id_test,
2487 __isl_take isl_set *domain, __isl_take isl_val *inc)
2489 isl_ctx *ctx = isl_set_get_ctx(domain);
2490 isl_space *space;
2491 isl_multi_pw_aff *test_index;
2492 isl_multi_pw_aff *prev;
2493 int sign = isl_val_sgn(inc);
2494 struct pet_scop *scop;
2496 prev = map_to_previous(isl_id_copy(id_test), isl_set_copy(domain), inc);
2497 scop_cond = pet_scop_filter(scop_cond, prev, 1);
2499 space = isl_space_map_from_set(isl_set_get_space(domain));
2500 test_index = isl_multi_pw_aff_identity(space);
2501 test_index = isl_multi_pw_aff_set_tuple_id(test_index, isl_dim_out,
2502 isl_id_copy(id_test));
2503 scop_body = pet_scop_filter(scop_body, test_index, 1);
2505 scop = pet_scop_add_seq(ctx, scop_cond, scop_body);
2506 scop = add_implication(scop, id_test, domain, sign, 1);
2508 return scop;
2511 /* Check if the while loop is of the form
2513 * while (affine expression)
2514 * body
2516 * If so, call extract_affine_while to construct a scop.
2518 * Otherwise, extract the body and pass control to extract_while
2519 * to extend the iteration domain with an infinite loop.
2520 * If we were only able to extract part of the body, then simply
2521 * return that part.
2523 struct pet_scop *PetScan::extract(WhileStmt *stmt)
2525 Expr *cond;
2526 int test_nr, stmt_nr;
2527 isl_pw_aff *pa;
2528 struct pet_scop *scop_body;
2530 cond = stmt->getCond();
2531 if (!cond) {
2532 unsupported(stmt);
2533 return NULL;
2536 clear_assignments clear(assigned_value);
2537 clear.TraverseStmt(stmt->getBody());
2539 pa = try_extract_affine_condition(cond);
2540 if (pa)
2541 return extract_affine_while(pa, stmt->getBody());
2543 if (!allow_nested) {
2544 unsupported(stmt);
2545 return NULL;
2548 test_nr = n_test++;
2549 stmt_nr = n_stmt++;
2550 scop_body = extract(stmt->getBody());
2551 if (partial)
2552 return scop_body;
2554 return extract_while(cond, test_nr, stmt_nr, scop_body);
2557 /* Construct a generic while scop, with iteration domain
2558 * { [t] : t >= 0 } around "scop_body". The scop consists of two parts,
2559 * one for evaluating the condition "cond" and one for the body.
2560 * "test_nr" is the sequence number of the virtual test variable that contains
2561 * the result of the condition and "stmt_nr" is the sequence number
2562 * of the statement that evaluates the condition.
2563 * The schedule is adjusted to reflect that the condition is evaluated
2564 * before the body is executed and the body is filtered to depend
2565 * on the result of the condition evaluating to true on all iterations
2566 * up to the current iteration, while the evaluation of the condition itself
2567 * is filtered to depend on the result of the condition evaluating to true
2568 * on all previous iterations.
2569 * The context of the scop representing the body is dropped
2570 * because we don't know how many times the body will be executed,
2571 * if at all.
2573 * If the body contains any break, then it is taken into
2574 * account in infinite_domain (if the skip condition is affine)
2575 * or in scop_add_break (if the skip condition is not affine).
2577 struct pet_scop *PetScan::extract_while(Expr *cond, int test_nr, int stmt_nr,
2578 struct pet_scop *scop_body)
2580 isl_id *id, *id_test, *id_break_test;
2581 isl_set *domain;
2582 isl_aff *ident;
2583 isl_multi_pw_aff *test_index;
2584 struct pet_scop *scop;
2585 bool has_var_break;
2587 test_index = pet_create_test_index(ctx, test_nr);
2588 scop = extract_non_affine_condition(cond, stmt_nr,
2589 isl_multi_pw_aff_copy(test_index));
2590 scop = scop_add_array(scop, test_index, ast_context);
2591 id_test = isl_multi_pw_aff_get_tuple_id(test_index, isl_dim_out);
2592 isl_multi_pw_aff_free(test_index);
2594 id = isl_id_alloc(ctx, "t", NULL);
2595 domain = infinite_domain(isl_id_copy(id), scop_body);
2596 ident = identity_aff(domain);
2598 has_var_break = pet_scop_has_var_skip(scop_body, pet_skip_later);
2599 if (has_var_break)
2600 id_break_test = pet_scop_get_skip_id(scop_body, pet_skip_later);
2602 scop = pet_scop_prefix(scop, 0);
2603 scop = pet_scop_embed(scop, isl_set_copy(domain), isl_aff_copy(ident),
2604 isl_aff_copy(ident), isl_id_copy(id));
2605 scop_body = pet_scop_reset_context(scop_body);
2606 scop_body = pet_scop_prefix(scop_body, 1);
2607 scop_body = pet_scop_embed(scop_body, isl_set_copy(domain),
2608 isl_aff_copy(ident), ident, id);
2610 if (has_var_break) {
2611 scop = scop_add_break(scop, isl_id_copy(id_break_test),
2612 isl_set_copy(domain), isl_val_one(ctx));
2613 scop_body = scop_add_break(scop_body, id_break_test,
2614 isl_set_copy(domain), isl_val_one(ctx));
2616 scop = scop_add_while(scop, scop_body, id_test, domain,
2617 isl_val_one(ctx));
2619 return scop;
2622 /* Check whether "cond" expresses a simple loop bound
2623 * on the only set dimension.
2624 * In particular, if "up" is set then "cond" should contain only
2625 * upper bounds on the set dimension.
2626 * Otherwise, it should contain only lower bounds.
2628 static bool is_simple_bound(__isl_keep isl_set *cond, __isl_keep isl_val *inc)
2630 if (isl_val_is_pos(inc))
2631 return !isl_set_dim_has_any_lower_bound(cond, isl_dim_set, 0);
2632 else
2633 return !isl_set_dim_has_any_upper_bound(cond, isl_dim_set, 0);
2636 /* Extend a condition on a given iteration of a loop to one that
2637 * imposes the same condition on all previous iterations.
2638 * "domain" expresses the lower [upper] bound on the iterations
2639 * when inc is positive [negative].
2641 * In particular, we construct the condition (when inc is positive)
2643 * forall i' : (domain(i') and i' <= i) => cond(i')
2645 * which is equivalent to
2647 * not exists i' : domain(i') and i' <= i and not cond(i')
2649 * We construct this set by negating cond, applying a map
2651 * { [i'] -> [i] : domain(i') and i' <= i }
2653 * and then negating the result again.
2655 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
2656 __isl_take isl_set *domain, __isl_take isl_val *inc)
2658 isl_map *previous_to_this;
2660 if (isl_val_is_pos(inc))
2661 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
2662 else
2663 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
2665 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
2667 cond = isl_set_complement(cond);
2668 cond = isl_set_apply(cond, previous_to_this);
2669 cond = isl_set_complement(cond);
2671 isl_val_free(inc);
2673 return cond;
2676 /* Construct a domain of the form
2678 * [id] -> { : exists a: id = init + a * inc and a >= 0 }
2680 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
2681 __isl_take isl_pw_aff *init, __isl_take isl_val *inc)
2683 isl_aff *aff;
2684 isl_space *dim;
2685 isl_set *set;
2687 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
2688 dim = isl_pw_aff_get_domain_space(init);
2689 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2690 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, 0, inc);
2691 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
2693 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
2694 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
2695 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2696 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
2698 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
2700 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
2702 return isl_set_params(set);
2705 /* Assuming "cond" represents a bound on a loop where the loop
2706 * iterator "iv" is incremented (or decremented) by one, check if wrapping
2707 * is possible.
2709 * Under the given assumptions, wrapping is only possible if "cond" allows
2710 * for the last value before wrapping, i.e., 2^width - 1 in case of an
2711 * increasing iterator and 0 in case of a decreasing iterator.
2713 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv,
2714 __isl_keep isl_val *inc)
2716 bool cw;
2717 isl_ctx *ctx;
2718 isl_val *limit;
2719 isl_set *test;
2721 test = isl_set_copy(cond);
2723 ctx = isl_set_get_ctx(test);
2724 if (isl_val_is_neg(inc))
2725 limit = isl_val_zero(ctx);
2726 else {
2727 limit = isl_val_int_from_ui(ctx, get_type_size(iv));
2728 limit = isl_val_2exp(limit);
2729 limit = isl_val_sub_ui(limit, 1);
2732 test = isl_set_fix_val(cond, isl_dim_set, 0, limit);
2733 cw = !isl_set_is_empty(test);
2734 isl_set_free(test);
2736 return cw;
2739 /* Given a one-dimensional space, construct the following affine expression
2740 * on this space
2742 * { [v] -> [v mod 2^width] }
2744 * where width is the number of bits used to represent the values
2745 * of the unsigned variable "iv".
2747 static __isl_give isl_aff *compute_wrapping(__isl_take isl_space *dim,
2748 ValueDecl *iv)
2750 isl_ctx *ctx;
2751 isl_val *mod;
2752 isl_aff *aff;
2754 ctx = isl_space_get_ctx(dim);
2755 mod = isl_val_int_from_ui(ctx, get_type_size(iv));
2756 mod = isl_val_2exp(mod);
2758 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2759 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2760 aff = isl_aff_mod_val(aff, mod);
2762 return aff;
2765 /* Project out the parameter "id" from "set".
2767 static __isl_give isl_set *set_project_out_by_id(__isl_take isl_set *set,
2768 __isl_keep isl_id *id)
2770 int pos;
2772 pos = isl_set_find_dim_by_id(set, isl_dim_param, id);
2773 if (pos >= 0)
2774 set = isl_set_project_out(set, isl_dim_param, pos, 1);
2776 return set;
2779 /* Compute the set of parameters for which "set1" is a subset of "set2".
2781 * set1 is a subset of set2 if
2783 * forall i in set1 : i in set2
2785 * or
2787 * not exists i in set1 and i not in set2
2789 * i.e.,
2791 * not exists i in set1 \ set2
2793 static __isl_give isl_set *enforce_subset(__isl_take isl_set *set1,
2794 __isl_take isl_set *set2)
2796 return isl_set_complement(isl_set_params(isl_set_subtract(set1, set2)));
2799 /* Compute the set of parameter values for which "cond" holds
2800 * on the next iteration for each element of "dom".
2802 * We first construct mapping { [i] -> [i + inc] }, apply that to "dom"
2803 * and then compute the set of parameters for which the result is a subset
2804 * of "cond".
2806 static __isl_give isl_set *valid_on_next(__isl_take isl_set *cond,
2807 __isl_take isl_set *dom, __isl_take isl_val *inc)
2809 isl_space *space;
2810 isl_aff *aff;
2811 isl_map *next;
2813 space = isl_set_get_space(dom);
2814 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2815 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2816 aff = isl_aff_add_constant_val(aff, inc);
2817 next = isl_map_from_basic_map(isl_basic_map_from_aff(aff));
2819 dom = isl_set_apply(dom, next);
2821 return enforce_subset(dom, cond);
2824 /* Construct a pet_scop for a for statement.
2825 * The for loop is required to be of the form
2827 * for (i = init; condition; ++i)
2829 * or
2831 * for (i = init; condition; --i)
2833 * The initialization of the for loop should either be an assignment
2834 * to an integer variable, or a declaration of such a variable with
2835 * initialization.
2837 * The condition is allowed to contain nested accesses, provided
2838 * they are not being written to inside the body of the loop.
2839 * Otherwise, or if the condition is otherwise non-affine, the for loop is
2840 * essentially treated as a while loop, with iteration domain
2841 * { [i] : i >= init }.
2843 * We extract a pet_scop for the body and then embed it in a loop with
2844 * iteration domain and schedule
2846 * { [i] : i >= init and condition' }
2847 * { [i] -> [i] }
2849 * or
2851 * { [i] : i <= init and condition' }
2852 * { [i] -> [-i] }
2854 * Where condition' is equal to condition if the latter is
2855 * a simple upper [lower] bound and a condition that is extended
2856 * to apply to all previous iterations otherwise.
2858 * If the condition is non-affine, then we drop the condition from the
2859 * iteration domain and instead create a separate statement
2860 * for evaluating the condition. The body is then filtered to depend
2861 * on the result of the condition evaluating to true on all iterations
2862 * up to the current iteration, while the evaluation the condition itself
2863 * is filtered to depend on the result of the condition evaluating to true
2864 * on all previous iterations.
2865 * The context of the scop representing the body is dropped
2866 * because we don't know how many times the body will be executed,
2867 * if at all.
2869 * If the stride of the loop is not 1, then "i >= init" is replaced by
2871 * (exists a: i = init + stride * a and a >= 0)
2873 * If the loop iterator i is unsigned, then wrapping may occur.
2874 * We therefore use a virtual iterator instead that does not wrap.
2875 * However, the condition in the code applies
2876 * to the wrapped value, so we need to change condition(i)
2877 * into condition([i % 2^width]). Similarly, we replace all accesses
2878 * to the original iterator by the wrapping of the virtual iterator.
2879 * Note that there may be no need to perform this final wrapping
2880 * if the loop condition (after wrapping) satisfies certain conditions.
2881 * However, the is_simple_bound condition is not enough since it doesn't
2882 * check if there even is an upper bound.
2884 * Wrapping on unsigned iterators can be avoided entirely if
2885 * loop condition is simple, the loop iterator is incremented
2886 * [decremented] by one and the last value before wrapping cannot
2887 * possibly satisfy the loop condition.
2889 * Before extracting a pet_scop from the body we remove all
2890 * assignments in assigned_value to variables that are assigned
2891 * somewhere in the body of the loop.
2893 * Valid parameters for a for loop are those for which the initial
2894 * value itself, the increment on each domain iteration and
2895 * the condition on both the initial value and
2896 * the result of incrementing the iterator for each iteration of the domain
2897 * can be evaluated.
2898 * If the loop condition is non-affine, then we only consider validity
2899 * of the initial value.
2901 * If the body contains any break, then we keep track of it in "skip"
2902 * (if the skip condition is affine) or it is handled in scop_add_break
2903 * (if the skip condition is not affine).
2904 * Note that the affine break condition needs to be considered with
2905 * respect to previous iterations in the virtual domain (if any).
2907 * If we were only able to extract part of the body, then simply
2908 * return that part.
2910 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
2912 BinaryOperator *ass;
2913 Decl *decl;
2914 Stmt *init;
2915 Expr *lhs, *rhs;
2916 ValueDecl *iv;
2917 isl_local_space *ls;
2918 isl_set *domain;
2919 isl_aff *sched;
2920 isl_set *cond = NULL;
2921 isl_set *skip = NULL;
2922 isl_id *id, *id_test = NULL, *id_break_test;
2923 struct pet_scop *scop, *scop_cond = NULL;
2924 assigned_value_cache cache(assigned_value);
2925 isl_val *inc;
2926 bool was_assigned;
2927 bool is_one;
2928 bool is_unsigned;
2929 bool is_simple;
2930 bool is_virtual;
2931 bool has_affine_break;
2932 bool has_var_break;
2933 isl_aff *wrap = NULL;
2934 isl_pw_aff *pa, *pa_inc, *init_val;
2935 isl_set *valid_init;
2936 isl_set *valid_cond;
2937 isl_set *valid_cond_init;
2938 isl_set *valid_cond_next;
2939 isl_set *valid_inc;
2940 int stmt_id;
2942 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
2943 return extract_infinite_for(stmt);
2945 init = stmt->getInit();
2946 if (!init) {
2947 unsupported(stmt);
2948 return NULL;
2950 if ((ass = initialization_assignment(init)) != NULL) {
2951 iv = extract_induction_variable(ass);
2952 if (!iv)
2953 return NULL;
2954 lhs = ass->getLHS();
2955 rhs = ass->getRHS();
2956 } else if ((decl = initialization_declaration(init)) != NULL) {
2957 VarDecl *var = extract_induction_variable(init, decl);
2958 if (!var)
2959 return NULL;
2960 iv = var;
2961 rhs = var->getInit();
2962 lhs = create_DeclRefExpr(var);
2963 } else {
2964 unsupported(stmt->getInit());
2965 return NULL;
2968 assigned_value.erase(iv);
2969 clear_assignments clear(assigned_value);
2970 clear.TraverseStmt(stmt->getBody());
2972 was_assigned = assigned_value.find(iv) != assigned_value.end();
2973 clear_assignment(assigned_value, iv);
2974 init_val = extract_affine(rhs);
2975 if (!was_assigned)
2976 assigned_value.erase(iv);
2977 if (!init_val)
2978 return NULL;
2980 pa_inc = extract_increment(stmt, iv);
2981 if (!pa_inc) {
2982 isl_pw_aff_free(init_val);
2983 return NULL;
2986 inc = pet_extract_cst(pa_inc);
2987 if (!inc || isl_val_is_nan(inc)) {
2988 isl_pw_aff_free(init_val);
2989 isl_pw_aff_free(pa_inc);
2990 unsupported(stmt->getInc());
2991 isl_val_free(inc);
2992 return NULL;
2995 pa = try_extract_nested_condition(stmt->getCond());
2996 if (allow_nested && (!pa || pet_nested_any_in_pw_aff(pa)))
2997 stmt_id = n_stmt++;
2999 scop = extract(stmt->getBody());
3000 if (partial) {
3001 isl_pw_aff_free(init_val);
3002 isl_pw_aff_free(pa_inc);
3003 isl_pw_aff_free(pa);
3004 isl_val_free(inc);
3005 return scop;
3008 valid_inc = isl_pw_aff_domain(pa_inc);
3010 is_unsigned = iv->getType()->isUnsignedIntegerType();
3012 id = create_decl_id(ctx, iv);
3014 has_affine_break = scop &&
3015 pet_scop_has_affine_skip(scop, pet_skip_later);
3016 if (has_affine_break)
3017 skip = pet_scop_get_affine_skip_domain(scop, pet_skip_later);
3018 has_var_break = scop && pet_scop_has_var_skip(scop, pet_skip_later);
3019 if (has_var_break)
3020 id_break_test = pet_scop_get_skip_id(scop, pet_skip_later);
3022 if (pa && !is_nested_allowed(pa, scop)) {
3023 isl_pw_aff_free(pa);
3024 pa = NULL;
3027 if (!allow_nested && !pa)
3028 pa = try_extract_affine_condition(stmt->getCond());
3029 valid_cond = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3030 cond = isl_pw_aff_non_zero_set(pa);
3031 if (allow_nested && !cond) {
3032 isl_multi_pw_aff *test_index;
3033 int save_n_stmt = n_stmt;
3034 test_index = pet_create_test_index(ctx, n_test++);
3035 n_stmt = stmt_id;
3036 scop_cond = extract_non_affine_condition(stmt->getCond(),
3037 n_stmt++, isl_multi_pw_aff_copy(test_index));
3038 n_stmt = save_n_stmt;
3039 scop_cond = scop_add_array(scop_cond, test_index, ast_context);
3040 id_test = isl_multi_pw_aff_get_tuple_id(test_index,
3041 isl_dim_out);
3042 isl_multi_pw_aff_free(test_index);
3043 scop_cond = pet_scop_prefix(scop_cond, 0);
3044 scop = pet_scop_reset_context(scop);
3045 scop = pet_scop_prefix(scop, 1);
3046 cond = isl_set_universe(isl_space_set_alloc(ctx, 0, 0));
3049 cond = embed(cond, isl_id_copy(id));
3050 skip = embed(skip, isl_id_copy(id));
3051 valid_cond = isl_set_coalesce(valid_cond);
3052 valid_cond = embed(valid_cond, isl_id_copy(id));
3053 valid_inc = embed(valid_inc, isl_id_copy(id));
3054 is_one = isl_val_is_one(inc) || isl_val_is_negone(inc);
3055 is_virtual = is_unsigned && (!is_one || can_wrap(cond, iv, inc));
3057 valid_cond_init = enforce_subset(
3058 isl_map_range(isl_map_from_pw_aff(isl_pw_aff_copy(init_val))),
3059 isl_set_copy(valid_cond));
3060 if (is_one && !is_virtual) {
3061 isl_pw_aff_free(init_val);
3062 pa = extract_comparison(isl_val_is_pos(inc) ? BO_GE : BO_LE,
3063 lhs, rhs, init);
3064 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(pa));
3065 valid_init = set_project_out_by_id(valid_init, id);
3066 domain = isl_pw_aff_non_zero_set(pa);
3067 } else {
3068 valid_init = isl_pw_aff_domain(isl_pw_aff_copy(init_val));
3069 domain = strided_domain(isl_id_copy(id), init_val,
3070 isl_val_copy(inc));
3073 domain = embed(domain, isl_id_copy(id));
3074 if (is_virtual) {
3075 isl_map *rev_wrap;
3076 wrap = compute_wrapping(isl_set_get_space(cond), iv);
3077 rev_wrap = isl_map_from_aff(isl_aff_copy(wrap));
3078 rev_wrap = isl_map_reverse(rev_wrap);
3079 cond = isl_set_apply(cond, isl_map_copy(rev_wrap));
3080 skip = isl_set_apply(skip, isl_map_copy(rev_wrap));
3081 valid_cond = isl_set_apply(valid_cond, isl_map_copy(rev_wrap));
3082 valid_inc = isl_set_apply(valid_inc, rev_wrap);
3084 is_simple = is_simple_bound(cond, inc);
3085 if (!is_simple) {
3086 cond = isl_set_gist(cond, isl_set_copy(domain));
3087 is_simple = is_simple_bound(cond, inc);
3089 if (!is_simple)
3090 cond = valid_for_each_iteration(cond,
3091 isl_set_copy(domain), isl_val_copy(inc));
3092 domain = isl_set_intersect(domain, cond);
3093 if (has_affine_break) {
3094 skip = isl_set_intersect(skip , isl_set_copy(domain));
3095 skip = after(skip, isl_val_sgn(inc));
3096 domain = isl_set_subtract(domain, skip);
3098 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
3099 ls = isl_local_space_from_space(isl_set_get_space(domain));
3100 sched = isl_aff_var_on_domain(ls, isl_dim_set, 0);
3101 if (isl_val_is_neg(inc))
3102 sched = isl_aff_neg(sched);
3104 valid_cond_next = valid_on_next(valid_cond, isl_set_copy(domain),
3105 isl_val_copy(inc));
3106 valid_inc = enforce_subset(isl_set_copy(domain), valid_inc);
3108 if (!is_virtual)
3109 wrap = identity_aff(domain);
3111 scop_cond = pet_scop_embed(scop_cond, isl_set_copy(domain),
3112 isl_aff_copy(sched), isl_aff_copy(wrap), isl_id_copy(id));
3113 scop = pet_scop_embed(scop, isl_set_copy(domain), sched, wrap, id);
3114 scop = resolve_nested(scop);
3115 if (has_var_break)
3116 scop = scop_add_break(scop, id_break_test, isl_set_copy(domain),
3117 isl_val_copy(inc));
3118 if (id_test) {
3119 scop = scop_add_while(scop_cond, scop, id_test, domain,
3120 isl_val_copy(inc));
3121 isl_set_free(valid_inc);
3122 } else {
3123 scop = pet_scop_restrict_context(scop, valid_inc);
3124 scop = pet_scop_restrict_context(scop, valid_cond_next);
3125 scop = pet_scop_restrict_context(scop, valid_cond_init);
3126 isl_set_free(domain);
3128 clear_assignment(assigned_value, iv);
3130 isl_val_free(inc);
3132 scop = pet_scop_restrict_context(scop, isl_set_params(valid_init));
3134 return scop;
3137 /* Try and construct a pet_scop corresponding to a compound statement.
3139 * "skip_declarations" is set if we should skip initial declarations
3140 * in the children of the compound statements. This then implies
3141 * that this sequence of children should not be treated as a block
3142 * since the initial statements may be skipped.
3144 struct pet_scop *PetScan::extract(CompoundStmt *stmt, bool skip_declarations)
3146 return extract(stmt->children(), !skip_declarations, skip_declarations);
3149 /* Extract a pet_expr from an isl_id created by either pet_nested_clang_expr or
3150 * pet_nested_pet_expr.
3151 * In the first case, the isl_id has no name and
3152 * the user pointer points to a clang::Expr object.
3153 * In the second case, the isl_id has name "__pet_expr" and
3154 * the user pointer points to a pet_expr object.
3156 __isl_give pet_expr *PetScan::extract_expr(__isl_keep isl_id *id)
3158 if (!isl_id_get_name(id))
3159 return extract_expr((Expr *) isl_id_get_user(id));
3160 else
3161 return pet_expr_copy((pet_expr *) isl_id_get_user(id));
3164 /* For each nested access parameter in "space",
3165 * construct a corresponding pet_expr, place it in args and
3166 * record its position in "param2pos".
3167 * "n_arg" is the number of elements that are already in args.
3168 * The position recorded in "param2pos" takes this number into account.
3169 * If the pet_expr corresponding to a parameter is identical to
3170 * the pet_expr corresponding to an earlier parameter, then these two
3171 * parameters are made to refer to the same element in args.
3173 * Return the final number of elements in args or -1 if an error has occurred.
3175 int PetScan::extract_nested(__isl_keep isl_space *space,
3176 int n_arg, pet_expr **args, std::map<int,int> &param2pos)
3178 int nparam;
3180 nparam = isl_space_dim(space, isl_dim_param);
3181 for (int i = 0; i < nparam; ++i) {
3182 int j;
3183 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3185 if (!pet_nested_in_id(id)) {
3186 isl_id_free(id);
3187 continue;
3190 args[n_arg] = extract_expr(id);
3191 isl_id_free(id);
3192 if (!args[n_arg])
3193 return -1;
3195 for (j = 0; j < n_arg; ++j)
3196 if (pet_expr_is_equal(args[j], args[n_arg]))
3197 break;
3199 if (j < n_arg) {
3200 pet_expr_free(args[n_arg]);
3201 args[n_arg] = NULL;
3202 param2pos[i] = j;
3203 } else
3204 param2pos[i] = n_arg++;
3207 return n_arg;
3210 /* For each nested access parameter in the access relations in "expr",
3211 * construct a corresponding pet_expr, place it in the arguments of "expr"
3212 * and record its position in "param2pos".
3213 * n is the number of nested access parameters.
3215 __isl_give pet_expr *PetScan::extract_nested(__isl_take pet_expr *expr, int n,
3216 std::map<int,int> &param2pos)
3218 isl_space *space;
3219 int i;
3220 pet_expr **args;
3222 args = isl_calloc_array(ctx, pet_expr *, n);
3223 if (!args)
3224 return pet_expr_free(expr);
3226 space = pet_expr_access_get_parameter_space(expr);
3227 n = extract_nested(space, 0, args, param2pos);
3228 isl_space_free(space);
3230 if (n < 0)
3231 expr = pet_expr_free(expr);
3232 else
3233 expr = pet_expr_set_n_arg(expr, n);
3235 for (i = 0; i < n; ++i)
3236 expr = pet_expr_set_arg(expr, i, args[i]);
3237 free(args);
3239 return expr;
3242 /* Look for parameters in any access relation in "expr" that
3243 * refer to nested accesses. In particular, these are
3244 * parameters with either no name or with name "__pet_expr".
3246 * If there are any such parameters, then the domain of the index
3247 * expression and the access relation, which is still [] at this point,
3248 * is replaced by [[] -> [t_1,...,t_n]], with n the number of these parameters
3249 * (after identifying identical nested accesses).
3251 * This transformation is performed in several steps.
3252 * We first extract the arguments in extract_nested.
3253 * param2pos maps the original parameter position to the position
3254 * of the argument.
3255 * Then we move these parameters to input dimensions.
3256 * t2pos maps the positions of these temporary input dimensions
3257 * to the positions of the corresponding arguments.
3258 * Finally, we express these temporary dimensions in terms of the domain
3259 * [[] -> [t_1,...,t_n]] and precompose index expression and access
3260 * relations with this function.
3262 __isl_give pet_expr *PetScan::resolve_nested(__isl_take pet_expr *expr)
3264 int n;
3265 int nparam;
3266 isl_space *space;
3267 isl_local_space *ls;
3268 isl_aff *aff;
3269 isl_multi_aff *ma;
3270 std::map<int,int> param2pos;
3271 std::map<int,int> t2pos;
3273 if (!expr)
3274 return expr;
3276 n = pet_expr_get_n_arg(expr);
3277 for (int i = 0; i < n; ++i) {
3278 pet_expr *arg;
3279 arg = pet_expr_get_arg(expr, i);
3280 arg = resolve_nested(arg);
3281 expr = pet_expr_set_arg(expr, i, arg);
3284 if (pet_expr_get_type(expr) != pet_expr_access)
3285 return expr;
3287 space = pet_expr_access_get_parameter_space(expr);
3288 n = pet_nested_n_in_space(space);
3289 isl_space_free(space);
3290 if (n == 0)
3291 return expr;
3293 expr = extract_nested(expr, n, param2pos);
3294 if (!expr)
3295 return NULL;
3297 expr = pet_expr_access_align_params(expr);
3298 if (!expr)
3299 return NULL;
3301 n = 0;
3302 space = pet_expr_access_get_parameter_space(expr);
3303 nparam = isl_space_dim(space, isl_dim_param);
3304 for (int i = nparam - 1; i >= 0; --i) {
3305 isl_id *id = isl_space_get_dim_id(space, isl_dim_param, i);
3306 if (!pet_nested_in_id(id)) {
3307 isl_id_free(id);
3308 continue;
3311 expr = pet_expr_access_move_dims(expr,
3312 isl_dim_in, n, isl_dim_param, i, 1);
3313 t2pos[n] = param2pos[i];
3314 n++;
3316 isl_id_free(id);
3318 isl_space_free(space);
3320 space = pet_expr_access_get_parameter_space(expr);
3321 space = isl_space_set_from_params(space);
3322 space = isl_space_add_dims(space, isl_dim_set,
3323 pet_expr_get_n_arg(expr));
3324 space = isl_space_wrap(isl_space_from_range(space));
3325 ls = isl_local_space_from_space(isl_space_copy(space));
3326 space = isl_space_from_domain(space);
3327 space = isl_space_add_dims(space, isl_dim_out, n);
3328 ma = isl_multi_aff_zero(space);
3330 for (int i = 0; i < n; ++i) {
3331 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3332 isl_dim_set, t2pos[i]);
3333 ma = isl_multi_aff_set_aff(ma, i, aff);
3335 isl_local_space_free(ls);
3337 expr = pet_expr_access_pullback_multi_aff(expr, ma);
3339 return expr;
3342 /* Return the file offset of the expansion location of "Loc".
3344 static unsigned getExpansionOffset(SourceManager &SM, SourceLocation Loc)
3346 return SM.getFileOffset(SM.getExpansionLoc(Loc));
3349 #ifdef HAVE_FINDLOCATIONAFTERTOKEN
3351 /* Return a SourceLocation for the location after the first semicolon
3352 * after "loc". If Lexer::findLocationAfterToken is available, we simply
3353 * call it and also skip trailing spaces and newline.
3355 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3356 const LangOptions &LO)
3358 return Lexer::findLocationAfterToken(loc, tok::semi, SM, LO, true);
3361 #else
3363 /* Return a SourceLocation for the location after the first semicolon
3364 * after "loc". If Lexer::findLocationAfterToken is not available,
3365 * we look in the underlying character data for the first semicolon.
3367 static SourceLocation location_after_semi(SourceLocation loc, SourceManager &SM,
3368 const LangOptions &LO)
3370 const char *semi;
3371 const char *s = SM.getCharacterData(loc);
3373 semi = strchr(s, ';');
3374 if (!semi)
3375 return SourceLocation();
3376 return loc.getFileLocWithOffset(semi + 1 - s);
3379 #endif
3381 /* If the token at "loc" is the first token on the line, then return
3382 * a location referring to the start of the line.
3383 * Otherwise, return "loc".
3385 * This function is used to extend a scop to the start of the line
3386 * if the first token of the scop is also the first token on the line.
3388 * We look for the first token on the line. If its location is equal to "loc",
3389 * then the latter is the location of the first token on the line.
3391 static SourceLocation move_to_start_of_line_if_first_token(SourceLocation loc,
3392 SourceManager &SM, const LangOptions &LO)
3394 std::pair<FileID, unsigned> file_offset_pair;
3395 llvm::StringRef file;
3396 const char *pos;
3397 Token tok;
3398 SourceLocation token_loc, line_loc;
3399 int col;
3401 loc = SM.getExpansionLoc(loc);
3402 col = SM.getExpansionColumnNumber(loc);
3403 line_loc = loc.getLocWithOffset(1 - col);
3404 file_offset_pair = SM.getDecomposedLoc(line_loc);
3405 file = SM.getBufferData(file_offset_pair.first, NULL);
3406 pos = file.data() + file_offset_pair.second;
3408 Lexer lexer(SM.getLocForStartOfFile(file_offset_pair.first), LO,
3409 file.begin(), pos, file.end());
3410 lexer.LexFromRawLexer(tok);
3411 token_loc = tok.getLocation();
3413 if (token_loc == loc)
3414 return line_loc;
3415 else
3416 return loc;
3419 /* Update start and end of "scop" to include the region covered by "range".
3420 * If "skip_semi" is set, then we assume "range" is followed by
3421 * a semicolon and also include this semicolon.
3423 struct pet_scop *PetScan::update_scop_start_end(struct pet_scop *scop,
3424 SourceRange range, bool skip_semi)
3426 SourceLocation loc = range.getBegin();
3427 SourceManager &SM = PP.getSourceManager();
3428 const LangOptions &LO = PP.getLangOpts();
3429 unsigned start, end;
3431 loc = move_to_start_of_line_if_first_token(loc, SM, LO);
3432 start = getExpansionOffset(SM, loc);
3433 loc = range.getEnd();
3434 if (skip_semi)
3435 loc = location_after_semi(loc, SM, LO);
3436 else
3437 loc = PP.getLocForEndOfToken(loc);
3438 end = getExpansionOffset(SM, loc);
3440 scop = pet_scop_update_start_end(scop, start, end);
3441 return scop;
3444 /* Convert a top-level pet_expr to a pet_scop with one statement.
3445 * This mainly involves resolving nested expression parameters
3446 * and setting the name of the iteration space.
3447 * The name is given by "label" if it is non-NULL. Otherwise,
3448 * it is of the form S_<n_stmt>.
3449 * start and end of the pet_scop are derived from "range" and "skip_semi".
3450 * In particular, if "skip_semi" is set then the semicolon following "range"
3451 * is also included.
3453 struct pet_scop *PetScan::extract(__isl_take pet_expr *expr, SourceRange range,
3454 bool skip_semi, __isl_take isl_id *label)
3456 struct pet_stmt *ps;
3457 struct pet_scop *scop;
3458 SourceLocation loc = range.getBegin();
3459 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3461 expr = resolve_nested(expr);
3462 ps = pet_stmt_from_pet_expr(line, label, n_stmt++, expr);
3463 scop = pet_scop_from_pet_stmt(ctx, ps);
3465 scop = update_scop_start_end(scop, range, skip_semi);
3466 return scop;
3469 /* Check if we can extract an affine expression from "expr".
3470 * Return the expressions as an isl_pw_aff if we can and NULL otherwise.
3471 * We turn on autodetection so that we won't generate any warnings
3472 * and turn off nesting, so that we won't accept any non-affine constructs.
3474 __isl_give isl_pw_aff *PetScan::try_extract_affine(Expr *expr)
3476 isl_pw_aff *pwaff;
3477 int save_autodetect = options->autodetect;
3478 bool save_nesting = nesting_enabled;
3480 options->autodetect = 1;
3481 nesting_enabled = false;
3483 pwaff = extract_affine(expr);
3485 options->autodetect = save_autodetect;
3486 nesting_enabled = save_nesting;
3488 return pwaff;
3491 /* Check if we can extract an affine constraint from "expr".
3492 * Return the constraint as an isl_set if we can and NULL otherwise.
3493 * We turn on autodetection so that we won't generate any warnings
3494 * and turn off nesting, so that we won't accept any non-affine constructs.
3496 __isl_give isl_pw_aff *PetScan::try_extract_affine_condition(Expr *expr)
3498 isl_pw_aff *cond;
3499 int save_autodetect = options->autodetect;
3500 bool save_nesting = nesting_enabled;
3502 options->autodetect = 1;
3503 nesting_enabled = false;
3505 cond = extract_condition(expr);
3507 options->autodetect = save_autodetect;
3508 nesting_enabled = save_nesting;
3510 return cond;
3513 /* Check whether "expr" is an affine constraint.
3515 bool PetScan::is_affine_condition(Expr *expr)
3517 isl_pw_aff *cond;
3519 cond = try_extract_affine_condition(expr);
3520 isl_pw_aff_free(cond);
3522 return cond != NULL;
3525 /* Check if we can extract a condition from "expr".
3526 * Return the condition as an isl_pw_aff if we can and NULL otherwise.
3527 * If allow_nested is set, then the condition may involve parameters
3528 * corresponding to nested accesses.
3529 * We turn on autodetection so that we won't generate any warnings.
3531 __isl_give isl_pw_aff *PetScan::try_extract_nested_condition(Expr *expr)
3533 isl_pw_aff *cond;
3534 int save_autodetect = options->autodetect;
3535 bool save_nesting = nesting_enabled;
3537 options->autodetect = 1;
3538 nesting_enabled = allow_nested;
3539 cond = extract_condition(expr);
3541 options->autodetect = save_autodetect;
3542 nesting_enabled = save_nesting;
3544 return cond;
3547 /* If the top-level expression of "stmt" is an assignment, then
3548 * return that assignment as a BinaryOperator.
3549 * Otherwise return NULL.
3551 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
3553 BinaryOperator *ass;
3555 if (!stmt)
3556 return NULL;
3557 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
3558 return NULL;
3560 ass = cast<BinaryOperator>(stmt);
3561 if(ass->getOpcode() != BO_Assign)
3562 return NULL;
3564 return ass;
3567 /* Check if the given if statement is a conditional assignement
3568 * with a non-affine condition. If so, construct a pet_scop
3569 * corresponding to this conditional assignment. Otherwise return NULL.
3571 * In particular we check if "stmt" is of the form
3573 * if (condition)
3574 * a = f(...);
3575 * else
3576 * a = g(...);
3578 * where a is some array or scalar access.
3579 * The constructed pet_scop then corresponds to the expression
3581 * a = condition ? f(...) : g(...)
3583 * All access relations in f(...) are intersected with condition
3584 * while all access relation in g(...) are intersected with the complement.
3586 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
3588 BinaryOperator *ass_then, *ass_else;
3589 isl_multi_pw_aff *write_then, *write_else;
3590 isl_set *cond, *comp;
3591 isl_multi_pw_aff *index;
3592 isl_pw_aff *pa;
3593 int equal;
3594 int type_size;
3595 pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
3596 bool save_nesting = nesting_enabled;
3598 if (!options->detect_conditional_assignment)
3599 return NULL;
3601 ass_then = top_assignment_or_null(stmt->getThen());
3602 ass_else = top_assignment_or_null(stmt->getElse());
3604 if (!ass_then || !ass_else)
3605 return NULL;
3607 if (is_affine_condition(stmt->getCond()))
3608 return NULL;
3610 write_then = extract_index(ass_then->getLHS());
3611 write_else = extract_index(ass_else->getLHS());
3613 equal = isl_multi_pw_aff_plain_is_equal(write_then, write_else);
3614 isl_multi_pw_aff_free(write_else);
3615 if (equal < 0 || !equal) {
3616 isl_multi_pw_aff_free(write_then);
3617 return NULL;
3620 nesting_enabled = allow_nested;
3621 pa = extract_condition(stmt->getCond());
3622 nesting_enabled = save_nesting;
3623 cond = isl_pw_aff_non_zero_set(isl_pw_aff_copy(pa));
3624 comp = isl_pw_aff_zero_set(isl_pw_aff_copy(pa));
3625 index = isl_multi_pw_aff_from_pw_aff(pa);
3627 pe_cond = pet_expr_from_index(index);
3629 pe_then = extract_expr(ass_then->getRHS());
3630 pe_then = pet_expr_restrict(pe_then, cond);
3631 pe_else = extract_expr(ass_else->getRHS());
3632 pe_else = pet_expr_restrict(pe_else, comp);
3634 pe = pet_expr_new_ternary(pe_cond, pe_then, pe_else);
3635 type_size = get_type_size(ass_then->getType(), ast_context);
3636 pe_write = pet_expr_from_index_and_depth(type_size, write_then,
3637 extract_depth(write_then));
3638 pe_write = pet_expr_access_set_write(pe_write, 1);
3639 pe_write = pet_expr_access_set_read(pe_write, 0);
3640 pe = pet_expr_new_binary(type_size, pet_op_assign, pe_write, pe);
3641 return extract(pe, stmt->getSourceRange(), false);
3644 /* Create a pet_scop with a single statement with name S_<stmt_nr>,
3645 * evaluating "cond" and writing the result to a virtual scalar,
3646 * as expressed by "index".
3648 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond, int stmt_nr,
3649 __isl_take isl_multi_pw_aff *index)
3651 pet_expr *expr, *write;
3652 struct pet_stmt *ps;
3653 SourceLocation loc = cond->getLocStart();
3654 int line = PP.getSourceManager().getExpansionLineNumber(loc);
3656 write = pet_expr_from_index(index);
3657 write = pet_expr_access_set_write(write, 1);
3658 write = pet_expr_access_set_read(write, 0);
3659 expr = extract_expr(cond);
3660 expr = resolve_nested(expr);
3661 expr = pet_expr_new_binary(1, pet_op_assign, write, expr);
3662 ps = pet_stmt_from_pet_expr(line, NULL, stmt_nr, expr);
3663 return pet_scop_from_pet_stmt(ctx, ps);
3666 extern "C" {
3667 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr,
3668 void *user);
3671 /* Precompose the access relation and the index expression associated
3672 * to "expr" with the function pointed to by "user",
3673 * thereby embedding the access relation in the domain of this function.
3674 * The initial domain of the access relation and the index expression
3675 * is the zero-dimensional domain.
3677 static __isl_give pet_expr *embed_access(__isl_take pet_expr *expr, void *user)
3679 isl_multi_aff *ma = (isl_multi_aff *) user;
3681 return pet_expr_access_pullback_multi_aff(expr, isl_multi_aff_copy(ma));
3684 /* Precompose all access relations in "expr" with "ma", thereby
3685 * embedding them in the domain of "ma".
3687 static __isl_give pet_expr *embed(__isl_take pet_expr *expr,
3688 __isl_keep isl_multi_aff *ma)
3690 return pet_expr_map_access(expr, &embed_access, ma);
3693 /* For each nested access parameter in the domain of "stmt",
3694 * construct a corresponding pet_expr, place it before the original
3695 * elements in stmt->args and record its position in "param2pos".
3696 * n is the number of nested access parameters.
3698 struct pet_stmt *PetScan::extract_nested(struct pet_stmt *stmt, int n,
3699 std::map<int,int> &param2pos)
3701 int i;
3702 isl_space *space;
3703 int n_arg;
3704 pet_expr **args;
3706 n_arg = stmt->n_arg;
3707 args = isl_calloc_array(ctx, pet_expr *, n + n_arg);
3708 if (!args)
3709 goto error;
3711 space = isl_set_get_space(stmt->domain);
3712 n_arg = extract_nested(space, 0, args, param2pos);
3713 isl_space_free(space);
3715 if (n_arg < 0)
3716 goto error;
3718 for (i = 0; i < stmt->n_arg; ++i)
3719 args[n_arg + i] = stmt->args[i];
3720 free(stmt->args);
3721 stmt->args = args;
3722 stmt->n_arg += n_arg;
3724 return stmt;
3725 error:
3726 if (args) {
3727 for (i = 0; i < n; ++i)
3728 pet_expr_free(args[i]);
3729 free(args);
3731 pet_stmt_free(stmt);
3732 return NULL;
3735 /* Check whether any of the arguments i of "stmt" starting at position "n"
3736 * is equal to one of the first "n" arguments j.
3737 * If so, combine the constraints on arguments i and j and remove
3738 * argument i.
3740 static struct pet_stmt *remove_duplicate_arguments(struct pet_stmt *stmt, int n)
3742 int i, j;
3743 isl_map *map;
3745 if (!stmt)
3746 return NULL;
3747 if (n == 0)
3748 return stmt;
3749 if (n == stmt->n_arg)
3750 return stmt;
3752 map = isl_set_unwrap(stmt->domain);
3754 for (i = stmt->n_arg - 1; i >= n; --i) {
3755 for (j = 0; j < n; ++j)
3756 if (pet_expr_is_equal(stmt->args[i], stmt->args[j]))
3757 break;
3758 if (j >= n)
3759 continue;
3761 map = isl_map_equate(map, isl_dim_out, i, isl_dim_out, j);
3762 map = isl_map_project_out(map, isl_dim_out, i, 1);
3764 pet_expr_free(stmt->args[i]);
3765 for (j = i; j + 1 < stmt->n_arg; ++j)
3766 stmt->args[j] = stmt->args[j + 1];
3767 stmt->n_arg--;
3770 stmt->domain = isl_map_wrap(map);
3771 if (!stmt->domain)
3772 goto error;
3773 return stmt;
3774 error:
3775 pet_stmt_free(stmt);
3776 return NULL;
3779 /* Look for parameters in the iteration domain of "stmt" that
3780 * refer to nested accesses. In particular, these are
3781 * parameters with either no name or with name "__pet_expr".
3783 * If there are any such parameters, then as many extra variables
3784 * (after identifying identical nested accesses) are inserted in the
3785 * range of the map wrapped inside the domain, before the original variables.
3786 * If the original domain is not a wrapped map, then a new wrapped
3787 * map is created with zero output dimensions.
3788 * The parameters are then equated to the corresponding output dimensions
3789 * and subsequently projected out, from the iteration domain,
3790 * the schedule and the access relations.
3791 * For each of the output dimensions, a corresponding argument
3792 * expression is inserted. Initially they are created with
3793 * a zero-dimensional domain, so they have to be embedded
3794 * in the current iteration domain.
3795 * param2pos maps the position of the parameter to the position
3796 * of the corresponding output dimension in the wrapped map.
3798 struct pet_stmt *PetScan::resolve_nested(struct pet_stmt *stmt)
3800 int n;
3801 int nparam;
3802 unsigned n_arg;
3803 isl_map *map;
3804 isl_space *space;
3805 isl_multi_aff *ma;
3806 std::map<int,int> param2pos;
3808 if (!stmt)
3809 return NULL;
3811 n = pet_nested_n_in_set(stmt->domain);
3812 if (n == 0)
3813 return stmt;
3815 n_arg = stmt->n_arg;
3816 stmt = extract_nested(stmt, n, param2pos);
3817 if (!stmt)
3818 return NULL;
3820 n = stmt->n_arg - n_arg;
3821 nparam = isl_set_dim(stmt->domain, isl_dim_param);
3822 if (isl_set_is_wrapping(stmt->domain))
3823 map = isl_set_unwrap(stmt->domain);
3824 else
3825 map = isl_map_from_domain(stmt->domain);
3826 map = isl_map_insert_dims(map, isl_dim_out, 0, n);
3828 for (int i = nparam - 1; i >= 0; --i) {
3829 isl_id *id;
3831 if (!pet_nested_in_map(map, i))
3832 continue;
3834 id = pet_expr_access_get_id(stmt->args[param2pos[i]]);
3835 map = isl_map_set_dim_id(map, isl_dim_out, param2pos[i], id);
3836 map = isl_map_equate(map, isl_dim_param, i, isl_dim_out,
3837 param2pos[i]);
3838 map = isl_map_project_out(map, isl_dim_param, i, 1);
3841 stmt->domain = isl_map_wrap(map);
3843 space = isl_space_unwrap(isl_set_get_space(stmt->domain));
3844 space = isl_space_from_domain(isl_space_domain(space));
3845 ma = isl_multi_aff_zero(space);
3846 for (int pos = 0; pos < n; ++pos)
3847 stmt->args[pos] = embed(stmt->args[pos], ma);
3848 isl_multi_aff_free(ma);
3850 stmt = pet_stmt_remove_nested_parameters(stmt);
3851 stmt = remove_duplicate_arguments(stmt, n);
3853 return stmt;
3856 /* For each statement in "scop", move the parameters that correspond
3857 * to nested access into the ranges of the domains and create
3858 * corresponding argument expressions.
3860 struct pet_scop *PetScan::resolve_nested(struct pet_scop *scop)
3862 if (!scop)
3863 return NULL;
3865 for (int i = 0; i < scop->n_stmt; ++i) {
3866 scop->stmts[i] = resolve_nested(scop->stmts[i]);
3867 if (!scop->stmts[i])
3868 goto error;
3871 return scop;
3872 error:
3873 pet_scop_free(scop);
3874 return NULL;
3877 /* Given an access expression "expr", is the variable accessed by
3878 * "expr" assigned anywhere inside "scop"?
3880 static bool is_assigned(__isl_keep pet_expr *expr, pet_scop *scop)
3882 bool assigned = false;
3883 isl_id *id;
3885 id = pet_expr_access_get_id(expr);
3886 assigned = pet_scop_writes(scop, id);
3887 isl_id_free(id);
3889 return assigned;
3892 /* Are all nested access parameters in "pa" allowed given "scop".
3893 * In particular, is none of them written by anywhere inside "scop".
3895 * If "scop" has any skip conditions, then no nested access parameters
3896 * are allowed. In particular, if there is any nested access in a guard
3897 * for a piece of code containing a "continue", then we want to introduce
3898 * a separate statement for evaluating this guard so that we can express
3899 * that the result is false for all previous iterations.
3901 bool PetScan::is_nested_allowed(__isl_keep isl_pw_aff *pa, pet_scop *scop)
3903 int nparam;
3905 if (!scop)
3906 return true;
3908 if (!pet_nested_any_in_pw_aff(pa))
3909 return true;
3911 if (pet_scop_has_skip(scop, pet_skip_now))
3912 return false;
3914 nparam = isl_pw_aff_dim(pa, isl_dim_param);
3915 for (int i = 0; i < nparam; ++i) {
3916 isl_id *id = isl_pw_aff_get_dim_id(pa, isl_dim_param, i);
3917 pet_expr *expr;
3918 bool allowed;
3920 if (!pet_nested_in_id(id)) {
3921 isl_id_free(id);
3922 continue;
3925 expr = extract_expr(id);
3926 allowed = pet_expr_get_type(expr) == pet_expr_access &&
3927 !is_assigned(expr, scop);
3929 pet_expr_free(expr);
3930 isl_id_free(id);
3932 if (!allowed)
3933 return false;
3936 return true;
3939 /* Construct a pet_scop for a non-affine if statement.
3941 * We create a separate statement that writes the result
3942 * of the non-affine condition to a virtual scalar.
3943 * A constraint requiring the value of this virtual scalar to be one
3944 * is added to the iteration domains of the then branch.
3945 * Similarly, a constraint requiring the value of this virtual scalar
3946 * to be zero is added to the iteration domains of the else branch, if any.
3947 * We adjust the schedules to ensure that the virtual scalar is written
3948 * before it is read.
3950 * If there are any breaks or continues in the then and/or else
3951 * branches, then we may have to compute a new skip condition.
3952 * This is handled using a pet_skip_info object.
3953 * On initialization, the object checks if skip conditions need
3954 * to be computed. If so, it does so in pet_skip_info_if_extract_index and
3955 * adds them in pet_skip_info_if_add.
3957 struct pet_scop *PetScan::extract_non_affine_if(Expr *cond,
3958 struct pet_scop *scop_then, struct pet_scop *scop_else,
3959 bool have_else, int stmt_id)
3961 struct pet_scop *scop;
3962 isl_multi_pw_aff *test_index;
3963 int int_size;
3964 int save_n_stmt = n_stmt;
3966 test_index = pet_create_test_index(ctx, n_test++);
3967 n_stmt = stmt_id;
3968 scop = extract_non_affine_condition(cond, n_stmt++,
3969 isl_multi_pw_aff_copy(test_index));
3970 n_stmt = save_n_stmt;
3971 scop = scop_add_array(scop, test_index, ast_context);
3973 pet_skip_info skip;
3974 pet_skip_info_if_init(&skip, ctx, scop_then, scop_else, have_else, 0);
3975 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
3976 pet_skip_info_if_extract_index(&skip, test_index, int_size,
3977 &n_stmt, &n_test);
3979 scop = pet_scop_prefix(scop, 0);
3980 scop_then = pet_scop_prefix(scop_then, 1);
3981 scop_then = pet_scop_filter(scop_then,
3982 isl_multi_pw_aff_copy(test_index), 1);
3983 if (have_else) {
3984 scop_else = pet_scop_prefix(scop_else, 1);
3985 scop_else = pet_scop_filter(scop_else, test_index, 0);
3986 scop_then = pet_scop_add_par(ctx, scop_then, scop_else);
3987 } else
3988 isl_multi_pw_aff_free(test_index);
3990 scop = pet_scop_add_seq(ctx, scop, scop_then);
3992 scop = pet_skip_info_if_add(&skip, scop, 2);
3994 return scop;
3997 /* Construct a pet_scop for an if statement.
3999 * If the condition fits the pattern of a conditional assignment,
4000 * then it is handled by extract_conditional_assignment.
4001 * Otherwise, we do the following.
4003 * If the condition is affine, then the condition is added
4004 * to the iteration domains of the then branch, while the
4005 * opposite of the condition in added to the iteration domains
4006 * of the else branch, if any.
4007 * We allow the condition to be dynamic, i.e., to refer to
4008 * scalars or array elements that may be written to outside
4009 * of the given if statement. These nested accesses are then represented
4010 * as output dimensions in the wrapping iteration domain.
4011 * If it is also written _inside_ the then or else branch, then
4012 * we treat the condition as non-affine.
4013 * As explained in extract_non_affine_if, this will introduce
4014 * an extra statement.
4015 * For aesthetic reasons, we want this statement to have a statement
4016 * number that is lower than those of the then and else branches.
4017 * In order to evaluate if we will need such a statement, however, we
4018 * first construct scops for the then and else branches.
4019 * We therefore reserve a statement number if we might have to
4020 * introduce such an extra statement.
4022 * If the condition is not affine, then the scop is created in
4023 * extract_non_affine_if.
4025 * If there are any breaks or continues in the then and/or else
4026 * branches, then we may have to compute a new skip condition.
4027 * This is handled using a pet_skip_info object.
4028 * On initialization, the object checks if skip conditions need
4029 * to be computed. If so, it does so in pet_skip_info_if_extract_cond and
4030 * adds them in pet_skip_info_if_add.
4032 struct pet_scop *PetScan::extract(IfStmt *stmt)
4034 struct pet_scop *scop_then, *scop_else = NULL, *scop;
4035 isl_pw_aff *cond;
4036 int stmt_id;
4037 int int_size;
4038 isl_set *set;
4039 isl_set *valid;
4041 clear_assignments clear(assigned_value);
4042 clear.TraverseStmt(stmt->getThen());
4043 if (stmt->getElse())
4044 clear.TraverseStmt(stmt->getElse());
4046 scop = extract_conditional_assignment(stmt);
4047 if (scop)
4048 return scop;
4050 cond = try_extract_nested_condition(stmt->getCond());
4051 if (allow_nested && (!cond || pet_nested_any_in_pw_aff(cond)))
4052 stmt_id = n_stmt++;
4055 assigned_value_cache cache(assigned_value);
4056 scop_then = extract(stmt->getThen());
4059 if (stmt->getElse()) {
4060 assigned_value_cache cache(assigned_value);
4061 scop_else = extract(stmt->getElse());
4062 if (options->autodetect) {
4063 if (scop_then && !scop_else) {
4064 partial = true;
4065 isl_pw_aff_free(cond);
4066 return scop_then;
4068 if (!scop_then && scop_else) {
4069 partial = true;
4070 isl_pw_aff_free(cond);
4071 return scop_else;
4076 if (cond &&
4077 (!is_nested_allowed(cond, scop_then) ||
4078 (stmt->getElse() && !is_nested_allowed(cond, scop_else)))) {
4079 isl_pw_aff_free(cond);
4080 cond = NULL;
4082 if (allow_nested && !cond)
4083 return extract_non_affine_if(stmt->getCond(), scop_then,
4084 scop_else, stmt->getElse(), stmt_id);
4086 if (!cond)
4087 cond = extract_condition(stmt->getCond());
4089 pet_skip_info skip;
4090 pet_skip_info_if_init(&skip, ctx, scop_then, scop_else,
4091 stmt->getElse() != NULL, 1);
4092 pet_skip_info_if_extract_cond(&skip, cond, int_size, &n_stmt, &n_test);
4094 valid = isl_pw_aff_domain(isl_pw_aff_copy(cond));
4095 set = isl_pw_aff_non_zero_set(cond);
4096 scop = pet_scop_restrict(scop_then, isl_set_params(isl_set_copy(set)));
4098 if (stmt->getElse()) {
4099 set = isl_set_subtract(isl_set_copy(valid), set);
4100 scop_else = pet_scop_restrict(scop_else, isl_set_params(set));
4101 scop = pet_scop_add_par(ctx, scop, scop_else);
4102 } else
4103 isl_set_free(set);
4104 scop = resolve_nested(scop);
4105 scop = pet_scop_restrict_context(scop, isl_set_params(valid));
4107 if (pet_skip_info_has_skip(&skip))
4108 scop = pet_scop_prefix(scop, 0);
4109 scop = pet_skip_info_if_add(&skip, scop, 1);
4111 return scop;
4114 /* Try and construct a pet_scop for a label statement.
4115 * We currently only allow labels on expression statements.
4117 struct pet_scop *PetScan::extract(LabelStmt *stmt)
4119 isl_id *label;
4120 Stmt *sub;
4122 sub = stmt->getSubStmt();
4123 if (!isa<Expr>(sub)) {
4124 unsupported(stmt);
4125 return NULL;
4128 label = isl_id_alloc(ctx, stmt->getName(), NULL);
4130 return extract(extract_expr(cast<Expr>(sub)), stmt->getSourceRange(),
4131 true, label);
4134 /* Return a one-dimensional multi piecewise affine expression that is equal
4135 * to the constant 1 and is defined over a zero-dimensional domain.
4137 static __isl_give isl_multi_pw_aff *one_mpa(isl_ctx *ctx)
4139 isl_space *space;
4140 isl_local_space *ls;
4141 isl_aff *aff;
4143 space = isl_space_set_alloc(ctx, 0, 0);
4144 ls = isl_local_space_from_space(space);
4145 aff = isl_aff_zero_on_domain(ls);
4146 aff = isl_aff_set_constant_si(aff, 1);
4148 return isl_multi_pw_aff_from_pw_aff(isl_pw_aff_from_aff(aff));
4151 /* Construct a pet_scop for a continue statement.
4153 * We simply create an empty scop with a universal pet_skip_now
4154 * skip condition. This skip condition will then be taken into
4155 * account by the enclosing loop construct, possibly after
4156 * being incorporated into outer skip conditions.
4158 struct pet_scop *PetScan::extract(ContinueStmt *stmt)
4160 pet_scop *scop;
4162 scop = pet_scop_empty(ctx);
4163 if (!scop)
4164 return NULL;
4166 scop = pet_scop_set_skip(scop, pet_skip_now, one_mpa(ctx));
4168 return scop;
4171 /* Construct a pet_scop for a break statement.
4173 * We simply create an empty scop with both a universal pet_skip_now
4174 * skip condition and a universal pet_skip_later skip condition.
4175 * These skip conditions will then be taken into
4176 * account by the enclosing loop construct, possibly after
4177 * being incorporated into outer skip conditions.
4179 struct pet_scop *PetScan::extract(BreakStmt *stmt)
4181 pet_scop *scop;
4182 isl_multi_pw_aff *skip;
4184 scop = pet_scop_empty(ctx);
4185 if (!scop)
4186 return NULL;
4188 skip = one_mpa(ctx);
4189 scop = pet_scop_set_skip(scop, pet_skip_now,
4190 isl_multi_pw_aff_copy(skip));
4191 scop = pet_scop_set_skip(scop, pet_skip_later, skip);
4193 return scop;
4196 /* Try and construct a pet_scop corresponding to "stmt".
4198 * If "stmt" is a compound statement, then "skip_declarations"
4199 * indicates whether we should skip initial declarations in the
4200 * compound statement.
4202 * If the constructed pet_scop is not a (possibly) partial representation
4203 * of "stmt", we update start and end of the pet_scop to those of "stmt".
4204 * In particular, if skip_declarations is set, then we may have skipped
4205 * declarations inside "stmt" and so the pet_scop may not represent
4206 * the entire "stmt".
4207 * Note that this function may be called with "stmt" referring to the entire
4208 * body of the function, including the outer braces. In such cases,
4209 * skip_declarations will be set and the braces will not be taken into
4210 * account in scop->start and scop->end.
4212 struct pet_scop *PetScan::extract(Stmt *stmt, bool skip_declarations)
4214 struct pet_scop *scop;
4216 if (isa<Expr>(stmt))
4217 return extract(extract_expr(cast<Expr>(stmt)),
4218 stmt->getSourceRange(), true);
4220 switch (stmt->getStmtClass()) {
4221 case Stmt::WhileStmtClass:
4222 scop = extract(cast<WhileStmt>(stmt));
4223 break;
4224 case Stmt::ForStmtClass:
4225 scop = extract_for(cast<ForStmt>(stmt));
4226 break;
4227 case Stmt::IfStmtClass:
4228 scop = extract(cast<IfStmt>(stmt));
4229 break;
4230 case Stmt::CompoundStmtClass:
4231 scop = extract(cast<CompoundStmt>(stmt), skip_declarations);
4232 break;
4233 case Stmt::LabelStmtClass:
4234 scop = extract(cast<LabelStmt>(stmt));
4235 break;
4236 case Stmt::ContinueStmtClass:
4237 scop = extract(cast<ContinueStmt>(stmt));
4238 break;
4239 case Stmt::BreakStmtClass:
4240 scop = extract(cast<BreakStmt>(stmt));
4241 break;
4242 case Stmt::DeclStmtClass:
4243 scop = extract(cast<DeclStmt>(stmt));
4244 break;
4245 default:
4246 unsupported(stmt);
4247 return NULL;
4250 if (partial || skip_declarations)
4251 return scop;
4253 scop = update_scop_start_end(scop, stmt->getSourceRange(), false);
4255 return scop;
4258 /* Extract a clone of the kill statement in "scop".
4259 * "scop" is expected to have been created from a DeclStmt
4260 * and should have the kill as its first statement.
4262 struct pet_stmt *PetScan::extract_kill(struct pet_scop *scop)
4264 pet_expr *kill;
4265 struct pet_stmt *stmt;
4266 isl_multi_pw_aff *index;
4267 isl_map *access;
4268 pet_expr *arg;
4270 if (!scop)
4271 return NULL;
4272 if (scop->n_stmt < 1)
4273 isl_die(ctx, isl_error_internal,
4274 "expecting at least one statement", return NULL);
4275 stmt = scop->stmts[0];
4276 if (!pet_stmt_is_kill(stmt))
4277 isl_die(ctx, isl_error_internal,
4278 "expecting kill statement", return NULL);
4280 arg = pet_expr_get_arg(stmt->body, 0);
4281 index = pet_expr_access_get_index(arg);
4282 access = pet_expr_access_get_access(arg);
4283 pet_expr_free(arg);
4284 index = isl_multi_pw_aff_reset_tuple_id(index, isl_dim_in);
4285 access = isl_map_reset_tuple_id(access, isl_dim_in);
4286 kill = pet_expr_kill_from_access_and_index(access, index);
4287 return pet_stmt_from_pet_expr(stmt->line, NULL, n_stmt++, kill);
4290 /* Mark all arrays in "scop" as being exposed.
4292 static struct pet_scop *mark_exposed(struct pet_scop *scop)
4294 if (!scop)
4295 return NULL;
4296 for (int i = 0; i < scop->n_array; ++i)
4297 scop->arrays[i]->exposed = 1;
4298 return scop;
4301 /* Try and construct a pet_scop corresponding to (part of)
4302 * a sequence of statements.
4304 * "block" is set if the sequence respresents the children of
4305 * a compound statement.
4306 * "skip_declarations" is set if we should skip initial declarations
4307 * in the sequence of statements.
4309 * If there are any breaks or continues in the individual statements,
4310 * then we may have to compute a new skip condition.
4311 * This is handled using a pet_skip_info object.
4312 * On initialization, the object checks if skip conditions need
4313 * to be computed. If so, it does so in pet_skip_info_seq_extract and
4314 * adds them in pet_skip_info_seq_add.
4316 * If "block" is set, then we need to insert kill statements at
4317 * the end of the block for any array that has been declared by
4318 * one of the statements in the sequence. Each of these declarations
4319 * results in the construction of a kill statement at the place
4320 * of the declaration, so we simply collect duplicates of
4321 * those kill statements and append these duplicates to the constructed scop.
4323 * If "block" is not set, then any array declared by one of the statements
4324 * in the sequence is marked as being exposed.
4326 * If autodetect is set, then we allow the extraction of only a subrange
4327 * of the sequence of statements. However, if there is at least one statement
4328 * for which we could not construct a scop and the final range contains
4329 * either no statements or at least one kill, then we discard the entire
4330 * range.
4332 struct pet_scop *PetScan::extract(StmtRange stmt_range, bool block,
4333 bool skip_declarations)
4335 pet_scop *scop;
4336 StmtIterator i;
4337 int int_size;
4338 int j;
4339 bool partial_range = false;
4340 set<struct pet_stmt *> kills;
4341 set<struct pet_stmt *>::iterator it;
4343 int_size = ast_context.getTypeInfo(ast_context.IntTy).first / 8;
4345 scop = pet_scop_empty(ctx);
4346 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
4347 Stmt *child = *i;
4348 struct pet_scop *scop_i;
4350 if (scop->n_stmt == 0 && skip_declarations &&
4351 child->getStmtClass() == Stmt::DeclStmtClass)
4352 continue;
4354 scop_i = extract(child);
4355 if (scop->n_stmt != 0 && partial) {
4356 pet_scop_free(scop_i);
4357 break;
4359 pet_skip_info skip;
4360 pet_skip_info_seq_init(&skip, ctx, scop, scop_i);
4361 pet_skip_info_seq_extract(&skip, int_size, &n_stmt, &n_test);
4362 if (pet_skip_info_has_skip(&skip))
4363 scop_i = pet_scop_prefix(scop_i, 0);
4364 if (scop_i && child->getStmtClass() == Stmt::DeclStmtClass) {
4365 if (block)
4366 kills.insert(extract_kill(scop_i));
4367 else
4368 scop_i = mark_exposed(scop_i);
4370 scop_i = pet_scop_prefix(scop_i, j);
4371 if (options->autodetect) {
4372 if (scop_i)
4373 scop = pet_scop_add_seq(ctx, scop, scop_i);
4374 else
4375 partial_range = true;
4376 if (scop->n_stmt != 0 && !scop_i)
4377 partial = true;
4378 } else {
4379 scop = pet_scop_add_seq(ctx, scop, scop_i);
4382 scop = pet_skip_info_seq_add(&skip, scop, j);
4384 if (partial || !scop)
4385 break;
4388 for (it = kills.begin(); it != kills.end(); ++it) {
4389 pet_scop *scop_j;
4390 scop_j = pet_scop_from_pet_stmt(ctx, *it);
4391 scop_j = pet_scop_prefix(scop_j, j);
4392 scop = pet_scop_add_seq(ctx, scop, scop_j);
4395 if (scop && partial_range) {
4396 if (scop->n_stmt == 0 || kills.size() != 0) {
4397 pet_scop_free(scop);
4398 return NULL;
4400 partial = true;
4403 return scop;
4406 /* Check if the scop marked by the user is exactly this Stmt
4407 * or part of this Stmt.
4408 * If so, return a pet_scop corresponding to the marked region.
4409 * Otherwise, return NULL.
4411 struct pet_scop *PetScan::scan(Stmt *stmt)
4413 SourceManager &SM = PP.getSourceManager();
4414 unsigned start_off, end_off;
4416 start_off = getExpansionOffset(SM, stmt->getLocStart());
4417 end_off = getExpansionOffset(SM, stmt->getLocEnd());
4419 if (start_off > loc.end)
4420 return NULL;
4421 if (end_off < loc.start)
4422 return NULL;
4423 if (start_off >= loc.start && end_off <= loc.end) {
4424 return extract(stmt);
4427 StmtIterator start;
4428 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
4429 Stmt *child = *start;
4430 if (!child)
4431 continue;
4432 start_off = getExpansionOffset(SM, child->getLocStart());
4433 end_off = getExpansionOffset(SM, child->getLocEnd());
4434 if (start_off < loc.start && end_off >= loc.end)
4435 return scan(child);
4436 if (start_off >= loc.start)
4437 break;
4440 StmtIterator end;
4441 for (end = start; end != stmt->child_end(); ++end) {
4442 Stmt *child = *end;
4443 start_off = SM.getFileOffset(child->getLocStart());
4444 if (start_off >= loc.end)
4445 break;
4448 return extract(StmtRange(start, end), false, false);
4451 /* Set the size of index "pos" of "array" to "size".
4452 * In particular, add a constraint of the form
4454 * i_pos < size
4456 * to array->extent and a constraint of the form
4458 * size >= 0
4460 * to array->context.
4462 static struct pet_array *update_size(struct pet_array *array, int pos,
4463 __isl_take isl_pw_aff *size)
4465 isl_set *valid;
4466 isl_set *univ;
4467 isl_set *bound;
4468 isl_space *dim;
4469 isl_aff *aff;
4470 isl_pw_aff *index;
4471 isl_id *id;
4473 valid = isl_set_params(isl_pw_aff_nonneg_set(isl_pw_aff_copy(size)));
4474 array->context = isl_set_intersect(array->context, valid);
4476 dim = isl_set_get_space(array->extent);
4477 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
4478 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
4479 univ = isl_set_universe(isl_aff_get_domain_space(aff));
4480 index = isl_pw_aff_alloc(univ, aff);
4482 size = isl_pw_aff_add_dims(size, isl_dim_in,
4483 isl_set_dim(array->extent, isl_dim_set));
4484 id = isl_set_get_tuple_id(array->extent);
4485 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
4486 bound = isl_pw_aff_lt_set(index, size);
4488 array->extent = isl_set_intersect(array->extent, bound);
4490 if (!array->context || !array->extent)
4491 goto error;
4493 return array;
4494 error:
4495 pet_array_free(array);
4496 return NULL;
4499 /* Figure out the size of the array at position "pos" and all
4500 * subsequent positions from "type" and update "array" accordingly.
4502 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
4503 const Type *type, int pos)
4505 const ArrayType *atype;
4506 isl_pw_aff *size;
4508 if (!array)
4509 return NULL;
4511 if (type->isPointerType()) {
4512 type = type->getPointeeType().getTypePtr();
4513 return set_upper_bounds(array, type, pos + 1);
4515 if (!type->isArrayType())
4516 return array;
4518 type = type->getCanonicalTypeInternal().getTypePtr();
4519 atype = cast<ArrayType>(type);
4521 if (type->isConstantArrayType()) {
4522 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
4523 size = extract_affine(ca->getSize());
4524 array = update_size(array, pos, size);
4525 } else if (type->isVariableArrayType()) {
4526 const VariableArrayType *vla = cast<VariableArrayType>(atype);
4527 size = extract_affine(vla->getSizeExpr());
4528 array = update_size(array, pos, size);
4531 type = atype->getElementType().getTypePtr();
4533 return set_upper_bounds(array, type, pos + 1);
4536 /* Is "T" the type of a variable length array with static size?
4538 static bool is_vla_with_static_size(QualType T)
4540 const VariableArrayType *vlatype;
4542 if (!T->isVariableArrayType())
4543 return false;
4544 vlatype = cast<VariableArrayType>(T);
4545 return vlatype->getSizeModifier() == VariableArrayType::Static;
4548 /* Return the type of "decl" as an array.
4550 * In particular, if "decl" is a parameter declaration that
4551 * is a variable length array with a static size, then
4552 * return the original type (i.e., the variable length array).
4553 * Otherwise, return the type of decl.
4555 static QualType get_array_type(ValueDecl *decl)
4557 ParmVarDecl *parm;
4558 QualType T;
4560 parm = dyn_cast<ParmVarDecl>(decl);
4561 if (!parm)
4562 return decl->getType();
4564 T = parm->getOriginalType();
4565 if (!is_vla_with_static_size(T))
4566 return decl->getType();
4567 return T;
4570 /* Does "decl" have definition that we can keep track of in a pet_type?
4572 static bool has_printable_definition(RecordDecl *decl)
4574 if (!decl->getDeclName())
4575 return false;
4576 return decl->getLexicalDeclContext() == decl->getDeclContext();
4579 /* Construct and return a pet_array corresponding to the variable "decl".
4580 * In particular, initialize array->extent to
4582 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
4584 * and then call set_upper_bounds to set the upper bounds on the indices
4585 * based on the type of the variable.
4587 * If the base type is that of a record with a top-level definition and
4588 * if "types" is not null, then the RecordDecl corresponding to the type
4589 * is added to "types".
4591 * If the base type is that of a record with no top-level definition,
4592 * then we replace it by "<subfield>".
4594 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl,
4595 lex_recorddecl_set *types)
4597 struct pet_array *array;
4598 QualType qt = get_array_type(decl);
4599 const Type *type = qt.getTypePtr();
4600 int depth = array_depth(type);
4601 QualType base = pet_clang_base_type(qt);
4602 string name;
4603 isl_id *id;
4604 isl_space *dim;
4606 array = isl_calloc_type(ctx, struct pet_array);
4607 if (!array)
4608 return NULL;
4610 id = create_decl_id(ctx, decl);
4611 dim = isl_space_set_alloc(ctx, 0, depth);
4612 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
4614 array->extent = isl_set_nat_universe(dim);
4616 dim = isl_space_params_alloc(ctx, 0);
4617 array->context = isl_set_universe(dim);
4619 array = set_upper_bounds(array, type, 0);
4620 if (!array)
4621 return NULL;
4623 name = base.getAsString();
4625 if (types && base->isRecordType()) {
4626 RecordDecl *decl = pet_clang_record_decl(base);
4627 if (has_printable_definition(decl))
4628 types->insert(decl);
4629 else
4630 name = "<subfield>";
4633 array->element_type = strdup(name.c_str());
4634 array->element_is_record = base->isRecordType();
4635 array->element_size = decl->getASTContext().getTypeInfo(base).first / 8;
4637 return array;
4640 /* Construct and return a pet_array corresponding to the sequence
4641 * of declarations "decls".
4642 * If the sequence contains a single declaration, then it corresponds
4643 * to a simple array access. Otherwise, it corresponds to a member access,
4644 * with the declaration for the substructure following that of the containing
4645 * structure in the sequence of declarations.
4646 * We start with the outermost substructure and then combine it with
4647 * information from the inner structures.
4649 * Additionally, keep track of all required types in "types".
4651 struct pet_array *PetScan::extract_array(isl_ctx *ctx,
4652 vector<ValueDecl *> decls, lex_recorddecl_set *types)
4654 struct pet_array *array;
4655 vector<ValueDecl *>::iterator it;
4657 it = decls.begin();
4659 array = extract_array(ctx, *it, types);
4661 for (++it; it != decls.end(); ++it) {
4662 struct pet_array *parent;
4663 const char *base_name, *field_name;
4664 char *product_name;
4666 parent = array;
4667 array = extract_array(ctx, *it, types);
4668 if (!array)
4669 return pet_array_free(parent);
4671 base_name = isl_set_get_tuple_name(parent->extent);
4672 field_name = isl_set_get_tuple_name(array->extent);
4673 product_name = member_access_name(ctx, base_name, field_name);
4675 array->extent = isl_set_product(isl_set_copy(parent->extent),
4676 array->extent);
4677 if (product_name)
4678 array->extent = isl_set_set_tuple_name(array->extent,
4679 product_name);
4680 array->context = isl_set_intersect(array->context,
4681 isl_set_copy(parent->context));
4683 pet_array_free(parent);
4684 free(product_name);
4686 if (!array->extent || !array->context || !product_name)
4687 return pet_array_free(array);
4690 return array;
4693 /* Add a pet_type corresponding to "decl" to "scop, provided
4694 * it is a member of "types" and it has not been added before
4695 * (i.e., it is not a member of "types_done".
4697 * Since we want the user to be able to print the types
4698 * in the order in which they appear in the scop, we need to
4699 * make sure that types of fields in a structure appear before
4700 * that structure. We therefore call ourselves recursively
4701 * on the types of all record subfields.
4703 static struct pet_scop *add_type(isl_ctx *ctx, struct pet_scop *scop,
4704 RecordDecl *decl, Preprocessor &PP, lex_recorddecl_set &types,
4705 lex_recorddecl_set &types_done)
4707 string s;
4708 llvm::raw_string_ostream S(s);
4709 RecordDecl::field_iterator it;
4711 if (types.find(decl) == types.end())
4712 return scop;
4713 if (types_done.find(decl) != types_done.end())
4714 return scop;
4716 for (it = decl->field_begin(); it != decl->field_end(); ++it) {
4717 RecordDecl *record;
4718 QualType type = it->getType();
4720 if (!type->isRecordType())
4721 continue;
4722 record = pet_clang_record_decl(type);
4723 scop = add_type(ctx, scop, record, PP, types, types_done);
4726 if (strlen(decl->getName().str().c_str()) == 0)
4727 return scop;
4729 decl->print(S, PrintingPolicy(PP.getLangOpts()));
4730 S.str();
4732 scop->types[scop->n_type] = pet_type_alloc(ctx,
4733 decl->getName().str().c_str(), s.c_str());
4734 if (!scop->types[scop->n_type])
4735 return pet_scop_free(scop);
4737 types_done.insert(decl);
4739 scop->n_type++;
4741 return scop;
4744 /* Construct a list of pet_arrays, one for each array (or scalar)
4745 * accessed inside "scop", add this list to "scop" and return the result.
4747 * The context of "scop" is updated with the intersection of
4748 * the contexts of all arrays, i.e., constraints on the parameters
4749 * that ensure that the arrays have a valid (non-negative) size.
4751 * If the any of the extracted arrays refers to a member access,
4752 * then also add the required types to "scop".
4754 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
4756 int i;
4757 array_desc_set arrays;
4758 array_desc_set::iterator it;
4759 lex_recorddecl_set types;
4760 lex_recorddecl_set types_done;
4761 lex_recorddecl_set::iterator types_it;
4762 int n_array;
4763 struct pet_array **scop_arrays;
4765 if (!scop)
4766 return NULL;
4768 pet_scop_collect_arrays(scop, arrays);
4769 if (arrays.size() == 0)
4770 return scop;
4772 n_array = scop->n_array;
4774 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
4775 n_array + arrays.size());
4776 if (!scop_arrays)
4777 goto error;
4778 scop->arrays = scop_arrays;
4780 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
4781 struct pet_array *array;
4782 array = extract_array(ctx, *it, &types);
4783 scop->arrays[n_array + i] = array;
4784 if (!scop->arrays[n_array + i])
4785 goto error;
4786 scop->n_array++;
4787 scop->context = isl_set_intersect(scop->context,
4788 isl_set_copy(array->context));
4789 if (!scop->context)
4790 goto error;
4793 if (types.size() == 0)
4794 return scop;
4796 scop->types = isl_alloc_array(ctx, struct pet_type *, types.size());
4797 if (!scop->types)
4798 goto error;
4800 for (types_it = types.begin(); types_it != types.end(); ++types_it)
4801 scop = add_type(ctx, scop, *types_it, PP, types, types_done);
4803 return scop;
4804 error:
4805 pet_scop_free(scop);
4806 return NULL;
4809 /* Bound all parameters in scop->context to the possible values
4810 * of the corresponding C variable.
4812 static struct pet_scop *add_parameter_bounds(struct pet_scop *scop)
4814 int n;
4816 if (!scop)
4817 return NULL;
4819 n = isl_set_dim(scop->context, isl_dim_param);
4820 for (int i = 0; i < n; ++i) {
4821 isl_id *id;
4822 ValueDecl *decl;
4824 id = isl_set_get_dim_id(scop->context, isl_dim_param, i);
4825 if (pet_nested_in_id(id)) {
4826 isl_id_free(id);
4827 isl_die(isl_set_get_ctx(scop->context),
4828 isl_error_internal,
4829 "unresolved nested parameter", goto error);
4831 decl = (ValueDecl *) isl_id_get_user(id);
4832 isl_id_free(id);
4834 scop->context = set_parameter_bounds(scop->context, i, decl);
4836 if (!scop->context)
4837 goto error;
4840 return scop;
4841 error:
4842 pet_scop_free(scop);
4843 return NULL;
4846 /* Construct a pet_scop from the given function.
4848 * If the scop was delimited by scop and endscop pragmas, then we override
4849 * the file offsets by those derived from the pragmas.
4851 struct pet_scop *PetScan::scan(FunctionDecl *fd)
4853 pet_scop *scop;
4854 Stmt *stmt;
4856 stmt = fd->getBody();
4858 if (options->autodetect)
4859 scop = extract(stmt, true);
4860 else {
4861 scop = scan(stmt);
4862 scop = pet_scop_update_start_end(scop, loc.start, loc.end);
4864 scop = pet_scop_detect_parameter_accesses(scop);
4865 scop = scan_arrays(scop);
4866 scop = add_parameter_bounds(scop);
4867 scop = pet_scop_gist(scop, value_bounds);
4869 return scop;