use isl_set_{lower,upper}_bound_si instead of our own open coded version
[pet.git] / scan.cc
blob21afa9864d02191ddba7293d6110ceb4e62d0ff1
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following
13 * disclaimer in the documentation and/or other materials provided
14 * with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
20 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 * The views and conclusions contained in the software and documentation
29 * are those of the authors and should not be interpreted as
30 * representing official policies, either expressed or implied, of
31 * Leiden University.
32 */
34 #include <set>
35 #include <map>
36 #include <iostream>
37 #include <clang/AST/ASTDiagnostic.h>
38 #include <clang/AST/Expr.h>
39 #include <clang/AST/RecursiveASTVisitor.h>
41 #include <isl/id.h>
42 #include <isl/space.h>
43 #include <isl/aff.h>
44 #include <isl/set.h>
46 #include "scan.h"
47 #include "scop.h"
48 #include "scop_plus.h"
50 #include "config.h"
52 using namespace std;
53 using namespace clang;
55 /* Look for any assignments to scalar variables in part of the parse
56 * tree and set assigned_value to NULL for each of them.
57 * Also reset assigned_value if the address of a scalar variable
58 * is being taken.
60 * This ensures that we won't use any previously stored value
61 * in the current subtree and its parents.
63 struct clear_assignments : RecursiveASTVisitor<clear_assignments> {
64 map<ValueDecl *, Expr *> &assigned_value;
66 clear_assignments(map<ValueDecl *, Expr *> &assigned_value) :
67 assigned_value(assigned_value) {}
69 bool VisitUnaryOperator(UnaryOperator *expr) {
70 Expr *arg;
71 DeclRefExpr *ref;
72 ValueDecl *decl;
74 if (expr->getOpcode() != UO_AddrOf)
75 return true;
77 arg = expr->getSubExpr();
78 if (arg->getStmtClass() != Stmt::DeclRefExprClass)
79 return true;
80 ref = cast<DeclRefExpr>(arg);
81 decl = ref->getDecl();
82 assigned_value[decl] = NULL;
83 return true;
86 bool VisitBinaryOperator(BinaryOperator *expr) {
87 Expr *lhs;
88 DeclRefExpr *ref;
89 ValueDecl *decl;
91 if (!expr->isAssignmentOp())
92 return true;
93 lhs = expr->getLHS();
94 if (lhs->getStmtClass() != Stmt::DeclRefExprClass)
95 return true;
96 ref = cast<DeclRefExpr>(lhs);
97 decl = ref->getDecl();
98 assigned_value[decl] = NULL;
99 return true;
103 /* Keep a copy of the currently assigned values.
105 * Any variable that is assigned a value inside the current scope
106 * is removed again when we leave the scope (either because it wasn't
107 * stored in the cache or because it has a different value in the cache).
109 struct assigned_value_cache {
110 map<ValueDecl *, Expr *> &assigned_value;
111 map<ValueDecl *, Expr *> cache;
113 assigned_value_cache(map<ValueDecl *, Expr *> &assigned_value) :
114 assigned_value(assigned_value), cache(assigned_value) {}
115 ~assigned_value_cache() {
116 map<ValueDecl *, Expr *>::iterator it = cache.begin();
117 for (it = assigned_value.begin(); it != assigned_value.end();
118 ++it) {
119 if (!it->second ||
120 (cache.find(it->first) != cache.end() &&
121 cache[it->first] != it->second))
122 cache[it->first] = NULL;
124 assigned_value = cache;
128 /* Called if we found something we (currently) cannot handle.
129 * We'll provide more informative warnings later.
131 * We only actually complain if autodetect is false.
133 void PetScan::unsupported(Stmt *stmt)
135 if (autodetect)
136 return;
138 SourceLocation loc = stmt->getLocStart();
139 DiagnosticsEngine &diag = PP.getDiagnostics();
140 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
141 "unsupported");
142 DiagnosticBuilder B = diag.Report(loc, id) << stmt->getSourceRange();
145 /* Extract an integer from "expr" and store it in "v".
147 int PetScan::extract_int(IntegerLiteral *expr, isl_int *v)
149 const Type *type = expr->getType().getTypePtr();
150 int is_signed = type->hasSignedIntegerRepresentation();
152 if (is_signed) {
153 int64_t i = expr->getValue().getSExtValue();
154 isl_int_set_si(*v, i);
155 } else {
156 uint64_t i = expr->getValue().getZExtValue();
157 isl_int_set_ui(*v, i);
160 return 0;
163 /* Extract an affine expression from the IntegerLiteral "expr".
165 __isl_give isl_pw_aff *PetScan::extract_affine(IntegerLiteral *expr)
167 isl_space *dim = isl_space_params_alloc(ctx, 0);
168 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
169 isl_aff *aff = isl_aff_zero_on_domain(ls);
170 isl_set *dom = isl_set_universe(dim);
171 isl_int v;
173 isl_int_init(v);
174 extract_int(expr, &v);
175 aff = isl_aff_add_constant(aff, v);
176 isl_int_clear(v);
178 return isl_pw_aff_alloc(dom, aff);
181 /* Extract an affine expression from the APInt "val".
183 __isl_give isl_pw_aff *PetScan::extract_affine(const llvm::APInt &val)
185 isl_space *dim = isl_space_params_alloc(ctx, 0);
186 isl_local_space *ls = isl_local_space_from_space(isl_space_copy(dim));
187 isl_aff *aff = isl_aff_zero_on_domain(ls);
188 isl_set *dom = isl_set_universe(dim);
189 isl_int v;
191 isl_int_init(v);
192 isl_int_set_ui(v, val.getZExtValue());
193 aff = isl_aff_add_constant(aff, v);
194 isl_int_clear(v);
196 return isl_pw_aff_alloc(dom, aff);
199 __isl_give isl_pw_aff *PetScan::extract_affine(ImplicitCastExpr *expr)
201 return extract_affine(expr->getSubExpr());
204 /* Extract an affine expression from the DeclRefExpr "expr".
206 * If we have recorded an expression that was assigned to the variable
207 * before, then we convert this expressoin to an isl_pw_aff if it is
208 * affine and to an extra parameter otherwise (provided nesting_enabled is set).
210 * Otherwise, we simply return an expression that is equal
211 * to a parameter corresponding to the referenced variable.
213 __isl_give isl_pw_aff *PetScan::extract_affine(DeclRefExpr *expr)
215 ValueDecl *decl = expr->getDecl();
216 const Type *type = decl->getType().getTypePtr();
217 isl_id *id;
218 isl_space *dim;
219 isl_aff *aff;
220 isl_set *dom;
222 if (!type->isIntegerType()) {
223 unsupported(expr);
224 return NULL;
227 if (assigned_value.find(decl) != assigned_value.end() &&
228 assigned_value[decl] != NULL) {
229 if (is_affine(assigned_value[decl]))
230 return extract_affine(assigned_value[decl]);
231 else
232 return non_affine(expr);
235 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
236 dim = isl_space_params_alloc(ctx, 1);
238 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
240 dom = isl_set_universe(isl_space_copy(dim));
241 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
242 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
244 return isl_pw_aff_alloc(dom, aff);
247 /* Extract an affine expression from an integer division operation.
248 * In particular, if "expr" is lhs/rhs, then return
250 * lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs)
252 * The second argument (rhs) is required to be a (positive) integer constant.
254 __isl_give isl_pw_aff *PetScan::extract_affine_div(BinaryOperator *expr)
256 Expr *rhs_expr;
257 isl_pw_aff *lhs, *lhs_f, *lhs_c;
258 isl_pw_aff *res;
259 isl_int v;
260 isl_set *cond;
262 rhs_expr = expr->getRHS();
263 if (rhs_expr->getStmtClass() != Stmt::IntegerLiteralClass) {
264 unsupported(expr);
265 return NULL;
268 lhs = extract_affine(expr->getLHS());
269 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
271 isl_int_init(v);
272 extract_int(cast<IntegerLiteral>(rhs_expr), &v);
273 lhs = isl_pw_aff_scale_down(lhs, v);
274 isl_int_clear(v);
276 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(lhs));
277 lhs_c = isl_pw_aff_ceil(lhs);
278 res = isl_pw_aff_cond(cond, lhs_f, lhs_c);
280 return res;
283 /* Extract an affine expression from a modulo operation.
284 * In particular, if "expr" is lhs/rhs, then return
286 * lhs - rhs * (lhs >= 0 ? floor(lhs/rhs) : ceil(lhs/rhs))
288 * The second argument (rhs) is required to be a (positive) integer constant.
290 __isl_give isl_pw_aff *PetScan::extract_affine_mod(BinaryOperator *expr)
292 Expr *rhs_expr;
293 isl_pw_aff *lhs, *lhs_f, *lhs_c;
294 isl_pw_aff *res;
295 isl_int v;
296 isl_set *cond;
298 rhs_expr = expr->getRHS();
299 if (rhs_expr->getStmtClass() != Stmt::IntegerLiteralClass) {
300 unsupported(expr);
301 return NULL;
304 lhs = extract_affine(expr->getLHS());
305 cond = isl_pw_aff_nonneg_set(isl_pw_aff_copy(lhs));
307 isl_int_init(v);
308 extract_int(cast<IntegerLiteral>(rhs_expr), &v);
309 res = isl_pw_aff_scale_down(isl_pw_aff_copy(lhs), v);
311 lhs_f = isl_pw_aff_floor(isl_pw_aff_copy(res));
312 lhs_c = isl_pw_aff_ceil(res);
313 res = isl_pw_aff_cond(cond, lhs_f, lhs_c);
315 res = isl_pw_aff_scale(res, v);
316 isl_int_clear(v);
318 res = isl_pw_aff_sub(lhs, res);
320 return res;
323 /* Extract an affine expression from a multiplication operation.
324 * This is only allowed if at least one of the two arguments
325 * is a (piecewise) constant.
327 __isl_give isl_pw_aff *PetScan::extract_affine_mul(BinaryOperator *expr)
329 isl_pw_aff *lhs;
330 isl_pw_aff *rhs;
332 lhs = extract_affine(expr->getLHS());
333 rhs = extract_affine(expr->getRHS());
335 if (!isl_pw_aff_is_cst(lhs) && !isl_pw_aff_is_cst(rhs)) {
336 isl_pw_aff_free(lhs);
337 isl_pw_aff_free(rhs);
338 unsupported(expr);
339 return NULL;
342 return isl_pw_aff_mul(lhs, rhs);
345 /* Extract an affine expression from an addition or subtraction operation.
347 __isl_give isl_pw_aff *PetScan::extract_affine_add(BinaryOperator *expr)
349 isl_pw_aff *lhs;
350 isl_pw_aff *rhs;
352 lhs = extract_affine(expr->getLHS());
353 rhs = extract_affine(expr->getRHS());
355 switch (expr->getOpcode()) {
356 case BO_Add:
357 return isl_pw_aff_add(lhs, rhs);
358 case BO_Sub:
359 return isl_pw_aff_sub(lhs, rhs);
360 default:
361 isl_pw_aff_free(lhs);
362 isl_pw_aff_free(rhs);
363 return NULL;
368 /* Compute
370 * pwaff mod 2^width
372 static __isl_give isl_pw_aff *wrap(__isl_take isl_pw_aff *pwaff,
373 unsigned width)
375 isl_int mod;
377 isl_int_init(mod);
378 isl_int_set_si(mod, 1);
379 isl_int_mul_2exp(mod, mod, width);
381 pwaff = isl_pw_aff_mod(pwaff, mod);
383 isl_int_clear(mod);
385 return pwaff;
388 /* Extract an affine expression from some binary operations.
389 * If the result of the expression is unsigned, then we wrap it
390 * based on the size of the type.
392 __isl_give isl_pw_aff *PetScan::extract_affine(BinaryOperator *expr)
394 isl_pw_aff *res;
396 switch (expr->getOpcode()) {
397 case BO_Add:
398 case BO_Sub:
399 res = extract_affine_add(expr);
400 break;
401 case BO_Div:
402 res = extract_affine_div(expr);
403 break;
404 case BO_Rem:
405 res = extract_affine_mod(expr);
406 break;
407 case BO_Mul:
408 res = extract_affine_mul(expr);
409 break;
410 default:
411 unsupported(expr);
412 return NULL;
415 if (expr->getType()->isUnsignedIntegerType())
416 res = wrap(res, ast_context.getIntWidth(expr->getType()));
418 return res;
421 /* Extract an affine expression from a negation operation.
423 __isl_give isl_pw_aff *PetScan::extract_affine(UnaryOperator *expr)
425 if (expr->getOpcode() == UO_Minus)
426 return isl_pw_aff_neg(extract_affine(expr->getSubExpr()));
428 unsupported(expr);
429 return NULL;
432 __isl_give isl_pw_aff *PetScan::extract_affine(ParenExpr *expr)
434 return extract_affine(expr->getSubExpr());
437 /* Extract an affine expression from some special function calls.
438 * In particular, we handle "min", "max", "ceild" and "floord".
439 * In case of the latter two, the second argument needs to be
440 * a (positive) integer constant.
442 __isl_give isl_pw_aff *PetScan::extract_affine(CallExpr *expr)
444 FunctionDecl *fd;
445 string name;
446 isl_pw_aff *aff1, *aff2;
448 fd = expr->getDirectCallee();
449 if (!fd) {
450 unsupported(expr);
451 return NULL;
454 name = fd->getDeclName().getAsString();
455 if (!(expr->getNumArgs() == 2 && name == "min") &&
456 !(expr->getNumArgs() == 2 && name == "max") &&
457 !(expr->getNumArgs() == 2 && name == "floord") &&
458 !(expr->getNumArgs() == 2 && name == "ceild")) {
459 unsupported(expr);
460 return NULL;
463 if (name == "min" || name == "max") {
464 aff1 = extract_affine(expr->getArg(0));
465 aff2 = extract_affine(expr->getArg(1));
467 if (name == "min")
468 aff1 = isl_pw_aff_min(aff1, aff2);
469 else
470 aff1 = isl_pw_aff_max(aff1, aff2);
471 } else if (name == "floord" || name == "ceild") {
472 isl_int v;
473 Expr *arg2 = expr->getArg(1);
475 if (arg2->getStmtClass() != Stmt::IntegerLiteralClass) {
476 unsupported(expr);
477 return NULL;
479 aff1 = extract_affine(expr->getArg(0));
480 isl_int_init(v);
481 extract_int(cast<IntegerLiteral>(arg2), &v);
482 aff1 = isl_pw_aff_scale_down(aff1, v);
483 isl_int_clear(v);
484 if (name == "floord")
485 aff1 = isl_pw_aff_floor(aff1);
486 else
487 aff1 = isl_pw_aff_ceil(aff1);
488 } else {
489 unsupported(expr);
490 return NULL;
493 return aff1;
497 /* This method is called when we come across a non-affine expression.
498 * If nesting is allowed, we return a new parameter that corresponds
499 * to the non-affine expression. Otherwise, we simply complain.
501 * The new parameter is resolved in resolve_nested.
503 isl_pw_aff *PetScan::non_affine(Expr *expr)
505 isl_id *id;
506 isl_space *dim;
507 isl_aff *aff;
508 isl_set *dom;
510 if (!nesting_enabled) {
511 unsupported(expr);
512 return NULL;
515 id = isl_id_alloc(ctx, NULL, expr);
516 dim = isl_space_params_alloc(ctx, 1);
518 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
520 dom = isl_set_universe(isl_space_copy(dim));
521 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
522 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
524 return isl_pw_aff_alloc(dom, aff);
527 /* Affine expressions are not supposed to contain array accesses,
528 * but if nesting is allowed, we return a parameter corresponding
529 * to the array access.
531 __isl_give isl_pw_aff *PetScan::extract_affine(ArraySubscriptExpr *expr)
533 return non_affine(expr);
536 /* Extract an affine expression from a conditional operation.
538 __isl_give isl_pw_aff *PetScan::extract_affine(ConditionalOperator *expr)
540 isl_set *cond;
541 isl_pw_aff *lhs, *rhs;
543 cond = extract_condition(expr->getCond());
544 lhs = extract_affine(expr->getTrueExpr());
545 rhs = extract_affine(expr->getFalseExpr());
547 return isl_pw_aff_cond(cond, lhs, rhs);
550 /* Extract an affine expression, if possible, from "expr".
551 * Otherwise return NULL.
553 __isl_give isl_pw_aff *PetScan::extract_affine(Expr *expr)
555 switch (expr->getStmtClass()) {
556 case Stmt::ImplicitCastExprClass:
557 return extract_affine(cast<ImplicitCastExpr>(expr));
558 case Stmt::IntegerLiteralClass:
559 return extract_affine(cast<IntegerLiteral>(expr));
560 case Stmt::DeclRefExprClass:
561 return extract_affine(cast<DeclRefExpr>(expr));
562 case Stmt::BinaryOperatorClass:
563 return extract_affine(cast<BinaryOperator>(expr));
564 case Stmt::UnaryOperatorClass:
565 return extract_affine(cast<UnaryOperator>(expr));
566 case Stmt::ParenExprClass:
567 return extract_affine(cast<ParenExpr>(expr));
568 case Stmt::CallExprClass:
569 return extract_affine(cast<CallExpr>(expr));
570 case Stmt::ArraySubscriptExprClass:
571 return extract_affine(cast<ArraySubscriptExpr>(expr));
572 case Stmt::ConditionalOperatorClass:
573 return extract_affine(cast<ConditionalOperator>(expr));
574 default:
575 unsupported(expr);
577 return NULL;
580 __isl_give isl_map *PetScan::extract_access(ImplicitCastExpr *expr)
582 return extract_access(expr->getSubExpr());
585 /* Return the depth of an array of the given type.
587 static int array_depth(const Type *type)
589 if (type->isPointerType())
590 return 1 + array_depth(type->getPointeeType().getTypePtr());
591 if (type->isArrayType()) {
592 const ArrayType *atype;
593 type = type->getCanonicalTypeInternal().getTypePtr();
594 atype = cast<ArrayType>(type);
595 return 1 + array_depth(atype->getElementType().getTypePtr());
597 return 0;
600 /* Return the element type of the given array type.
602 static QualType base_type(QualType qt)
604 const Type *type = qt.getTypePtr();
606 if (type->isPointerType())
607 return base_type(type->getPointeeType());
608 if (type->isArrayType()) {
609 const ArrayType *atype;
610 type = type->getCanonicalTypeInternal().getTypePtr();
611 atype = cast<ArrayType>(type);
612 return base_type(atype->getElementType());
614 return qt;
617 /* Check if the element type corresponding to the given array type
618 * has a const qualifier.
620 static bool const_base(QualType qt)
622 const Type *type = qt.getTypePtr();
624 if (type->isPointerType())
625 return const_base(type->getPointeeType());
626 if (type->isArrayType()) {
627 const ArrayType *atype;
628 type = type->getCanonicalTypeInternal().getTypePtr();
629 atype = cast<ArrayType>(type);
630 return const_base(atype->getElementType());
633 return qt.isConstQualified();
636 /* Extract an access relation from a reference to a variable.
637 * If the variable has name "A" and its type corresponds to an
638 * array of depth d, then the returned access relation is of the
639 * form
641 * { [] -> A[i_1,...,i_d] }
643 __isl_give isl_map *PetScan::extract_access(DeclRefExpr *expr)
645 ValueDecl *decl = expr->getDecl();
646 int depth = array_depth(decl->getType().getTypePtr());
647 isl_id *id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
648 isl_space *dim = isl_space_alloc(ctx, 0, 0, depth);
649 isl_map *access_rel;
651 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
653 access_rel = isl_map_universe(dim);
655 return access_rel;
658 /* Extract an access relation from an integer contant.
659 * If the value of the constant is "v", then the returned access relation
660 * is
662 * { [] -> [v] }
664 __isl_give isl_map *PetScan::extract_access(IntegerLiteral *expr)
666 return isl_map_from_range(isl_set_from_pw_aff(extract_affine(expr)));
669 /* Try and extract an access relation from the given Expr.
670 * Return NULL if it doesn't work out.
672 __isl_give isl_map *PetScan::extract_access(Expr *expr)
674 switch (expr->getStmtClass()) {
675 case Stmt::ImplicitCastExprClass:
676 return extract_access(cast<ImplicitCastExpr>(expr));
677 case Stmt::DeclRefExprClass:
678 return extract_access(cast<DeclRefExpr>(expr));
679 case Stmt::ArraySubscriptExprClass:
680 return extract_access(cast<ArraySubscriptExpr>(expr));
681 default:
682 unsupported(expr);
684 return NULL;
687 /* Assign the affine expression "index" to the output dimension "pos" of "map"
688 * and return the result.
690 __isl_give isl_map *set_index(__isl_take isl_map *map, int pos,
691 __isl_take isl_pw_aff *index)
693 isl_map *index_map;
694 int len = isl_map_dim(map, isl_dim_out);
695 isl_id *id;
697 index_map = isl_map_from_range(isl_set_from_pw_aff(index));
698 index_map = isl_map_insert_dims(index_map, isl_dim_out, 0, pos);
699 index_map = isl_map_add_dims(index_map, isl_dim_out, len - pos - 1);
700 id = isl_map_get_tuple_id(map, isl_dim_out);
701 index_map = isl_map_set_tuple_id(index_map, isl_dim_out, id);
703 map = isl_map_intersect(map, index_map);
705 return map;
708 /* Extract an access relation from the given array subscript expression.
709 * If nesting is allowed in general, then we turn it on while
710 * examining the index expression.
712 * We first extract an access relation from the base.
713 * This will result in an access relation with a range that corresponds
714 * to the array being accessed and with earlier indices filled in already.
715 * We then extract the current index and fill that in as well.
716 * The position of the current index is based on the type of base.
717 * If base is the actual array variable, then the depth of this type
718 * will be the same as the depth of the array and we will fill in
719 * the first array index.
720 * Otherwise, the depth of the base type will be smaller and we will fill
721 * in a later index.
723 __isl_give isl_map *PetScan::extract_access(ArraySubscriptExpr *expr)
725 Expr *base = expr->getBase();
726 Expr *idx = expr->getIdx();
727 isl_pw_aff *index;
728 isl_map *base_access;
729 isl_map *access;
730 int depth = array_depth(base->getType().getTypePtr());
731 int pos;
732 bool save_nesting = nesting_enabled;
734 nesting_enabled = allow_nested;
736 base_access = extract_access(base);
737 index = extract_affine(idx);
739 nesting_enabled = save_nesting;
741 pos = isl_map_dim(base_access, isl_dim_out) - depth;
742 access = set_index(base_access, pos, index);
744 return access;
747 /* Check if "expr" calls function "minmax" with two arguments and if so
748 * make lhs and rhs refer to these two arguments.
750 static bool is_minmax(Expr *expr, const char *minmax, Expr *&lhs, Expr *&rhs)
752 CallExpr *call;
753 FunctionDecl *fd;
754 string name;
756 if (expr->getStmtClass() != Stmt::CallExprClass)
757 return false;
759 call = cast<CallExpr>(expr);
760 fd = call->getDirectCallee();
761 if (!fd)
762 return false;
764 if (call->getNumArgs() != 2)
765 return false;
767 name = fd->getDeclName().getAsString();
768 if (name != minmax)
769 return false;
771 lhs = call->getArg(0);
772 rhs = call->getArg(1);
774 return true;
777 /* Check if "expr" is of the form min(lhs, rhs) and if so make
778 * lhs and rhs refer to the two arguments.
780 static bool is_min(Expr *expr, Expr *&lhs, Expr *&rhs)
782 return is_minmax(expr, "min", lhs, rhs);
785 /* Check if "expr" is of the form max(lhs, rhs) and if so make
786 * lhs and rhs refer to the two arguments.
788 static bool is_max(Expr *expr, Expr *&lhs, Expr *&rhs)
790 return is_minmax(expr, "max", lhs, rhs);
793 /* Extract a set of values satisfying the comparison "LHS op RHS"
794 * "comp" is the original statement that "LHS op RHS" is derived from
795 * and is used for diagnostics.
797 * If the comparison is of the form
799 * a <= min(b,c)
801 * then the set is constructed as the intersection of the set corresponding
802 * to the comparisons
804 * a <= b and a <= c
806 * A similar optimization is performed for max(a,b) <= c.
807 * We do this because that will lead to simpler representations of the set.
808 * If isl is ever enhanced to explicitly deal with min and max expressions,
809 * this optimization can be removed.
811 __isl_give isl_set *PetScan::extract_comparison(BinaryOperatorKind op,
812 Expr *LHS, Expr *RHS, Stmt *comp)
814 isl_pw_aff *lhs;
815 isl_pw_aff *rhs;
816 isl_set *cond;
818 if (op == BO_GT)
819 return extract_comparison(BO_LT, RHS, LHS, comp);
820 if (op == BO_GE)
821 return extract_comparison(BO_LE, RHS, LHS, comp);
823 if (op == BO_LT || op == BO_LE) {
824 Expr *expr1, *expr2;
825 isl_set *set1, *set2;
826 if (is_min(RHS, expr1, expr2)) {
827 set1 = extract_comparison(op, LHS, expr1, comp);
828 set2 = extract_comparison(op, LHS, expr2, comp);
829 return isl_set_intersect(set1, set2);
831 if (is_max(LHS, expr1, expr2)) {
832 set1 = extract_comparison(op, expr1, RHS, comp);
833 set2 = extract_comparison(op, expr2, RHS, comp);
834 return isl_set_intersect(set1, set2);
838 lhs = extract_affine(LHS);
839 rhs = extract_affine(RHS);
841 switch (op) {
842 case BO_LT:
843 cond = isl_pw_aff_lt_set(lhs, rhs);
844 break;
845 case BO_LE:
846 cond = isl_pw_aff_le_set(lhs, rhs);
847 break;
848 case BO_EQ:
849 cond = isl_pw_aff_eq_set(lhs, rhs);
850 break;
851 case BO_NE:
852 cond = isl_pw_aff_ne_set(lhs, rhs);
853 break;
854 default:
855 isl_pw_aff_free(lhs);
856 isl_pw_aff_free(rhs);
857 unsupported(comp);
858 return NULL;
861 cond = isl_set_coalesce(cond);
863 return cond;
866 __isl_give isl_set *PetScan::extract_comparison(BinaryOperator *comp)
868 return extract_comparison(comp->getOpcode(), comp->getLHS(),
869 comp->getRHS(), comp);
872 /* Extract a set of values satisfying the negation (logical not)
873 * of a subexpression.
875 __isl_give isl_set *PetScan::extract_boolean(UnaryOperator *op)
877 isl_set *cond;
879 cond = extract_condition(op->getSubExpr());
881 return isl_set_complement(cond);
884 /* Extract a set of values satisfying the union (logical or)
885 * or intersection (logical and) of two subexpressions.
887 __isl_give isl_set *PetScan::extract_boolean(BinaryOperator *comp)
889 isl_set *lhs;
890 isl_set *rhs;
891 isl_set *cond;
893 lhs = extract_condition(comp->getLHS());
894 rhs = extract_condition(comp->getRHS());
896 switch (comp->getOpcode()) {
897 case BO_LAnd:
898 cond = isl_set_intersect(lhs, rhs);
899 break;
900 case BO_LOr:
901 cond = isl_set_union(lhs, rhs);
902 break;
903 default:
904 isl_set_free(lhs);
905 isl_set_free(rhs);
906 unsupported(comp);
907 return NULL;
910 return cond;
913 __isl_give isl_set *PetScan::extract_condition(UnaryOperator *expr)
915 switch (expr->getOpcode()) {
916 case UO_LNot:
917 return extract_boolean(expr);
918 default:
919 unsupported(expr);
920 return NULL;
924 /* Extract a set of values satisfying the condition "expr != 0".
926 __isl_give isl_set *PetScan::extract_implicit_condition(Expr *expr)
928 return isl_pw_aff_non_zero_set(extract_affine(expr));
931 /* Extract a set of values satisfying the condition expressed by "expr".
933 * If the expression doesn't look like a condition, we assume it
934 * is an affine expression and return the condition "expr != 0".
936 __isl_give isl_set *PetScan::extract_condition(Expr *expr)
938 BinaryOperator *comp;
940 if (!expr)
941 return isl_set_universe(isl_space_params_alloc(ctx, 0));
943 if (expr->getStmtClass() == Stmt::ParenExprClass)
944 return extract_condition(cast<ParenExpr>(expr)->getSubExpr());
946 if (expr->getStmtClass() == Stmt::UnaryOperatorClass)
947 return extract_condition(cast<UnaryOperator>(expr));
949 if (expr->getStmtClass() != Stmt::BinaryOperatorClass)
950 return extract_implicit_condition(expr);
952 comp = cast<BinaryOperator>(expr);
953 switch (comp->getOpcode()) {
954 case BO_LT:
955 case BO_LE:
956 case BO_GT:
957 case BO_GE:
958 case BO_EQ:
959 case BO_NE:
960 return extract_comparison(comp);
961 case BO_LAnd:
962 case BO_LOr:
963 return extract_boolean(comp);
964 default:
965 return extract_implicit_condition(expr);
969 static enum pet_op_type UnaryOperatorKind2pet_op_type(UnaryOperatorKind kind)
971 switch (kind) {
972 case UO_Minus:
973 return pet_op_minus;
974 default:
975 return pet_op_last;
979 static enum pet_op_type BinaryOperatorKind2pet_op_type(BinaryOperatorKind kind)
981 switch (kind) {
982 case BO_AddAssign:
983 return pet_op_add_assign;
984 case BO_SubAssign:
985 return pet_op_sub_assign;
986 case BO_MulAssign:
987 return pet_op_mul_assign;
988 case BO_DivAssign:
989 return pet_op_div_assign;
990 case BO_Assign:
991 return pet_op_assign;
992 case BO_Add:
993 return pet_op_add;
994 case BO_Sub:
995 return pet_op_sub;
996 case BO_Mul:
997 return pet_op_mul;
998 case BO_Div:
999 return pet_op_div;
1000 case BO_EQ:
1001 return pet_op_eq;
1002 case BO_LE:
1003 return pet_op_le;
1004 case BO_LT:
1005 return pet_op_lt;
1006 case BO_GT:
1007 return pet_op_gt;
1008 default:
1009 return pet_op_last;
1013 /* Construct a pet_expr representing a unary operator expression.
1015 struct pet_expr *PetScan::extract_expr(UnaryOperator *expr)
1017 struct pet_expr *arg;
1018 enum pet_op_type op;
1020 op = UnaryOperatorKind2pet_op_type(expr->getOpcode());
1021 if (op == pet_op_last) {
1022 unsupported(expr);
1023 return NULL;
1026 arg = extract_expr(expr->getSubExpr());
1028 return pet_expr_new_unary(ctx, op, arg);
1031 /* Mark the given access pet_expr as a write.
1032 * If a scalar is being accessed, then mark its value
1033 * as unknown in assigned_value.
1035 void PetScan::mark_write(struct pet_expr *access)
1037 isl_id *id;
1038 ValueDecl *decl;
1040 access->acc.write = 1;
1041 access->acc.read = 0;
1043 if (isl_map_dim(access->acc.access, isl_dim_out) != 0)
1044 return;
1046 id = isl_map_get_tuple_id(access->acc.access, isl_dim_out);
1047 decl = (ValueDecl *) isl_id_get_user(id);
1048 assigned_value[decl] = NULL;
1049 isl_id_free(id);
1052 /* Construct a pet_expr representing a binary operator expression.
1054 * If the top level operator is an assignment and the LHS is an access,
1055 * then we mark that access as a write. If the operator is a compound
1056 * assignment, the access is marked as both a read and a write.
1058 * If "expr" assigns something to a scalar variable, then we keep track
1059 * of the assigned expression in assigned_value so that we can plug
1060 * it in when we later come across the same variable.
1062 struct pet_expr *PetScan::extract_expr(BinaryOperator *expr)
1064 struct pet_expr *lhs, *rhs;
1065 enum pet_op_type op;
1067 op = BinaryOperatorKind2pet_op_type(expr->getOpcode());
1068 if (op == pet_op_last) {
1069 unsupported(expr);
1070 return NULL;
1073 lhs = extract_expr(expr->getLHS());
1074 rhs = extract_expr(expr->getRHS());
1076 if (expr->isAssignmentOp() && lhs && lhs->type == pet_expr_access) {
1077 mark_write(lhs);
1078 if (expr->isCompoundAssignmentOp())
1079 lhs->acc.read = 1;
1082 if (expr->getOpcode() == BO_Assign &&
1083 lhs && lhs->type == pet_expr_access &&
1084 isl_map_dim(lhs->acc.access, isl_dim_out) == 0) {
1085 isl_id *id = isl_map_get_tuple_id(lhs->acc.access, isl_dim_out);
1086 ValueDecl *decl = (ValueDecl *) isl_id_get_user(id);
1087 assigned_value[decl] = expr->getRHS();
1088 isl_id_free(id);
1091 return pet_expr_new_binary(ctx, op, lhs, rhs);
1094 /* Construct a pet_expr representing a conditional operation.
1096 struct pet_expr *PetScan::extract_expr(ConditionalOperator *expr)
1098 struct pet_expr *cond, *lhs, *rhs;
1100 cond = extract_expr(expr->getCond());
1101 lhs = extract_expr(expr->getTrueExpr());
1102 rhs = extract_expr(expr->getFalseExpr());
1104 return pet_expr_new_ternary(ctx, cond, lhs, rhs);
1107 struct pet_expr *PetScan::extract_expr(ImplicitCastExpr *expr)
1109 return extract_expr(expr->getSubExpr());
1112 /* Construct a pet_expr representing a floating point value.
1114 struct pet_expr *PetScan::extract_expr(FloatingLiteral *expr)
1116 return pet_expr_new_double(ctx, expr->getValueAsApproximateDouble());
1119 /* Extract an access relation from "expr" and then convert it into
1120 * a pet_expr.
1122 struct pet_expr *PetScan::extract_access_expr(Expr *expr)
1124 isl_map *access;
1125 struct pet_expr *pe;
1127 switch (expr->getStmtClass()) {
1128 case Stmt::ArraySubscriptExprClass:
1129 access = extract_access(cast<ArraySubscriptExpr>(expr));
1130 break;
1131 case Stmt::DeclRefExprClass:
1132 access = extract_access(cast<DeclRefExpr>(expr));
1133 break;
1134 case Stmt::IntegerLiteralClass:
1135 access = extract_access(cast<IntegerLiteral>(expr));
1136 break;
1137 default:
1138 unsupported(expr);
1139 return NULL;
1142 pe = pet_expr_from_access(access);
1144 return pe;
1147 struct pet_expr *PetScan::extract_expr(ParenExpr *expr)
1149 return extract_expr(expr->getSubExpr());
1152 /* Construct a pet_expr representing a function call.
1154 * If we are passing along a pointer to an array element
1155 * or an entire row or even higher dimensional slice of an array,
1156 * then the function being called may write into the array.
1158 * We assume here that if the function is declared to take a pointer
1159 * to a const type, then the function will perform a read
1160 * and that otherwise, it will perform a write.
1162 struct pet_expr *PetScan::extract_expr(CallExpr *expr)
1164 struct pet_expr *res = NULL;
1165 FunctionDecl *fd;
1166 string name;
1168 fd = expr->getDirectCallee();
1169 if (!fd) {
1170 unsupported(expr);
1171 return NULL;
1174 name = fd->getDeclName().getAsString();
1175 res = pet_expr_new_call(ctx, name.c_str(), expr->getNumArgs());
1176 if (!res)
1177 return NULL;
1179 for (int i = 0; i < expr->getNumArgs(); ++i) {
1180 Expr *arg = expr->getArg(i);
1181 int is_addr = 0;
1183 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
1184 ImplicitCastExpr *ice = cast<ImplicitCastExpr>(arg);
1185 arg = ice->getSubExpr();
1187 if (arg->getStmtClass() == Stmt::UnaryOperatorClass) {
1188 UnaryOperator *op = cast<UnaryOperator>(arg);
1189 if (op->getOpcode() == UO_AddrOf) {
1190 is_addr = 1;
1191 arg = op->getSubExpr();
1194 res->args[i] = PetScan::extract_expr(arg);
1195 if (!res->args[i])
1196 goto error;
1197 if (arg->getStmtClass() == Stmt::ArraySubscriptExprClass &&
1198 array_depth(arg->getType().getTypePtr()) > 0)
1199 is_addr = 1;
1200 if (is_addr && res->args[i]->type == pet_expr_access) {
1201 ParmVarDecl *parm = fd->getParamDecl(i);
1202 if (!const_base(parm->getType()))
1203 mark_write(res->args[i]);
1207 return res;
1208 error:
1209 pet_expr_free(res);
1210 return NULL;
1213 /* Try and onstruct a pet_expr representing "expr".
1215 struct pet_expr *PetScan::extract_expr(Expr *expr)
1217 switch (expr->getStmtClass()) {
1218 case Stmt::UnaryOperatorClass:
1219 return extract_expr(cast<UnaryOperator>(expr));
1220 case Stmt::CompoundAssignOperatorClass:
1221 case Stmt::BinaryOperatorClass:
1222 return extract_expr(cast<BinaryOperator>(expr));
1223 case Stmt::ImplicitCastExprClass:
1224 return extract_expr(cast<ImplicitCastExpr>(expr));
1225 case Stmt::ArraySubscriptExprClass:
1226 case Stmt::DeclRefExprClass:
1227 case Stmt::IntegerLiteralClass:
1228 return extract_access_expr(expr);
1229 case Stmt::FloatingLiteralClass:
1230 return extract_expr(cast<FloatingLiteral>(expr));
1231 case Stmt::ParenExprClass:
1232 return extract_expr(cast<ParenExpr>(expr));
1233 case Stmt::ConditionalOperatorClass:
1234 return extract_expr(cast<ConditionalOperator>(expr));
1235 case Stmt::CallExprClass:
1236 return extract_expr(cast<CallExpr>(expr));
1237 default:
1238 unsupported(expr);
1240 return NULL;
1243 /* Check if the given initialization statement is an assignment.
1244 * If so, return that assignment. Otherwise return NULL.
1246 BinaryOperator *PetScan::initialization_assignment(Stmt *init)
1248 BinaryOperator *ass;
1250 if (init->getStmtClass() != Stmt::BinaryOperatorClass)
1251 return NULL;
1253 ass = cast<BinaryOperator>(init);
1254 if (ass->getOpcode() != BO_Assign)
1255 return NULL;
1257 return ass;
1260 /* Check if the given initialization statement is a declaration
1261 * of a single variable.
1262 * If so, return that declaration. Otherwise return NULL.
1264 Decl *PetScan::initialization_declaration(Stmt *init)
1266 DeclStmt *decl;
1268 if (init->getStmtClass() != Stmt::DeclStmtClass)
1269 return NULL;
1271 decl = cast<DeclStmt>(init);
1273 if (!decl->isSingleDecl())
1274 return NULL;
1276 return decl->getSingleDecl();
1279 /* Given the assignment operator in the initialization of a for loop,
1280 * extract the induction variable, i.e., the (integer)variable being
1281 * assigned.
1283 ValueDecl *PetScan::extract_induction_variable(BinaryOperator *init)
1285 Expr *lhs;
1286 DeclRefExpr *ref;
1287 ValueDecl *decl;
1288 const Type *type;
1290 lhs = init->getLHS();
1291 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1292 unsupported(init);
1293 return NULL;
1296 ref = cast<DeclRefExpr>(lhs);
1297 decl = ref->getDecl();
1298 type = decl->getType().getTypePtr();
1300 if (!type->isIntegerType()) {
1301 unsupported(lhs);
1302 return NULL;
1305 return decl;
1308 /* Given the initialization statement of a for loop and the single
1309 * declaration in this initialization statement,
1310 * extract the induction variable, i.e., the (integer) variable being
1311 * declared.
1313 VarDecl *PetScan::extract_induction_variable(Stmt *init, Decl *decl)
1315 VarDecl *vd;
1317 vd = cast<VarDecl>(decl);
1319 const QualType type = vd->getType();
1320 if (!type->isIntegerType()) {
1321 unsupported(init);
1322 return NULL;
1325 if (!vd->getInit()) {
1326 unsupported(init);
1327 return NULL;
1330 return vd;
1333 /* Check that op is of the form iv++ or iv--.
1334 * "inc" is accordingly set to 1 or -1.
1336 bool PetScan::check_unary_increment(UnaryOperator *op, clang::ValueDecl *iv,
1337 isl_int &inc)
1339 Expr *sub;
1340 DeclRefExpr *ref;
1342 if (!op->isIncrementDecrementOp()) {
1343 unsupported(op);
1344 return false;
1347 if (op->isIncrementOp())
1348 isl_int_set_si(inc, 1);
1349 else
1350 isl_int_set_si(inc, -1);
1352 sub = op->getSubExpr();
1353 if (sub->getStmtClass() != Stmt::DeclRefExprClass) {
1354 unsupported(op);
1355 return false;
1358 ref = cast<DeclRefExpr>(sub);
1359 if (ref->getDecl() != iv) {
1360 unsupported(op);
1361 return false;
1364 return true;
1367 /* If the isl_pw_aff on which isl_pw_aff_foreach_piece is called
1368 * has a single constant expression on a universe domain, then
1369 * put this constant in *user.
1371 static int extract_cst(__isl_take isl_set *set, __isl_take isl_aff *aff,
1372 void *user)
1374 isl_int *inc = (isl_int *)user;
1375 int res = 0;
1377 if (!isl_set_plain_is_universe(set) || !isl_aff_is_cst(aff))
1378 res = -1;
1379 else
1380 isl_aff_get_constant(aff, inc);
1382 isl_set_free(set);
1383 isl_aff_free(aff);
1385 return res;
1388 /* Check if op is of the form
1390 * iv = iv + inc
1392 * with inc a constant and set "inc" accordingly.
1394 * We extract an affine expression from the RHS and the subtract iv.
1395 * The result should be a constant.
1397 bool PetScan::check_binary_increment(BinaryOperator *op, clang::ValueDecl *iv,
1398 isl_int &inc)
1400 Expr *lhs;
1401 DeclRefExpr *ref;
1402 isl_id *id;
1403 isl_space *dim;
1404 isl_aff *aff;
1405 isl_pw_aff *val;
1407 if (op->getOpcode() != BO_Assign) {
1408 unsupported(op);
1409 return false;
1412 lhs = op->getLHS();
1413 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1414 unsupported(op);
1415 return false;
1418 ref = cast<DeclRefExpr>(lhs);
1419 if (ref->getDecl() != iv) {
1420 unsupported(op);
1421 return false;
1424 val = extract_affine(op->getRHS());
1426 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1428 dim = isl_space_params_alloc(ctx, 1);
1429 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1430 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1431 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1433 val = isl_pw_aff_sub(val, isl_pw_aff_from_aff(aff));
1435 if (isl_pw_aff_foreach_piece(val, &extract_cst, &inc) < 0) {
1436 isl_pw_aff_free(val);
1437 unsupported(op);
1438 return false;
1441 isl_pw_aff_free(val);
1443 return true;
1446 /* Check that op is of the form iv += cst or iv -= cst.
1447 * "inc" is set to cst or -cst accordingly.
1449 bool PetScan::check_compound_increment(CompoundAssignOperator *op,
1450 clang::ValueDecl *iv, isl_int &inc)
1452 Expr *lhs, *rhs;
1453 DeclRefExpr *ref;
1454 bool neg = false;
1456 BinaryOperatorKind opcode;
1458 opcode = op->getOpcode();
1459 if (opcode != BO_AddAssign && opcode != BO_SubAssign) {
1460 unsupported(op);
1461 return false;
1463 if (opcode == BO_SubAssign)
1464 neg = true;
1466 lhs = op->getLHS();
1467 if (lhs->getStmtClass() != Stmt::DeclRefExprClass) {
1468 unsupported(op);
1469 return false;
1472 ref = cast<DeclRefExpr>(lhs);
1473 if (ref->getDecl() != iv) {
1474 unsupported(op);
1475 return false;
1478 rhs = op->getRHS();
1480 if (rhs->getStmtClass() == Stmt::UnaryOperatorClass) {
1481 UnaryOperator *op = cast<UnaryOperator>(rhs);
1482 if (op->getOpcode() != UO_Minus) {
1483 unsupported(op);
1484 return false;
1487 neg = !neg;
1489 rhs = op->getSubExpr();
1492 if (rhs->getStmtClass() != Stmt::IntegerLiteralClass) {
1493 unsupported(op);
1494 return false;
1497 extract_int(cast<IntegerLiteral>(rhs), &inc);
1498 if (neg)
1499 isl_int_neg(inc, inc);
1501 return true;
1504 /* Check that the increment of the given for loop increments
1505 * (or decrements) the induction variable "iv".
1506 * "up" is set to true if the induction variable is incremented.
1508 bool PetScan::check_increment(ForStmt *stmt, ValueDecl *iv, isl_int &v)
1510 Stmt *inc = stmt->getInc();
1512 if (!inc) {
1513 unsupported(stmt);
1514 return false;
1517 if (inc->getStmtClass() == Stmt::UnaryOperatorClass)
1518 return check_unary_increment(cast<UnaryOperator>(inc), iv, v);
1519 if (inc->getStmtClass() == Stmt::CompoundAssignOperatorClass)
1520 return check_compound_increment(
1521 cast<CompoundAssignOperator>(inc), iv, v);
1522 if (inc->getStmtClass() == Stmt::BinaryOperatorClass)
1523 return check_binary_increment(cast<BinaryOperator>(inc), iv, v);
1525 unsupported(inc);
1526 return false;
1529 /* Embed the given iteration domain in an extra outer loop
1530 * with induction variable "var".
1531 * If this variable appeared as a parameter in the constraints,
1532 * it is replaced by the new outermost dimension.
1534 static __isl_give isl_set *embed(__isl_take isl_set *set,
1535 __isl_take isl_id *var)
1537 int pos;
1539 set = isl_set_insert_dims(set, isl_dim_set, 0, 1);
1540 pos = isl_set_find_dim_by_id(set, isl_dim_param, var);
1541 if (pos >= 0) {
1542 set = isl_set_equate(set, isl_dim_param, pos, isl_dim_set, 0);
1543 set = isl_set_project_out(set, isl_dim_param, pos, 1);
1546 isl_id_free(var);
1547 return set;
1550 /* Construct a pet_scop for an infinite loop around the given body.
1552 * We extract a pet_scop for the body and then embed it in a loop with
1553 * iteration domain
1555 * { [t] : t >= 0 }
1557 * and schedule
1559 * { [t] -> [t] }
1561 struct pet_scop *PetScan::extract_infinite_loop(Stmt *body)
1563 isl_id *id;
1564 isl_space *dim;
1565 isl_set *domain;
1566 isl_map *sched;
1567 struct pet_scop *scop;
1569 scop = extract(body);
1570 if (!scop)
1571 return NULL;
1573 id = isl_id_alloc(ctx, "t", NULL);
1574 domain = isl_set_nat_universe(isl_space_set_alloc(ctx, 0, 1));
1575 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
1576 dim = isl_space_from_domain(isl_set_get_space(domain));
1577 dim = isl_space_add_dims(dim, isl_dim_out, 1);
1578 sched = isl_map_universe(dim);
1579 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
1580 scop = pet_scop_embed(scop, domain, sched, id);
1582 return scop;
1585 /* Construct a pet_scop for an infinite loop, i.e., a loop of the form
1587 * for (;;)
1588 * body
1591 struct pet_scop *PetScan::extract_infinite_for(ForStmt *stmt)
1593 return extract_infinite_loop(stmt->getBody());
1596 /* Check if the while loop is of the form
1598 * while (1)
1599 * body
1601 * If so, construct a scop for an infinite loop around body.
1602 * Otherwise, fail.
1604 struct pet_scop *PetScan::extract(WhileStmt *stmt)
1606 Expr *cond;
1607 isl_set *set;
1608 int is_universe;
1610 cond = stmt->getCond();
1611 if (!cond) {
1612 unsupported(stmt);
1613 return NULL;
1616 set = extract_condition(cond);
1617 is_universe = isl_set_plain_is_universe(set);
1618 isl_set_free(set);
1620 if (!is_universe) {
1621 unsupported(stmt);
1622 return NULL;
1625 return extract_infinite_loop(stmt->getBody());
1628 /* Check whether "cond" expresses a simple loop bound
1629 * on the only set dimension.
1630 * In particular, if "up" is set then "cond" should contain only
1631 * upper bounds on the set dimension.
1632 * Otherwise, it should contain only lower bounds.
1634 static bool is_simple_bound(__isl_keep isl_set *cond, isl_int inc)
1636 if (isl_int_is_pos(inc))
1637 return !isl_set_dim_has_lower_bound(cond, isl_dim_set, 0);
1638 else
1639 return !isl_set_dim_has_upper_bound(cond, isl_dim_set, 0);
1642 /* Extend a condition on a given iteration of a loop to one that
1643 * imposes the same condition on all previous iterations.
1644 * "domain" expresses the lower [upper] bound on the iterations
1645 * when up is set [not set].
1647 * In particular, we construct the condition (when up is set)
1649 * forall i' : (domain(i') and i' <= i) => cond(i')
1651 * which is equivalent to
1653 * not exists i' : domain(i') and i' <= i and not cond(i')
1655 * We construct this set by negating cond, applying a map
1657 * { [i'] -> [i] : domain(i') and i' <= i }
1659 * and then negating the result again.
1661 static __isl_give isl_set *valid_for_each_iteration(__isl_take isl_set *cond,
1662 __isl_take isl_set *domain, isl_int inc)
1664 isl_map *previous_to_this;
1666 if (isl_int_is_pos(inc))
1667 previous_to_this = isl_map_lex_le(isl_set_get_space(domain));
1668 else
1669 previous_to_this = isl_map_lex_ge(isl_set_get_space(domain));
1671 previous_to_this = isl_map_intersect_domain(previous_to_this, domain);
1673 cond = isl_set_complement(cond);
1674 cond = isl_set_apply(cond, previous_to_this);
1675 cond = isl_set_complement(cond);
1677 return cond;
1680 /* Construct a domain of the form
1682 * [id] -> { [] : exists a: id = init + a * inc and a >= 0 }
1684 static __isl_give isl_set *strided_domain(__isl_take isl_id *id,
1685 __isl_take isl_pw_aff *init, isl_int inc)
1687 isl_aff *aff;
1688 isl_space *dim;
1689 isl_set *set;
1691 init = isl_pw_aff_insert_dims(init, isl_dim_in, 0, 1);
1692 dim = isl_pw_aff_get_domain_space(init);
1693 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1694 aff = isl_aff_add_coefficient(aff, isl_dim_in, 0, inc);
1695 init = isl_pw_aff_add(init, isl_pw_aff_from_aff(aff));
1697 dim = isl_space_set_alloc(isl_pw_aff_get_ctx(init), 1, 1);
1698 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
1699 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1700 aff = isl_aff_add_coefficient_si(aff, isl_dim_param, 0, 1);
1702 set = isl_pw_aff_eq_set(isl_pw_aff_from_aff(aff), init);
1704 set = isl_set_lower_bound_si(set, isl_dim_set, 0, 0);
1706 return isl_set_project_out(set, isl_dim_set, 0, 1);
1709 static unsigned get_type_size(ValueDecl *decl)
1711 return decl->getASTContext().getIntWidth(decl->getType());
1714 /* Assuming "cond" represents a simple bound on a loop where the loop
1715 * iterator "iv" is incremented (or decremented) by one, check if wrapping
1716 * is possible.
1718 * Under the given assumptions, wrapping is only possible if "cond" allows
1719 * for the last value before wrapping, i.e., 2^width - 1 in case of an
1720 * increasing iterator and 0 in case of a decreasing iterator.
1722 static bool can_wrap(__isl_keep isl_set *cond, ValueDecl *iv, isl_int inc)
1724 bool cw;
1725 isl_int limit;
1726 isl_set *test;
1728 test = isl_set_copy(cond);
1730 isl_int_init(limit);
1731 if (isl_int_is_neg(inc))
1732 isl_int_set_si(limit, 0);
1733 else {
1734 isl_int_set_si(limit, 1);
1735 isl_int_mul_2exp(limit, limit, get_type_size(iv));
1736 isl_int_sub_ui(limit, limit, 1);
1739 test = isl_set_fix(cond, isl_dim_set, 0, limit);
1740 cw = !isl_set_is_empty(test);
1741 isl_set_free(test);
1743 isl_int_clear(limit);
1745 return cw;
1748 /* Given a one-dimensional space, construct the following mapping on this
1749 * space
1751 * { [v] -> [v mod 2^width] }
1753 * where width is the number of bits used to represent the values
1754 * of the unsigned variable "iv".
1756 static __isl_give isl_map *compute_wrapping(__isl_take isl_space *dim,
1757 ValueDecl *iv)
1759 isl_int mod;
1760 isl_aff *aff;
1761 isl_map *map;
1763 isl_int_init(mod);
1764 isl_int_set_si(mod, 1);
1765 isl_int_mul_2exp(mod, mod, get_type_size(iv));
1767 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
1768 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1769 aff = isl_aff_mod(aff, mod);
1771 isl_int_clear(mod);
1773 return isl_map_from_basic_map(isl_basic_map_from_aff(aff));
1774 map = isl_map_reverse(map);
1777 /* Construct a pet_scop for a for statement.
1778 * The for loop is required to be of the form
1780 * for (i = init; condition; ++i)
1782 * or
1784 * for (i = init; condition; --i)
1786 * The initialization of the for loop should either be an assignment
1787 * to an integer variable, or a declaration of such a variable with
1788 * initialization.
1790 * We extract a pet_scop for the body and then embed it in a loop with
1791 * iteration domain and schedule
1793 * { [i] : i >= init and condition' }
1794 * { [i] -> [i] }
1796 * or
1798 * { [i] : i <= init and condition' }
1799 * { [i] -> [-i] }
1801 * Where condition' is equal to condition if the latter is
1802 * a simple upper [lower] bound and a condition that is extended
1803 * to apply to all previous iterations otherwise.
1805 * If the stride of the loop is not 1, then "i >= init" is replaced by
1807 * (exists a: i = init + stride * a and a >= 0)
1809 * If the loop iterator i is unsigned, then wrapping may occur.
1810 * During the computation, we work with a virtual iterator that
1811 * does not wrap. However, the condition in the code applies
1812 * to the wrapped value, so we need to change condition(i)
1813 * into condition([i % 2^width]).
1814 * After computing the virtual domain and schedule, we apply
1815 * the function { [v] -> [v % 2^width] } to the domain and the domain
1816 * of the schedule. In order not to lose any information, we also
1817 * need to intersect the domain of the schedule with the virtual domain
1818 * first, since some iterations in the wrapped domain may be scheduled
1819 * several times, typically an infinite number of times.
1820 * Note that there is no need to perform this final wrapping
1821 * if the loop condition (after wrapping) is simple.
1823 * Wrapping on unsigned iterators can be avoided entirely if
1824 * loop condition is simple, the loop iterator is incremented
1825 * [decremented] by one and the last value before wrapping cannot
1826 * possibly satisfy the loop condition.
1828 * Before extracting a pet_scop from the body we remove all
1829 * assignments in assigned_value to variables that are assigned
1830 * somewhere in the body of the loop.
1832 struct pet_scop *PetScan::extract_for(ForStmt *stmt)
1834 BinaryOperator *ass;
1835 Decl *decl;
1836 Stmt *init;
1837 Expr *lhs, *rhs;
1838 ValueDecl *iv;
1839 isl_space *dim;
1840 isl_set *domain;
1841 isl_map *sched;
1842 isl_set *cond;
1843 isl_id *id;
1844 struct pet_scop *scop;
1845 assigned_value_cache cache(assigned_value);
1846 isl_int inc;
1847 bool is_one;
1848 bool is_unsigned;
1849 bool is_simple;
1850 isl_map *wrap = NULL;
1852 if (!stmt->getInit() && !stmt->getCond() && !stmt->getInc())
1853 return extract_infinite_for(stmt);
1855 init = stmt->getInit();
1856 if (!init) {
1857 unsupported(stmt);
1858 return NULL;
1860 if ((ass = initialization_assignment(init)) != NULL) {
1861 iv = extract_induction_variable(ass);
1862 if (!iv)
1863 return NULL;
1864 lhs = ass->getLHS();
1865 rhs = ass->getRHS();
1866 } else if ((decl = initialization_declaration(init)) != NULL) {
1867 VarDecl *var = extract_induction_variable(init, decl);
1868 if (!var)
1869 return NULL;
1870 iv = var;
1871 rhs = var->getInit();
1872 lhs = DeclRefExpr::Create(iv->getASTContext(),
1873 var->getQualifierLoc(), iv, var->getInnerLocStart(),
1874 var->getType(), VK_LValue);
1875 } else {
1876 unsupported(stmt->getInit());
1877 return NULL;
1880 isl_int_init(inc);
1881 if (!check_increment(stmt, iv, inc)) {
1882 isl_int_clear(inc);
1883 return NULL;
1886 is_unsigned = iv->getType()->isUnsignedIntegerType();
1888 assigned_value[iv] = NULL;
1889 clear_assignments clear(assigned_value);
1890 clear.TraverseStmt(stmt->getBody());
1892 id = isl_id_alloc(ctx, iv->getName().str().c_str(), iv);
1894 is_one = isl_int_is_one(inc) || isl_int_is_negone(inc);
1895 if (is_one)
1896 domain = extract_comparison(isl_int_is_pos(inc) ? BO_GE : BO_LE,
1897 lhs, rhs, init);
1898 else {
1899 isl_pw_aff *lb = extract_affine(rhs);
1900 domain = strided_domain(isl_id_copy(id), lb, inc);
1903 cond = extract_condition(stmt->getCond());
1904 cond = embed(cond, isl_id_copy(id));
1905 domain = embed(domain, isl_id_copy(id));
1906 is_simple = is_simple_bound(cond, inc);
1907 if (is_unsigned &&
1908 (!is_simple || !is_one || can_wrap(cond, iv, inc))) {
1909 wrap = compute_wrapping(isl_set_get_space(cond), iv);
1910 cond = isl_set_apply(cond, isl_map_reverse(isl_map_copy(wrap)));
1911 is_simple = is_simple && is_simple_bound(cond, inc);
1913 if (!is_simple)
1914 cond = valid_for_each_iteration(cond,
1915 isl_set_copy(domain), inc);
1916 domain = isl_set_intersect(domain, cond);
1917 domain = isl_set_set_dim_id(domain, isl_dim_set, 0, isl_id_copy(id));
1918 dim = isl_space_from_domain(isl_set_get_space(domain));
1919 dim = isl_space_add_dims(dim, isl_dim_out, 1);
1920 sched = isl_map_universe(dim);
1921 if (isl_int_is_pos(inc))
1922 sched = isl_map_equate(sched, isl_dim_in, 0, isl_dim_out, 0);
1923 else
1924 sched = isl_map_oppose(sched, isl_dim_in, 0, isl_dim_out, 0);
1926 if (is_unsigned && !is_simple) {
1927 wrap = isl_map_set_dim_id(wrap,
1928 isl_dim_out, 0, isl_id_copy(id));
1929 sched = isl_map_intersect_domain(sched, isl_set_copy(domain));
1930 domain = isl_set_apply(domain, isl_map_copy(wrap));
1931 sched = isl_map_apply_domain(sched, wrap);
1932 } else
1933 isl_map_free(wrap);
1935 scop = extract(stmt->getBody());
1936 scop = pet_scop_embed(scop, domain, sched, id);
1938 isl_int_clear(inc);
1939 return scop;
1942 struct pet_scop *PetScan::extract(CompoundStmt *stmt)
1944 return extract(stmt->children());
1947 /* Look for parameters in any access relation in "expr" that
1948 * refer to non-affine constructs. In particular, these are
1949 * parameters with no name.
1951 * If there are any such parameters, then the domain of the access
1952 * relation, which is still [] at this point, is replaced by
1953 * [[] -> [t_1,...,t_n]], with n the number of these parameters
1954 * (after identifying identical non-affine constructs).
1955 * The parameters are then equated to the corresponding t dimensions
1956 * and subsequently projected out.
1957 * param2pos maps the position of the parameter to the position
1958 * of the corresponding t dimension.
1960 struct pet_expr *PetScan::resolve_nested(struct pet_expr *expr)
1962 int n;
1963 int nparam;
1964 int n_in;
1965 isl_space *dim;
1966 isl_map *map;
1967 std::map<int,int> param2pos;
1969 if (!expr)
1970 return expr;
1972 for (int i = 0; i < expr->n_arg; ++i) {
1973 expr->args[i] = resolve_nested(expr->args[i]);
1974 if (!expr->args[i]) {
1975 pet_expr_free(expr);
1976 return NULL;
1980 if (expr->type != pet_expr_access)
1981 return expr;
1983 nparam = isl_map_dim(expr->acc.access, isl_dim_param);
1984 n = 0;
1985 for (int i = 0; i < nparam; ++i) {
1986 isl_id *id = isl_map_get_dim_id(expr->acc.access,
1987 isl_dim_param, i);
1988 if (id && isl_id_get_user(id) && !isl_id_get_name(id))
1989 n++;
1990 isl_id_free(id);
1993 if (n == 0)
1994 return expr;
1996 expr->n_arg = n;
1997 expr->args = isl_calloc_array(ctx, struct pet_expr *, n);
1998 if (!expr->args)
1999 goto error;
2001 n_in = isl_map_dim(expr->acc.access, isl_dim_in);
2002 for (int i = 0, pos = 0; i < nparam; ++i) {
2003 int j;
2004 isl_id *id = isl_map_get_dim_id(expr->acc.access,
2005 isl_dim_param, i);
2006 Expr *nested;
2008 if (!(id && isl_id_get_user(id) && !isl_id_get_name(id))) {
2009 isl_id_free(id);
2010 continue;
2013 nested = (Expr *) isl_id_get_user(id);
2014 expr->args[pos] = extract_expr(nested);
2016 for (j = 0; j < pos; ++j)
2017 if (pet_expr_is_equal(expr->args[j], expr->args[pos]))
2018 break;
2020 if (j < pos) {
2021 pet_expr_free(expr->args[pos]);
2022 param2pos[i] = n_in + j;
2023 n--;
2024 } else
2025 param2pos[i] = n_in + pos++;
2027 isl_id_free(id);
2029 expr->n_arg = n;
2031 dim = isl_map_get_space(expr->acc.access);
2032 dim = isl_space_domain(dim);
2033 dim = isl_space_from_domain(dim);
2034 dim = isl_space_add_dims(dim, isl_dim_out, n);
2035 map = isl_map_universe(dim);
2036 map = isl_map_domain_map(map);
2037 map = isl_map_reverse(map);
2038 expr->acc.access = isl_map_apply_domain(expr->acc.access, map);
2040 for (int i = nparam - 1; i >= 0; --i) {
2041 isl_id *id = isl_map_get_dim_id(expr->acc.access,
2042 isl_dim_param, i);
2043 if (!(id && isl_id_get_user(id) && !isl_id_get_name(id))) {
2044 isl_id_free(id);
2045 continue;
2048 expr->acc.access = isl_map_equate(expr->acc.access,
2049 isl_dim_param, i, isl_dim_in,
2050 param2pos[i]);
2051 expr->acc.access = isl_map_project_out(expr->acc.access,
2052 isl_dim_param, i, 1);
2054 isl_id_free(id);
2057 return expr;
2058 error:
2059 pet_expr_free(expr);
2060 return NULL;
2063 /* Convert a top-level pet_expr to a pet_scop with one statement.
2064 * This mainly involves resolving nested expression parameters
2065 * and setting the name of the iteration space.
2067 struct pet_scop *PetScan::extract(Stmt *stmt, struct pet_expr *expr)
2069 struct pet_stmt *ps;
2070 SourceLocation loc = stmt->getLocStart();
2071 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2073 expr = resolve_nested(expr);
2074 ps = pet_stmt_from_pet_expr(ctx, line, n_stmt++, expr);
2075 return pet_scop_from_pet_stmt(ctx, ps);
2078 /* Check whether "expr" is an affine expression.
2079 * We turn on autodetection so that we won't generate any warnings
2080 * and turn off nesting, so that we won't accept any non-affine constructs.
2082 bool PetScan::is_affine(Expr *expr)
2084 isl_pw_aff *pwaff;
2085 int save_autodetect = autodetect;
2086 bool save_nesting = nesting_enabled;
2088 autodetect = 1;
2089 nesting_enabled = false;
2091 pwaff = extract_affine(expr);
2092 isl_pw_aff_free(pwaff);
2094 autodetect = save_autodetect;
2095 nesting_enabled = save_nesting;
2097 return pwaff != NULL;
2100 /* Check whether "expr" is an affine constraint.
2101 * We turn on autodetection so that we won't generate any warnings
2102 * and turn off nesting, so that we won't accept any non-affine constructs.
2104 bool PetScan::is_affine_condition(Expr *expr)
2106 isl_set *set;
2107 int save_autodetect = autodetect;
2108 bool save_nesting = nesting_enabled;
2110 autodetect = 1;
2111 nesting_enabled = false;
2113 set = extract_condition(expr);
2114 isl_set_free(set);
2116 autodetect = save_autodetect;
2117 nesting_enabled = save_nesting;
2119 return set != NULL;
2122 /* If the top-level expression of "stmt" is an assignment, then
2123 * return that assignment as a BinaryOperator.
2124 * Otherwise return NULL.
2126 static BinaryOperator *top_assignment_or_null(Stmt *stmt)
2128 BinaryOperator *ass;
2130 if (!stmt)
2131 return NULL;
2132 if (stmt->getStmtClass() != Stmt::BinaryOperatorClass)
2133 return NULL;
2135 ass = cast<BinaryOperator>(stmt);
2136 if(ass->getOpcode() != BO_Assign)
2137 return NULL;
2139 return ass;
2142 /* Check if the given if statement is a conditional assignement
2143 * with a non-affine condition. If so, construct a pet_scop
2144 * corresponding to this conditional assignment. Otherwise return NULL.
2146 * In particular we check if "stmt" is of the form
2148 * if (condition)
2149 * a = f(...);
2150 * else
2151 * a = g(...);
2153 * where a is some array or scalar access.
2154 * The constructed pet_scop then corresponds to the expression
2156 * a = condition ? f(...) : g(...)
2158 * All access relations in f(...) are intersected with condition
2159 * while all access relation in g(...) are intersected with the complement.
2161 struct pet_scop *PetScan::extract_conditional_assignment(IfStmt *stmt)
2163 BinaryOperator *ass_then, *ass_else;
2164 isl_map *write_then, *write_else;
2165 isl_set *cond, *comp;
2166 isl_map *map, *map_true, *map_false;
2167 int equal;
2168 struct pet_expr *pe_cond, *pe_then, *pe_else, *pe, *pe_write;
2169 bool save_nesting = nesting_enabled;
2171 ass_then = top_assignment_or_null(stmt->getThen());
2172 ass_else = top_assignment_or_null(stmt->getElse());
2174 if (!ass_then || !ass_else)
2175 return NULL;
2177 if (is_affine_condition(stmt->getCond()))
2178 return NULL;
2180 write_then = extract_access(ass_then->getLHS());
2181 write_else = extract_access(ass_else->getLHS());
2183 equal = isl_map_is_equal(write_then, write_else);
2184 isl_map_free(write_else);
2185 if (equal < 0 || !equal) {
2186 isl_map_free(write_then);
2187 return NULL;
2190 nesting_enabled = allow_nested;
2191 cond = extract_condition(stmt->getCond());
2192 nesting_enabled = save_nesting;
2193 comp = isl_set_complement(isl_set_copy(cond));
2194 map_true = isl_map_from_domain(isl_set_from_params(isl_set_copy(cond)));
2195 map_true = isl_map_add_dims(map_true, isl_dim_out, 1);
2196 map_true = isl_map_fix_si(map_true, isl_dim_out, 0, 1);
2197 map_false = isl_map_from_domain(isl_set_from_params(isl_set_copy(comp)));
2198 map_false = isl_map_add_dims(map_false, isl_dim_out, 1);
2199 map_false = isl_map_fix_si(map_false, isl_dim_out, 0, 0);
2200 map = isl_map_union_disjoint(map_true, map_false);
2202 pe_cond = pet_expr_from_access(map);
2204 pe_then = extract_expr(ass_then->getRHS());
2205 pe_then = pet_expr_restrict(pe_then, cond);
2206 pe_else = extract_expr(ass_else->getRHS());
2207 pe_else = pet_expr_restrict(pe_else, comp);
2209 pe = pet_expr_new_ternary(ctx, pe_cond, pe_then, pe_else);
2210 pe_write = pet_expr_from_access(write_then);
2211 if (pe_write) {
2212 pe_write->acc.write = 1;
2213 pe_write->acc.read = 0;
2215 pe = pet_expr_new_binary(ctx, pet_op_assign, pe_write, pe);
2216 return extract(stmt, pe);
2219 /* Create an access to a virtual scalar representing the result
2220 * of a condition.
2221 * Unlike other accessed data, the id of the scalar is NULL as
2222 * there is no ValueDecl in the program corresponding to the virtual
2223 * scalar.
2225 static __isl_give isl_map *create_test_access(isl_ctx *ctx, int test_nr)
2227 isl_space *dim = isl_space_alloc(ctx, 0, 0, 0);
2228 isl_id *id;
2229 char name[50];
2231 snprintf(name, sizeof(name), "__pet_test_%d", test_nr);
2232 id = isl_id_alloc(ctx, name, NULL);
2233 dim = isl_space_set_tuple_id(dim, isl_dim_out, id);
2234 return isl_map_universe(dim);
2237 /* Create a pet_scop with a single statement evaluating "cond"
2238 * and writing the result to a virtual scalar, as expressed by
2239 * "access".
2241 struct pet_scop *PetScan::extract_non_affine_condition(Expr *cond,
2242 __isl_take isl_map *access)
2244 struct pet_expr *expr, *write;
2245 struct pet_stmt *ps;
2246 SourceLocation loc = cond->getLocStart();
2247 int line = PP.getSourceManager().getExpansionLineNumber(loc);
2249 write = pet_expr_from_access(access);
2250 if (write) {
2251 write->acc.write = 1;
2252 write->acc.read = 0;
2254 expr = extract_expr(cond);
2255 expr = pet_expr_new_binary(ctx, pet_op_assign, write, expr);
2256 ps = pet_stmt_from_pet_expr(ctx, line, n_stmt++, expr);
2257 return pet_scop_from_pet_stmt(ctx, ps);
2260 /* Add an array with the given extend ("access") to the list
2261 * of arrays in "scop" and return the extended pet_scop.
2263 static struct pet_scop *scop_add_array(struct pet_scop *scop,
2264 __isl_keep isl_map *access)
2266 isl_ctx *ctx = isl_map_get_ctx(access);
2267 isl_space *dim;
2268 struct pet_array **arrays;
2269 struct pet_array *array;
2271 if (!scop)
2272 return NULL;
2273 if (!ctx)
2274 goto error;
2276 arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2277 scop->n_array + 1);
2278 if (!arrays)
2279 goto error;
2280 scop->arrays = arrays;
2282 array = isl_calloc_type(ctx, struct pet_array);
2283 if (!array)
2284 goto error;
2286 array->extent = isl_map_range(isl_map_copy(access));
2287 dim = isl_space_params_alloc(ctx, 0);
2288 array->context = isl_set_universe(dim);
2289 array->element_type = strdup("int");
2291 scop->arrays[scop->n_array] = array;
2292 scop->n_array++;
2294 if (!array->extent || !array->context)
2295 goto error;
2297 return scop;
2298 error:
2299 pet_scop_free(scop);
2300 return NULL;
2303 /* Construct a pet_scop for an if statement.
2305 * If the condition fits the pattern of a conditional assignment,
2306 * then it is handled by extract_conditional_assignment.
2307 * Otherwise, we do the following.
2309 * If the condition is affine, then the condition is added
2310 * to the iteration domains of the then branch, while the
2311 * opposite of the condition in added to the iteration domains
2312 * of the else branch, if any.
2314 * If the condition is not-affine, then we create a separate
2315 * statement that write the result of the condition to a virtual scalar.
2316 * A constraint requiring the value of this virtual scalar to be one
2317 * is added to the iteration domains of the then branch.
2318 * Similarly, a constraint requiring the value of this virtual scalar
2319 * to be zero is added to the iteration domains of the else branch, if any.
2320 * We adjust the schedules to ensure that the virtual scalar is written
2321 * before it is read.
2323 struct pet_scop *PetScan::extract(IfStmt *stmt)
2325 struct pet_scop *scop_then, *scop_else, *scop;
2326 assigned_value_cache cache(assigned_value);
2327 isl_map *test_access = NULL;
2329 scop = extract_conditional_assignment(stmt);
2330 if (scop)
2331 return scop;
2333 if (allow_nested && !is_affine_condition(stmt->getCond())) {
2334 test_access = create_test_access(ctx, n_test++);
2335 scop = extract_non_affine_condition(stmt->getCond(),
2336 isl_map_copy(test_access));
2337 scop = scop_add_array(scop, test_access);
2338 if (!scop) {
2339 isl_map_free(test_access);
2340 return NULL;
2344 scop_then = extract(stmt->getThen());
2346 if (stmt->getElse()) {
2347 scop_else = extract(stmt->getElse());
2348 if (autodetect) {
2349 if (scop_then && !scop_else) {
2350 partial = true;
2351 pet_scop_free(scop);
2352 isl_map_free(test_access);
2353 return scop_then;
2355 if (!scop_then && scop_else) {
2356 partial = true;
2357 pet_scop_free(scop);
2358 isl_map_free(test_access);
2359 return scop_else;
2364 if (!scop) {
2365 isl_set *cond;
2366 cond = extract_condition(stmt->getCond());
2367 scop = pet_scop_restrict(scop_then, isl_set_copy(cond));
2369 if (stmt->getElse()) {
2370 cond = isl_set_complement(cond);
2371 scop_else = pet_scop_restrict(scop_else, cond);
2372 scop = pet_scop_add(ctx, scop, scop_else);
2373 } else
2374 isl_set_free(cond);
2375 } else {
2376 scop = pet_scop_prefix(scop, 0);
2377 scop_then = pet_scop_prefix(scop_then, 1);
2378 scop_then = pet_scop_filter(scop_then,
2379 isl_map_copy(test_access), 1);
2380 scop = pet_scop_add(ctx, scop, scop_then);
2381 if (stmt->getElse()) {
2382 scop_else = pet_scop_prefix(scop_else, 1);
2383 scop_else = pet_scop_filter(scop_else, test_access, 0);
2384 scop = pet_scop_add(ctx, scop, scop_else);
2385 } else
2386 isl_map_free(test_access);
2389 return scop;
2392 /* Try and construct a pet_scop corresponding to "stmt".
2394 struct pet_scop *PetScan::extract(Stmt *stmt)
2396 if (isa<Expr>(stmt))
2397 return extract(stmt, extract_expr(cast<Expr>(stmt)));
2399 switch (stmt->getStmtClass()) {
2400 case Stmt::WhileStmtClass:
2401 return extract(cast<WhileStmt>(stmt));
2402 case Stmt::ForStmtClass:
2403 return extract_for(cast<ForStmt>(stmt));
2404 case Stmt::IfStmtClass:
2405 return extract(cast<IfStmt>(stmt));
2406 case Stmt::CompoundStmtClass:
2407 return extract(cast<CompoundStmt>(stmt));
2408 default:
2409 unsupported(stmt);
2412 return NULL;
2415 /* Try and construct a pet_scop corresponding to (part of)
2416 * a sequence of statements.
2418 struct pet_scop *PetScan::extract(StmtRange stmt_range)
2420 pet_scop *scop;
2421 StmtIterator i;
2422 int j;
2423 bool partial_range = false;
2425 scop = pet_scop_empty(ctx);
2426 for (i = stmt_range.first, j = 0; i != stmt_range.second; ++i, ++j) {
2427 Stmt *child = *i;
2428 struct pet_scop *scop_i;
2429 scop_i = extract(child);
2430 if (scop && partial) {
2431 pet_scop_free(scop_i);
2432 break;
2434 scop_i = pet_scop_prefix(scop_i, j);
2435 if (autodetect) {
2436 if (scop_i)
2437 scop = pet_scop_add(ctx, scop, scop_i);
2438 else
2439 partial_range = true;
2440 if (scop->n_stmt != 0 && !scop_i)
2441 partial = true;
2442 } else {
2443 scop = pet_scop_add(ctx, scop, scop_i);
2445 if (partial)
2446 break;
2449 if (scop && partial_range)
2450 partial = true;
2452 return scop;
2455 /* Check if the scop marked by the user is exactly this Stmt
2456 * or part of this Stmt.
2457 * If so, return a pet_scop corresponding to the marked region.
2458 * Otherwise, return NULL.
2460 struct pet_scop *PetScan::scan(Stmt *stmt)
2462 SourceManager &SM = PP.getSourceManager();
2463 unsigned start_off, end_off;
2465 start_off = SM.getFileOffset(stmt->getLocStart());
2466 end_off = SM.getFileOffset(stmt->getLocEnd());
2468 if (start_off > loc.end)
2469 return NULL;
2470 if (end_off < loc.start)
2471 return NULL;
2472 if (start_off >= loc.start && end_off <= loc.end) {
2473 return extract(stmt);
2476 StmtIterator start;
2477 for (start = stmt->child_begin(); start != stmt->child_end(); ++start) {
2478 Stmt *child = *start;
2479 if (!child)
2480 continue;
2481 start_off = SM.getFileOffset(child->getLocStart());
2482 end_off = SM.getFileOffset(child->getLocEnd());
2483 if (start_off < loc.start && end_off > loc.end)
2484 return scan(child);
2485 if (start_off >= loc.start)
2486 break;
2489 StmtIterator end;
2490 for (end = start; end != stmt->child_end(); ++end) {
2491 Stmt *child = *end;
2492 start_off = SM.getFileOffset(child->getLocStart());
2493 if (start_off >= loc.end)
2494 break;
2497 return extract(StmtRange(start, end));
2500 /* Set the size of index "pos" of "array" to "size".
2501 * In particular, add a constraint of the form
2503 * i_pos < size
2505 * to array->extent and a constraint of the form
2507 * size >= 0
2509 * to array->context.
2511 static struct pet_array *update_size(struct pet_array *array, int pos,
2512 __isl_take isl_pw_aff *size)
2514 isl_set *valid;
2515 isl_set *univ;
2516 isl_set *bound;
2517 isl_space *dim;
2518 isl_aff *aff;
2519 isl_pw_aff *index;
2520 isl_id *id;
2522 valid = isl_pw_aff_nonneg_set(isl_pw_aff_copy(size));
2523 array->context = isl_set_intersect(array->context, valid);
2525 dim = isl_set_get_space(array->extent);
2526 aff = isl_aff_zero_on_domain(isl_local_space_from_space(dim));
2527 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, pos, 1);
2528 univ = isl_set_universe(isl_aff_get_domain_space(aff));
2529 index = isl_pw_aff_alloc(univ, aff);
2531 size = isl_pw_aff_add_dims(size, isl_dim_in,
2532 isl_set_dim(array->extent, isl_dim_set));
2533 id = isl_set_get_tuple_id(array->extent);
2534 size = isl_pw_aff_set_tuple_id(size, isl_dim_in, id);
2535 bound = isl_pw_aff_lt_set(index, size);
2537 array->extent = isl_set_intersect(array->extent, bound);
2539 if (!array->context || !array->extent)
2540 goto error;
2542 return array;
2543 error:
2544 pet_array_free(array);
2545 return NULL;
2548 /* Figure out the size of the array at position "pos" and all
2549 * subsequent positions from "type" and update "array" accordingly.
2551 struct pet_array *PetScan::set_upper_bounds(struct pet_array *array,
2552 const Type *type, int pos)
2554 const ArrayType *atype;
2555 isl_pw_aff *size;
2557 if (!array)
2558 return NULL;
2560 if (type->isPointerType()) {
2561 type = type->getPointeeType().getTypePtr();
2562 return set_upper_bounds(array, type, pos + 1);
2564 if (!type->isArrayType())
2565 return array;
2567 type = type->getCanonicalTypeInternal().getTypePtr();
2568 atype = cast<ArrayType>(type);
2570 if (type->isConstantArrayType()) {
2571 const ConstantArrayType *ca = cast<ConstantArrayType>(atype);
2572 size = extract_affine(ca->getSize());
2573 array = update_size(array, pos, size);
2574 } else if (type->isVariableArrayType()) {
2575 const VariableArrayType *vla = cast<VariableArrayType>(atype);
2576 size = extract_affine(vla->getSizeExpr());
2577 array = update_size(array, pos, size);
2580 type = atype->getElementType().getTypePtr();
2582 return set_upper_bounds(array, type, pos + 1);
2585 /* Construct and return a pet_array corresponding to the variable "decl".
2586 * In particular, initialize array->extent to
2588 * { name[i_1,...,i_d] : i_1,...,i_d >= 0 }
2590 * and then call set_upper_bounds to set the upper bounds on the indices
2591 * based on the type of the variable.
2593 struct pet_array *PetScan::extract_array(isl_ctx *ctx, ValueDecl *decl)
2595 struct pet_array *array;
2596 QualType qt = decl->getType();
2597 const Type *type = qt.getTypePtr();
2598 int depth = array_depth(type);
2599 QualType base = base_type(qt);
2600 string name;
2601 isl_id *id;
2602 isl_space *dim;
2604 array = isl_calloc_type(ctx, struct pet_array);
2605 if (!array)
2606 return NULL;
2608 id = isl_id_alloc(ctx, decl->getName().str().c_str(), decl);
2609 dim = isl_space_set_alloc(ctx, 0, depth);
2610 dim = isl_space_set_tuple_id(dim, isl_dim_set, id);
2612 array->extent = isl_set_nat_universe(dim);
2614 dim = isl_space_params_alloc(ctx, 0);
2615 array->context = isl_set_universe(dim);
2617 array = set_upper_bounds(array, type, 0);
2618 if (!array)
2619 return NULL;
2621 name = base.getAsString();
2622 array->element_type = strdup(name.c_str());
2624 return array;
2627 /* Construct a list of pet_arrays, one for each array (or scalar)
2628 * accessed inside "scop" add this list to "scop" and return the result.
2630 * The context of "scop" is updated with the intesection of
2631 * the contexts of all arrays, i.e., constraints on the parameters
2632 * that ensure that the arrays have a valid (non-negative) size.
2634 struct pet_scop *PetScan::scan_arrays(struct pet_scop *scop)
2636 int i;
2637 set<ValueDecl *> arrays;
2638 set<ValueDecl *>::iterator it;
2639 int n_array;
2640 struct pet_array **scop_arrays;
2642 if (!scop)
2643 return NULL;
2645 pet_scop_collect_arrays(scop, arrays);
2646 if (arrays.size() == 0)
2647 return scop;
2649 n_array = scop->n_array;
2651 scop_arrays = isl_realloc_array(ctx, scop->arrays, struct pet_array *,
2652 n_array + arrays.size());
2653 if (!scop_arrays)
2654 goto error;
2655 scop->arrays = scop_arrays;
2657 for (it = arrays.begin(), i = 0; it != arrays.end(); ++it, ++i) {
2658 struct pet_array *array;
2659 scop->arrays[n_array + i] = array = extract_array(ctx, *it);
2660 if (!scop->arrays[n_array + i])
2661 goto error;
2662 scop->n_array++;
2663 scop->context = isl_set_intersect(scop->context,
2664 isl_set_copy(array->context));
2665 if (!scop->context)
2666 goto error;
2669 return scop;
2670 error:
2671 pet_scop_free(scop);
2672 return NULL;
2675 /* Construct a pet_scop from the given function.
2677 struct pet_scop *PetScan::scan(FunctionDecl *fd)
2679 pet_scop *scop;
2680 Stmt *stmt;
2682 stmt = fd->getBody();
2684 if (autodetect)
2685 scop = extract(stmt);
2686 else
2687 scop = scan(stmt);
2688 scop = pet_scop_detect_parameter_accesses(scop);
2689 scop = scan_arrays(scop);
2691 return scop;