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