1 //===------ IslExprBuilder.cpp ----- Code generate isl AST expressions ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //===----------------------------------------------------------------------===//
11 
12 #include "polly/CodeGen/IslExprBuilder.h"
13 #include "polly/Options.h"
14 #include "polly/ScopInfo.h"
15 #include "polly/Support/GICHelper.h"
16 #include "polly/Support/ScopHelper.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
19 
20 using namespace llvm;
21 using namespace polly;
22 
23 /// @brief Different overflow tracking modes.
24 enum OverflowTrackingChoice {
25   OT_NEVER,   ///< Never tack potential overflows.
26   OT_REQUEST, ///< Track potential overflows if requested.
27   OT_ALWAYS   ///< Always track potential overflows.
28 };
29 
30 static cl::opt<OverflowTrackingChoice> OTMode(
31     "polly-overflow-tracking",
32     cl::desc("Define where potential integer overflows in generated "
33              "expressions should be tracked."),
34     cl::values(clEnumValN(OT_NEVER, "never", "Never track the overflow bit."),
35                clEnumValN(OT_REQUEST, "request",
36                           "Track the overflow bit if requested."),
37                clEnumValN(OT_ALWAYS, "always",
38                           "Always track the overflow bit."),
39                clEnumValEnd),
40     cl::Hidden, cl::init(OT_REQUEST), cl::ZeroOrMore, cl::cat(PollyCategory));
41 
42 IslExprBuilder::IslExprBuilder(Scop &S, PollyIRBuilder &Builder,
43                                IDToValueTy &IDToValue, ValueMapT &GlobalMap,
44                                const DataLayout &DL, ScalarEvolution &SE,
45                                DominatorTree &DT, LoopInfo &LI)
46     : S(S), Builder(Builder), IDToValue(IDToValue), GlobalMap(GlobalMap),
47       DL(DL), SE(SE), DT(DT), LI(LI) {
48   OverflowState = (OTMode == OT_ALWAYS) ? Builder.getFalse() : nullptr;
49 }
50 
51 void IslExprBuilder::setTrackOverflow(bool Enable) {
52   // If potential overflows are tracked always or never we ignore requests
53   // to change the behaviour.
54   if (OTMode != OT_REQUEST)
55     return;
56 
57   if (Enable) {
58     // If tracking should be enabled initialize the OverflowState.
59     OverflowState = Builder.getFalse();
60   } else {
61     // If tracking should be disabled just unset the OverflowState.
62     OverflowState = nullptr;
63   }
64 }
65 
66 Value *IslExprBuilder::getOverflowState() const {
67   // If the overflow tracking was requested but it is disabled we avoid the
68   // additional nullptr checks at the call sides but instead provide a
69   // meaningful result.
70   if (OTMode == OT_NEVER)
71     return Builder.getFalse();
72   return OverflowState;
73 }
74 
75 Value *IslExprBuilder::createBinOp(BinaryOperator::BinaryOps Opc, Value *LHS,
76                                    Value *RHS, const Twine &Name) {
77   // Handle the plain operation (without overflow tracking) first.
78   if (!OverflowState) {
79     switch (Opc) {
80     case Instruction::Add:
81       return Builder.CreateNSWAdd(LHS, RHS, Name);
82     case Instruction::Sub:
83       return Builder.CreateNSWSub(LHS, RHS, Name);
84     case Instruction::Mul:
85       return Builder.CreateNSWMul(LHS, RHS, Name);
86     default:
87       llvm_unreachable("Unknown binary operator!");
88     }
89   }
90 
91   Function *F = nullptr;
92   Module *M = Builder.GetInsertBlock()->getModule();
93   switch (Opc) {
94   case Instruction::Add:
95     F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
96                                   {LHS->getType()});
97     break;
98   case Instruction::Sub:
99     F = Intrinsic::getDeclaration(M, Intrinsic::ssub_with_overflow,
100                                   {LHS->getType()});
101     break;
102   case Instruction::Mul:
103     F = Intrinsic::getDeclaration(M, Intrinsic::smul_with_overflow,
104                                   {LHS->getType()});
105     break;
106   default:
107     llvm_unreachable("No overflow intrinsic for binary operator found!");
108   }
109 
110   auto *ResultStruct = Builder.CreateCall(F, {LHS, RHS}, Name);
111   assert(ResultStruct->getType()->isStructTy());
112 
113   auto *OverflowFlag =
114       Builder.CreateExtractValue(ResultStruct, 1, Name + ".obit");
115 
116   // If all overflows are tracked we do not combine the results as this could
117   // cause dominance problems. Instead we will always keep the last overflow
118   // flag as current state.
119   if (OTMode == OT_ALWAYS)
120     OverflowState = OverflowFlag;
121   else
122     OverflowState =
123         Builder.CreateOr(OverflowState, OverflowFlag, "polly.overflow.state");
124 
125   return Builder.CreateExtractValue(ResultStruct, 0, Name + ".res");
126 }
127 
128 Value *IslExprBuilder::createAdd(Value *LHS, Value *RHS, const Twine &Name) {
129   return createBinOp(Instruction::Add, LHS, RHS, Name);
130 }
131 
132 Value *IslExprBuilder::createSub(Value *LHS, Value *RHS, const Twine &Name) {
133   return createBinOp(Instruction::Sub, LHS, RHS, Name);
134 }
135 
136 Value *IslExprBuilder::createMul(Value *LHS, Value *RHS, const Twine &Name) {
137   return createBinOp(Instruction::Mul, LHS, RHS, Name);
138 }
139 
140 Type *IslExprBuilder::getWidestType(Type *T1, Type *T2) {
141   assert(isa<IntegerType>(T1) && isa<IntegerType>(T2));
142 
143   if (T1->getPrimitiveSizeInBits() < T2->getPrimitiveSizeInBits())
144     return T2;
145   else
146     return T1;
147 }
148 
149 Value *IslExprBuilder::createOpUnary(__isl_take isl_ast_expr *Expr) {
150   assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_minus &&
151          "Unsupported unary operation");
152 
153   Value *V;
154   Type *MaxType = getType(Expr);
155   assert(MaxType->isIntegerTy() &&
156          "Unary expressions can only be created for integer types");
157 
158   V = create(isl_ast_expr_get_op_arg(Expr, 0));
159   MaxType = getWidestType(MaxType, V->getType());
160 
161   if (MaxType != V->getType())
162     V = Builder.CreateSExt(V, MaxType);
163 
164   isl_ast_expr_free(Expr);
165   return createSub(ConstantInt::getNullValue(MaxType), V);
166 }
167 
168 Value *IslExprBuilder::createOpNAry(__isl_take isl_ast_expr *Expr) {
169   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
170          "isl ast expression not of type isl_ast_op");
171   assert(isl_ast_expr_get_op_n_arg(Expr) >= 2 &&
172          "We need at least two operands in an n-ary operation");
173 
174   CmpInst::Predicate Pred;
175   switch (isl_ast_expr_get_op_type(Expr)) {
176   default:
177     llvm_unreachable("This is not a an n-ary isl ast expression");
178   case isl_ast_op_max:
179     Pred = CmpInst::ICMP_SGT;
180     break;
181   case isl_ast_op_min:
182     Pred = CmpInst::ICMP_SLT;
183     break;
184   }
185 
186   Value *V = create(isl_ast_expr_get_op_arg(Expr, 0));
187 
188   for (int i = 1; i < isl_ast_expr_get_op_n_arg(Expr); ++i) {
189     Value *OpV = create(isl_ast_expr_get_op_arg(Expr, i));
190     Type *Ty = getWidestType(V->getType(), OpV->getType());
191 
192     if (Ty != OpV->getType())
193       OpV = Builder.CreateSExt(OpV, Ty);
194 
195     if (Ty != V->getType())
196       V = Builder.CreateSExt(V, Ty);
197 
198     Value *Cmp = Builder.CreateICmp(Pred, V, OpV);
199     V = Builder.CreateSelect(Cmp, V, OpV);
200   }
201 
202   // TODO: We can truncate the result, if it fits into a smaller type. This can
203   // help in cases where we have larger operands (e.g. i67) but the result is
204   // known to fit into i64. Without the truncation, the larger i67 type may
205   // force all subsequent operations to be performed on a non-native type.
206   isl_ast_expr_free(Expr);
207   return V;
208 }
209 
210 Value *IslExprBuilder::createAccessAddress(isl_ast_expr *Expr) {
211   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
212          "isl ast expression not of type isl_ast_op");
213   assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_access &&
214          "not an access isl ast expression");
215   assert(isl_ast_expr_get_op_n_arg(Expr) >= 2 &&
216          "We need at least two operands to create a member access.");
217 
218   Value *Base, *IndexOp, *Access;
219   isl_ast_expr *BaseExpr;
220   isl_id *BaseId;
221 
222   BaseExpr = isl_ast_expr_get_op_arg(Expr, 0);
223   BaseId = isl_ast_expr_get_id(BaseExpr);
224   isl_ast_expr_free(BaseExpr);
225 
226   const ScopArrayInfo *SAI = nullptr;
227 
228   if (IDToSAI)
229     SAI = (*IDToSAI)[BaseId];
230 
231   if (!SAI)
232     SAI = ScopArrayInfo::getFromId(BaseId);
233   else
234     isl_id_free(BaseId);
235 
236   assert(SAI && "No ScopArrayInfo found for this isl_id.");
237 
238   Base = SAI->getBasePtr();
239 
240   if (auto NewBase = GlobalMap.lookup(Base))
241     Base = NewBase;
242 
243   assert(Base->getType()->isPointerTy() && "Access base should be a pointer");
244   StringRef BaseName = Base->getName();
245 
246   auto PointerTy = PointerType::get(SAI->getElementType(),
247                                     Base->getType()->getPointerAddressSpace());
248   if (Base->getType() != PointerTy) {
249     Base =
250         Builder.CreateBitCast(Base, PointerTy, "polly.access.cast." + BaseName);
251   }
252 
253   IndexOp = nullptr;
254   for (unsigned u = 1, e = isl_ast_expr_get_op_n_arg(Expr); u < e; u++) {
255     Value *NextIndex = create(isl_ast_expr_get_op_arg(Expr, u));
256     assert(NextIndex->getType()->isIntegerTy() &&
257            "Access index should be an integer");
258 
259     if (!IndexOp) {
260       IndexOp = NextIndex;
261     } else {
262       Type *Ty = getWidestType(NextIndex->getType(), IndexOp->getType());
263 
264       if (Ty != NextIndex->getType())
265         NextIndex = Builder.CreateIntCast(NextIndex, Ty, true);
266       if (Ty != IndexOp->getType())
267         IndexOp = Builder.CreateIntCast(IndexOp, Ty, true);
268 
269       IndexOp = createAdd(IndexOp, NextIndex, "polly.access.add." + BaseName);
270     }
271 
272     // For every but the last dimension multiply the size, for the last
273     // dimension we can exit the loop.
274     if (u + 1 >= e)
275       break;
276 
277     const SCEV *DimSCEV = SAI->getDimensionSize(u);
278 
279     llvm::ValueToValueMap Map(GlobalMap.begin(), GlobalMap.end());
280     DimSCEV = SCEVParameterRewriter::rewrite(DimSCEV, SE, Map);
281     Value *DimSize =
282         expandCodeFor(S, SE, DL, "polly", DimSCEV, DimSCEV->getType(),
283                       &*Builder.GetInsertPoint());
284 
285     Type *Ty = getWidestType(DimSize->getType(), IndexOp->getType());
286 
287     if (Ty != IndexOp->getType())
288       IndexOp = Builder.CreateSExtOrTrunc(IndexOp, Ty,
289                                           "polly.access.sext." + BaseName);
290     if (Ty != DimSize->getType())
291       DimSize = Builder.CreateSExtOrTrunc(DimSize, Ty,
292                                           "polly.access.sext." + BaseName);
293     IndexOp = createMul(IndexOp, DimSize, "polly.access.mul." + BaseName);
294   }
295 
296   Access = Builder.CreateGEP(Base, IndexOp, "polly.access." + BaseName);
297 
298   isl_ast_expr_free(Expr);
299   return Access;
300 }
301 
302 Value *IslExprBuilder::createOpAccess(isl_ast_expr *Expr) {
303   Value *Addr = createAccessAddress(Expr);
304   assert(Addr && "Could not create op access address");
305   return Builder.CreateLoad(Addr, Addr->getName() + ".load");
306 }
307 
308 Value *IslExprBuilder::createOpBin(__isl_take isl_ast_expr *Expr) {
309   Value *LHS, *RHS, *Res;
310   Type *MaxType;
311   isl_ast_op_type OpType;
312 
313   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
314          "isl ast expression not of type isl_ast_op");
315   assert(isl_ast_expr_get_op_n_arg(Expr) == 2 &&
316          "not a binary isl ast expression");
317 
318   OpType = isl_ast_expr_get_op_type(Expr);
319 
320   LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
321   RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
322 
323   Type *LHSType = LHS->getType();
324   Type *RHSType = RHS->getType();
325 
326   MaxType = getWidestType(LHSType, RHSType);
327 
328   // Take the result into account when calculating the widest type.
329   //
330   // For operations such as '+' the result may require a type larger than
331   // the type of the individual operands. For other operations such as '/', the
332   // result type cannot be larger than the type of the individual operand. isl
333   // does not calculate correct types for these operations and we consequently
334   // exclude those operations here.
335   switch (OpType) {
336   case isl_ast_op_pdiv_q:
337   case isl_ast_op_pdiv_r:
338   case isl_ast_op_div:
339   case isl_ast_op_fdiv_q:
340   case isl_ast_op_zdiv_r:
341     // Do nothing
342     break;
343   case isl_ast_op_add:
344   case isl_ast_op_sub:
345   case isl_ast_op_mul:
346     MaxType = getWidestType(MaxType, getType(Expr));
347     break;
348   default:
349     llvm_unreachable("This is no binary isl ast expression");
350   }
351 
352   if (MaxType != RHS->getType())
353     RHS = Builder.CreateSExt(RHS, MaxType);
354 
355   if (MaxType != LHS->getType())
356     LHS = Builder.CreateSExt(LHS, MaxType);
357 
358   switch (OpType) {
359   default:
360     llvm_unreachable("This is no binary isl ast expression");
361   case isl_ast_op_add:
362     Res = createAdd(LHS, RHS);
363     break;
364   case isl_ast_op_sub:
365     Res = createSub(LHS, RHS);
366     break;
367   case isl_ast_op_mul:
368     Res = createMul(LHS, RHS);
369     break;
370   case isl_ast_op_div:
371     Res = Builder.CreateSDiv(LHS, RHS, "pexp.div", true);
372     break;
373   case isl_ast_op_pdiv_q: // Dividend is non-negative
374     Res = Builder.CreateUDiv(LHS, RHS, "pexp.p_div_q");
375     break;
376   case isl_ast_op_fdiv_q: { // Round towards -infty
377     if (auto *Const = dyn_cast<ConstantInt>(RHS)) {
378       auto &Val = Const->getValue();
379       if (Val.isPowerOf2() && Val.isNonNegative()) {
380         Res = Builder.CreateAShr(LHS, Val.ceilLogBase2(), "polly.fdiv_q.shr");
381         break;
382       }
383     }
384     // TODO: Review code and check that this calculation does not yield
385     //       incorrect overflow in some bordercases.
386     //
387     // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
388     Value *One = ConstantInt::get(MaxType, 1);
389     Value *Zero = ConstantInt::get(MaxType, 0);
390     Value *Sum1 = createSub(LHS, RHS, "pexp.fdiv_q.0");
391     Value *Sum2 = createAdd(Sum1, One, "pexp.fdiv_q.1");
392     Value *isNegative = Builder.CreateICmpSLT(LHS, Zero, "pexp.fdiv_q.2");
393     Value *Dividend =
394         Builder.CreateSelect(isNegative, Sum2, LHS, "pexp.fdiv_q.3");
395     Res = Builder.CreateSDiv(Dividend, RHS, "pexp.fdiv_q.4");
396     break;
397   }
398   case isl_ast_op_pdiv_r: // Dividend is non-negative
399     Res = Builder.CreateURem(LHS, RHS, "pexp.pdiv_r");
400     break;
401 
402   case isl_ast_op_zdiv_r: // Result only compared against zero
403     Res = Builder.CreateSRem(LHS, RHS, "pexp.zdiv_r");
404     break;
405   }
406 
407   // TODO: We can truncate the result, if it fits into a smaller type. This can
408   // help in cases where we have larger operands (e.g. i67) but the result is
409   // known to fit into i64. Without the truncation, the larger i67 type may
410   // force all subsequent operations to be performed on a non-native type.
411   isl_ast_expr_free(Expr);
412   return Res;
413 }
414 
415 Value *IslExprBuilder::createOpSelect(__isl_take isl_ast_expr *Expr) {
416   assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_select &&
417          "Unsupported unary isl ast expression");
418   Value *LHS, *RHS, *Cond;
419   Type *MaxType = getType(Expr);
420 
421   Cond = create(isl_ast_expr_get_op_arg(Expr, 0));
422   if (!Cond->getType()->isIntegerTy(1))
423     Cond = Builder.CreateIsNotNull(Cond);
424 
425   LHS = create(isl_ast_expr_get_op_arg(Expr, 1));
426   RHS = create(isl_ast_expr_get_op_arg(Expr, 2));
427 
428   MaxType = getWidestType(MaxType, LHS->getType());
429   MaxType = getWidestType(MaxType, RHS->getType());
430 
431   if (MaxType != RHS->getType())
432     RHS = Builder.CreateSExt(RHS, MaxType);
433 
434   if (MaxType != LHS->getType())
435     LHS = Builder.CreateSExt(LHS, MaxType);
436 
437   // TODO: Do we want to truncate the result?
438   isl_ast_expr_free(Expr);
439   return Builder.CreateSelect(Cond, LHS, RHS);
440 }
441 
442 Value *IslExprBuilder::createOpICmp(__isl_take isl_ast_expr *Expr) {
443   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
444          "Expected an isl_ast_expr_op expression");
445 
446   Value *LHS, *RHS, *Res;
447 
448   auto *Op0 = isl_ast_expr_get_op_arg(Expr, 0);
449   auto *Op1 = isl_ast_expr_get_op_arg(Expr, 1);
450   bool HasNonAddressOfOperand =
451       isl_ast_expr_get_type(Op0) != isl_ast_expr_op ||
452       isl_ast_expr_get_type(Op1) != isl_ast_expr_op ||
453       isl_ast_expr_get_op_type(Op0) != isl_ast_op_address_of ||
454       isl_ast_expr_get_op_type(Op1) != isl_ast_op_address_of;
455 
456   LHS = create(Op0);
457   RHS = create(Op1);
458 
459   auto *LHSTy = LHS->getType();
460   auto *RHSTy = RHS->getType();
461   bool IsPtrType = LHSTy->isPointerTy() || RHSTy->isPointerTy();
462   bool UseUnsignedCmp = IsPtrType && !HasNonAddressOfOperand;
463 
464   auto *PtrAsIntTy = Builder.getIntNTy(DL.getPointerSizeInBits());
465   if (LHSTy->isPointerTy())
466     LHS = Builder.CreatePtrToInt(LHS, PtrAsIntTy);
467   if (RHSTy->isPointerTy())
468     RHS = Builder.CreatePtrToInt(RHS, PtrAsIntTy);
469 
470   if (LHS->getType() != RHS->getType()) {
471     Type *MaxType = LHS->getType();
472     MaxType = getWidestType(MaxType, RHS->getType());
473 
474     if (MaxType != RHS->getType())
475       RHS = Builder.CreateSExt(RHS, MaxType);
476 
477     if (MaxType != LHS->getType())
478       LHS = Builder.CreateSExt(LHS, MaxType);
479   }
480 
481   isl_ast_op_type OpType = isl_ast_expr_get_op_type(Expr);
482   assert(OpType >= isl_ast_op_eq && OpType <= isl_ast_op_gt &&
483          "Unsupported ICmp isl ast expression");
484   assert(isl_ast_op_eq + 4 == isl_ast_op_gt &&
485          "Isl ast op type interface changed");
486 
487   CmpInst::Predicate Predicates[5][2] = {
488       {CmpInst::ICMP_EQ, CmpInst::ICMP_EQ},
489       {CmpInst::ICMP_SLE, CmpInst::ICMP_ULE},
490       {CmpInst::ICMP_SLT, CmpInst::ICMP_ULT},
491       {CmpInst::ICMP_SGE, CmpInst::ICMP_UGE},
492       {CmpInst::ICMP_SGT, CmpInst::ICMP_UGT},
493   };
494 
495   Res = Builder.CreateICmp(Predicates[OpType - isl_ast_op_eq][UseUnsignedCmp],
496                            LHS, RHS);
497 
498   isl_ast_expr_free(Expr);
499   return Res;
500 }
501 
502 Value *IslExprBuilder::createOpBoolean(__isl_take isl_ast_expr *Expr) {
503   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
504          "Expected an isl_ast_expr_op expression");
505 
506   Value *LHS, *RHS, *Res;
507   isl_ast_op_type OpType;
508 
509   OpType = isl_ast_expr_get_op_type(Expr);
510 
511   assert((OpType == isl_ast_op_and || OpType == isl_ast_op_or) &&
512          "Unsupported isl_ast_op_type");
513 
514   LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
515   RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
516 
517   // Even though the isl pretty printer prints the expressions as 'exp && exp'
518   // or 'exp || exp', we actually code generate the bitwise expressions
519   // 'exp & exp' or 'exp | exp'. This forces the evaluation of both branches,
520   // but it is, due to the use of i1 types, otherwise equivalent. The reason
521   // to go for bitwise operations is, that we assume the reduced control flow
522   // will outweight the overhead introduced by evaluating unneeded expressions.
523   // The isl code generation currently does not take advantage of the fact that
524   // the expression after an '||' or '&&' is in some cases not evaluated.
525   // Evaluating it anyways does not cause any undefined behaviour.
526   //
527   // TODO: Document in isl itself, that the unconditionally evaluating the
528   // second part of '||' or '&&' expressions is safe.
529   if (!LHS->getType()->isIntegerTy(1))
530     LHS = Builder.CreateIsNotNull(LHS);
531   if (!RHS->getType()->isIntegerTy(1))
532     RHS = Builder.CreateIsNotNull(RHS);
533 
534   switch (OpType) {
535   default:
536     llvm_unreachable("Unsupported boolean expression");
537   case isl_ast_op_and:
538     Res = Builder.CreateAnd(LHS, RHS);
539     break;
540   case isl_ast_op_or:
541     Res = Builder.CreateOr(LHS, RHS);
542     break;
543   }
544 
545   isl_ast_expr_free(Expr);
546   return Res;
547 }
548 
549 Value *
550 IslExprBuilder::createOpBooleanConditional(__isl_take isl_ast_expr *Expr) {
551   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
552          "Expected an isl_ast_expr_op expression");
553 
554   Value *LHS, *RHS;
555   isl_ast_op_type OpType;
556 
557   Function *F = Builder.GetInsertBlock()->getParent();
558   LLVMContext &Context = F->getContext();
559 
560   OpType = isl_ast_expr_get_op_type(Expr);
561 
562   assert((OpType == isl_ast_op_and_then || OpType == isl_ast_op_or_else) &&
563          "Unsupported isl_ast_op_type");
564 
565   auto InsertBB = Builder.GetInsertBlock();
566   auto InsertPoint = Builder.GetInsertPoint();
567   auto NextBB = SplitBlock(InsertBB, &*InsertPoint, &DT, &LI);
568   BasicBlock *CondBB = BasicBlock::Create(Context, "polly.cond", F);
569   LI.changeLoopFor(CondBB, LI.getLoopFor(InsertBB));
570   DT.addNewBlock(CondBB, InsertBB);
571 
572   InsertBB->getTerminator()->eraseFromParent();
573   Builder.SetInsertPoint(InsertBB);
574   auto BR = Builder.CreateCondBr(Builder.getTrue(), NextBB, CondBB);
575 
576   Builder.SetInsertPoint(CondBB);
577   Builder.CreateBr(NextBB);
578 
579   Builder.SetInsertPoint(InsertBB->getTerminator());
580 
581   LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
582   if (!LHS->getType()->isIntegerTy(1))
583     LHS = Builder.CreateIsNotNull(LHS);
584   auto LeftBB = Builder.GetInsertBlock();
585 
586   if (OpType == isl_ast_op_and || OpType == isl_ast_op_and_then)
587     BR->setCondition(Builder.CreateNeg(LHS));
588   else
589     BR->setCondition(LHS);
590 
591   Builder.SetInsertPoint(CondBB->getTerminator());
592   RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
593   if (!RHS->getType()->isIntegerTy(1))
594     RHS = Builder.CreateIsNotNull(RHS);
595   auto RightBB = Builder.GetInsertBlock();
596 
597   Builder.SetInsertPoint(NextBB->getTerminator());
598   auto PHI = Builder.CreatePHI(Builder.getInt1Ty(), 2);
599   PHI->addIncoming(OpType == isl_ast_op_and_then ? Builder.getFalse()
600                                                  : Builder.getTrue(),
601                    LeftBB);
602   PHI->addIncoming(RHS, RightBB);
603 
604   isl_ast_expr_free(Expr);
605   return PHI;
606 }
607 
608 Value *IslExprBuilder::createOp(__isl_take isl_ast_expr *Expr) {
609   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
610          "Expression not of type isl_ast_expr_op");
611   switch (isl_ast_expr_get_op_type(Expr)) {
612   case isl_ast_op_error:
613   case isl_ast_op_cond:
614   case isl_ast_op_call:
615   case isl_ast_op_member:
616     llvm_unreachable("Unsupported isl ast expression");
617   case isl_ast_op_access:
618     return createOpAccess(Expr);
619   case isl_ast_op_max:
620   case isl_ast_op_min:
621     return createOpNAry(Expr);
622   case isl_ast_op_add:
623   case isl_ast_op_sub:
624   case isl_ast_op_mul:
625   case isl_ast_op_div:
626   case isl_ast_op_fdiv_q: // Round towards -infty
627   case isl_ast_op_pdiv_q: // Dividend is non-negative
628   case isl_ast_op_pdiv_r: // Dividend is non-negative
629   case isl_ast_op_zdiv_r: // Result only compared against zero
630     return createOpBin(Expr);
631   case isl_ast_op_minus:
632     return createOpUnary(Expr);
633   case isl_ast_op_select:
634     return createOpSelect(Expr);
635   case isl_ast_op_and:
636   case isl_ast_op_or:
637     return createOpBoolean(Expr);
638   case isl_ast_op_and_then:
639   case isl_ast_op_or_else:
640     return createOpBooleanConditional(Expr);
641   case isl_ast_op_eq:
642   case isl_ast_op_le:
643   case isl_ast_op_lt:
644   case isl_ast_op_ge:
645   case isl_ast_op_gt:
646     return createOpICmp(Expr);
647   case isl_ast_op_address_of:
648     return createOpAddressOf(Expr);
649   }
650 
651   llvm_unreachable("Unsupported isl_ast_expr_op kind.");
652 }
653 
654 Value *IslExprBuilder::createOpAddressOf(__isl_take isl_ast_expr *Expr) {
655   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
656          "Expected an isl_ast_expr_op expression.");
657   assert(isl_ast_expr_get_op_n_arg(Expr) == 1 && "Address of should be unary.");
658 
659   isl_ast_expr *Op = isl_ast_expr_get_op_arg(Expr, 0);
660   assert(isl_ast_expr_get_type(Op) == isl_ast_expr_op &&
661          "Expected address of operator to be an isl_ast_expr_op expression.");
662   assert(isl_ast_expr_get_op_type(Op) == isl_ast_op_access &&
663          "Expected address of operator to be an access expression.");
664 
665   Value *V = createAccessAddress(Op);
666 
667   isl_ast_expr_free(Expr);
668 
669   return V;
670 }
671 
672 Value *IslExprBuilder::createId(__isl_take isl_ast_expr *Expr) {
673   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_id &&
674          "Expression not of type isl_ast_expr_ident");
675 
676   isl_id *Id;
677   Value *V;
678 
679   Id = isl_ast_expr_get_id(Expr);
680 
681   assert(IDToValue.count(Id) && "Identifier not found");
682 
683   V = IDToValue[Id];
684   if (!V)
685     V = UndefValue::get(getType(Expr));
686 
687   if (V->getType()->isPointerTy())
688     V = Builder.CreatePtrToInt(V, Builder.getIntNTy(DL.getPointerSizeInBits()));
689 
690   assert(V && "Unknown parameter id found");
691 
692   isl_id_free(Id);
693   isl_ast_expr_free(Expr);
694 
695   return V;
696 }
697 
698 IntegerType *IslExprBuilder::getType(__isl_keep isl_ast_expr *Expr) {
699   // XXX: We assume i64 is large enough. This is often true, but in general
700   //      incorrect. Also, on 32bit architectures, it would be beneficial to
701   //      use a smaller type. We can and should directly derive this information
702   //      during code generation.
703   return IntegerType::get(Builder.getContext(), 64);
704 }
705 
706 Value *IslExprBuilder::createInt(__isl_take isl_ast_expr *Expr) {
707   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_int &&
708          "Expression not of type isl_ast_expr_int");
709   isl_val *Val;
710   Value *V;
711   APInt APValue;
712   IntegerType *T;
713 
714   Val = isl_ast_expr_get_val(Expr);
715   APValue = APIntFromVal(Val);
716 
717   auto BitWidth = APValue.getBitWidth();
718   if (BitWidth <= 64)
719     T = getType(Expr);
720   else
721     T = Builder.getIntNTy(BitWidth);
722 
723   APValue = APValue.sextOrSelf(T->getBitWidth());
724   V = ConstantInt::get(T, APValue);
725 
726   isl_ast_expr_free(Expr);
727   return V;
728 }
729 
730 Value *IslExprBuilder::create(__isl_take isl_ast_expr *Expr) {
731   switch (isl_ast_expr_get_type(Expr)) {
732   case isl_ast_expr_error:
733     llvm_unreachable("Code generation error");
734   case isl_ast_expr_op:
735     return createOp(Expr);
736   case isl_ast_expr_id:
737     return createId(Expr);
738   case isl_ast_expr_int:
739     return createInt(Expr);
740   }
741 
742   llvm_unreachable("Unexpected enum value");
743 }
744