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