1 //===- ScopBuilder.cpp ---------------------------------------------------===// 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 // Create a polyhedral description for a static control flow region. 11 // 12 // The pass creates a polyhedral description of the Scops detected by the SCoP 13 // detection derived from their LLVM-IR code. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "polly/ScopBuilder.h" 18 #include "polly/Options.h" 19 #include "polly/Support/GICHelper.h" 20 #include "polly/Support/SCEVValidator.h" 21 #include "llvm/Analysis/RegionIterator.h" 22 #include "llvm/IR/DiagnosticInfo.h" 23 24 using namespace llvm; 25 using namespace polly; 26 27 #define DEBUG_TYPE "polly-scops" 28 29 STATISTIC(ScopFound, "Number of valid Scops"); 30 STATISTIC(RichScopFound, "Number of Scops containing a loop"); 31 32 // If the loop is nonaffine/boxed, return the first non-boxed surrounding loop 33 // for Polly. If the loop is affine, return the loop itself. Do not call 34 // `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need 35 // to analyze the memory accesses of the nonaffine/boxed loops. 36 static Loop *getFirstNonBoxedLoopFor(Loop *L, LoopInfo &LI, 37 const BoxedLoopsSetTy &BoxedLoops) { 38 while (BoxedLoops.count(L)) 39 L = L->getParentLoop(); 40 return L; 41 } 42 43 static cl::opt<bool> ModelReadOnlyScalars( 44 "polly-analyze-read-only-scalars", 45 cl::desc("Model read-only scalar values in the scop description"), 46 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory)); 47 48 void ScopBuilder::buildPHIAccesses(PHINode *PHI, Region *NonAffineSubRegion, 49 bool IsExitBlock) { 50 51 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is 52 // true, are not modeled as ordinary PHI nodes as they are not part of the 53 // region. However, we model the operands in the predecessor blocks that are 54 // part of the region as regular scalar accesses. 55 56 // If we can synthesize a PHI we can skip it, however only if it is in 57 // the region. If it is not it can only be in the exit block of the region. 58 // In this case we model the operands but not the PHI itself. 59 auto *Scope = LI.getLoopFor(PHI->getParent()); 60 if (!IsExitBlock && canSynthesize(PHI, *scop, &LI, &SE, Scope)) 61 return; 62 63 // PHI nodes are modeled as if they had been demoted prior to the SCoP 64 // detection. Hence, the PHI is a load of a new memory location in which the 65 // incoming value was written at the end of the incoming basic block. 66 bool OnlyNonAffineSubRegionOperands = true; 67 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) { 68 Value *Op = PHI->getIncomingValue(u); 69 BasicBlock *OpBB = PHI->getIncomingBlock(u); 70 71 // Do not build PHI dependences inside a non-affine subregion, but make 72 // sure that the necessary scalar values are still made available. 73 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB)) { 74 auto *OpInst = dyn_cast<Instruction>(Op); 75 if (!OpInst || !NonAffineSubRegion->contains(OpInst)) 76 ensureValueRead(Op, OpBB); 77 continue; 78 } 79 80 OnlyNonAffineSubRegionOperands = false; 81 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock); 82 } 83 84 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) { 85 addPHIReadAccess(PHI); 86 } 87 } 88 89 void ScopBuilder::buildScalarDependences(Instruction *Inst) { 90 assert(!isa<PHINode>(Inst)); 91 92 // Pull-in required operands. 93 for (Use &Op : Inst->operands()) 94 ensureValueRead(Op.get(), Inst->getParent()); 95 } 96 97 void ScopBuilder::buildEscapingDependences(Instruction *Inst) { 98 // Check for uses of this instruction outside the scop. Because we do not 99 // iterate over such instructions and therefore did not "ensure" the existence 100 // of a write, we must determine such use here. 101 for (Use &U : Inst->uses()) { 102 Instruction *UI = dyn_cast<Instruction>(U.getUser()); 103 if (!UI) 104 continue; 105 106 BasicBlock *UseParent = getUseBlock(U); 107 BasicBlock *UserParent = UI->getParent(); 108 109 // An escaping value is either used by an instruction not within the scop, 110 // or (when the scop region's exit needs to be simplified) by a PHI in the 111 // scop's exit block. This is because region simplification before code 112 // generation inserts new basic blocks before the PHI such that its incoming 113 // blocks are not in the scop anymore. 114 if (!scop->contains(UseParent) || 115 (isa<PHINode>(UI) && scop->isExit(UserParent) && 116 scop->hasSingleExitEdge())) { 117 // At least one escaping use found. 118 ensureValueWrite(Inst); 119 break; 120 } 121 } 122 } 123 124 bool ScopBuilder::buildAccessMultiDimFixed(MemAccInst Inst, Loop *L) { 125 Value *Val = Inst.getValueOperand(); 126 Type *ElementType = Val->getType(); 127 Value *Address = Inst.getPointerOperand(); 128 const SCEV *AccessFunction = SE.getSCEVAtScope(Address, L); 129 const SCEVUnknown *BasePointer = 130 dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction)); 131 enum MemoryAccess::AccessType AccType = 132 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE; 133 134 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) { 135 auto *Src = BitCast->getOperand(0); 136 auto *SrcTy = Src->getType(); 137 auto *DstTy = BitCast->getType(); 138 // Do not try to delinearize non-sized (opaque) pointers. 139 if ((SrcTy->isPointerTy() && !SrcTy->getPointerElementType()->isSized()) || 140 (DstTy->isPointerTy() && !DstTy->getPointerElementType()->isSized())) { 141 return false; 142 } 143 if (SrcTy->isPointerTy() && DstTy->isPointerTy() && 144 DL.getTypeAllocSize(SrcTy->getPointerElementType()) == 145 DL.getTypeAllocSize(DstTy->getPointerElementType())) 146 Address = Src; 147 } 148 149 auto *GEP = dyn_cast<GetElementPtrInst>(Address); 150 if (!GEP) 151 return false; 152 153 std::vector<const SCEV *> Subscripts; 154 std::vector<int> Sizes; 155 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE); 156 auto *BasePtr = GEP->getOperand(0); 157 158 if (auto *BasePtrCast = dyn_cast<BitCastInst>(BasePtr)) 159 BasePtr = BasePtrCast->getOperand(0); 160 161 // Check for identical base pointers to ensure that we do not miss index 162 // offsets that have been added before this GEP is applied. 163 if (BasePtr != BasePointer->getValue()) 164 return false; 165 166 std::vector<const SCEV *> SizesSCEV; 167 168 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads(); 169 170 Loop *SurroundingLoop = getFirstNonBoxedLoopFor(L, LI, scop->getBoxedLoops()); 171 for (auto *Subscript : Subscripts) { 172 InvariantLoadsSetTy AccessILS; 173 if (!isAffineExpr(&scop->getRegion(), SurroundingLoop, Subscript, SE, 174 &AccessILS)) 175 return false; 176 177 for (LoadInst *LInst : AccessILS) 178 if (!ScopRIL.count(LInst)) 179 return false; 180 } 181 182 if (Sizes.empty()) 183 return false; 184 185 SizesSCEV.push_back(nullptr); 186 187 for (auto V : Sizes) 188 SizesSCEV.push_back(SE.getSCEV( 189 ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V))); 190 191 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true, 192 Subscripts, SizesSCEV, Val); 193 return true; 194 } 195 196 bool ScopBuilder::buildAccessMultiDimParam(MemAccInst Inst, Loop *L) { 197 if (!PollyDelinearize) 198 return false; 199 200 Value *Address = Inst.getPointerOperand(); 201 Value *Val = Inst.getValueOperand(); 202 Type *ElementType = Val->getType(); 203 unsigned ElementSize = DL.getTypeAllocSize(ElementType); 204 enum MemoryAccess::AccessType AccType = 205 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE; 206 207 const SCEV *AccessFunction = SE.getSCEVAtScope(Address, L); 208 const SCEVUnknown *BasePointer = 209 dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction)); 210 211 assert(BasePointer && "Could not find base pointer"); 212 213 auto &InsnToMemAcc = scop->getInsnToMemAccMap(); 214 auto AccItr = InsnToMemAcc.find(Inst); 215 if (AccItr == InsnToMemAcc.end()) 216 return false; 217 218 std::vector<const SCEV *> Sizes = {nullptr}; 219 220 Sizes.insert(Sizes.end(), AccItr->second.Shape->DelinearizedSizes.begin(), 221 AccItr->second.Shape->DelinearizedSizes.end()); 222 // Remove the element size. This information is already provided by the 223 // ElementSize parameter. In case the element size of this access and the 224 // element size used for delinearization differs the delinearization is 225 // incorrect. Hence, we invalidate the scop. 226 // 227 // TODO: Handle delinearization with differing element sizes. 228 auto DelinearizedSize = 229 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue(); 230 Sizes.pop_back(); 231 if (ElementSize != DelinearizedSize) 232 scop->invalidate(DELINEARIZATION, Inst->getDebugLoc()); 233 234 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true, 235 AccItr->second.DelinearizedSubscripts, Sizes, Val); 236 return true; 237 } 238 239 bool ScopBuilder::buildAccessMemIntrinsic(MemAccInst Inst, Loop *L) { 240 auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst); 241 242 if (MemIntr == nullptr) 243 return false; 244 245 auto *LengthVal = SE.getSCEVAtScope(MemIntr->getLength(), L); 246 assert(LengthVal); 247 248 // Check if the length val is actually affine or if we overapproximate it 249 InvariantLoadsSetTy AccessILS; 250 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads(); 251 252 Loop *SurroundingLoop = getFirstNonBoxedLoopFor(L, LI, scop->getBoxedLoops()); 253 bool LengthIsAffine = isAffineExpr(&scop->getRegion(), SurroundingLoop, 254 LengthVal, SE, &AccessILS); 255 for (LoadInst *LInst : AccessILS) 256 if (!ScopRIL.count(LInst)) 257 LengthIsAffine = false; 258 if (!LengthIsAffine) 259 LengthVal = nullptr; 260 261 auto *DestPtrVal = MemIntr->getDest(); 262 assert(DestPtrVal); 263 264 auto *DestAccFunc = SE.getSCEVAtScope(DestPtrVal, L); 265 assert(DestAccFunc); 266 // Ignore accesses to "NULL". 267 // TODO: We could use this to optimize the region further, e.g., intersect 268 // the context with 269 // isl_set_complement(isl_set_params(getDomain())) 270 // as we know it would be undefined to execute this instruction anyway. 271 if (DestAccFunc->isZero()) 272 return true; 273 274 auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE.getPointerBase(DestAccFunc)); 275 assert(DestPtrSCEV); 276 DestAccFunc = SE.getMinusSCEV(DestAccFunc, DestPtrSCEV); 277 addArrayAccess(Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(), 278 IntegerType::getInt8Ty(DestPtrVal->getContext()), false, 279 {DestAccFunc, LengthVal}, {nullptr}, Inst.getValueOperand()); 280 281 auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr); 282 if (!MemTrans) 283 return true; 284 285 auto *SrcPtrVal = MemTrans->getSource(); 286 assert(SrcPtrVal); 287 288 auto *SrcAccFunc = SE.getSCEVAtScope(SrcPtrVal, L); 289 assert(SrcAccFunc); 290 // Ignore accesses to "NULL". 291 // TODO: See above TODO 292 if (SrcAccFunc->isZero()) 293 return true; 294 295 auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE.getPointerBase(SrcAccFunc)); 296 assert(SrcPtrSCEV); 297 SrcAccFunc = SE.getMinusSCEV(SrcAccFunc, SrcPtrSCEV); 298 addArrayAccess(Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(), 299 IntegerType::getInt8Ty(SrcPtrVal->getContext()), false, 300 {SrcAccFunc, LengthVal}, {nullptr}, Inst.getValueOperand()); 301 302 return true; 303 } 304 305 bool ScopBuilder::buildAccessCallInst(MemAccInst Inst, Loop *L) { 306 auto *CI = dyn_cast_or_null<CallInst>(Inst); 307 308 if (CI == nullptr) 309 return false; 310 311 if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI)) 312 return true; 313 314 bool ReadOnly = false; 315 auto *AF = SE.getConstant(IntegerType::getInt64Ty(CI->getContext()), 0); 316 auto *CalledFunction = CI->getCalledFunction(); 317 switch (AA.getModRefBehavior(CalledFunction)) { 318 case llvm::FMRB_UnknownModRefBehavior: 319 llvm_unreachable("Unknown mod ref behaviour cannot be represented."); 320 case llvm::FMRB_DoesNotAccessMemory: 321 return true; 322 case llvm::FMRB_DoesNotReadMemory: 323 return false; 324 case llvm::FMRB_OnlyReadsMemory: 325 GlobalReads.push_back(CI); 326 return true; 327 case llvm::FMRB_OnlyReadsArgumentPointees: 328 ReadOnly = true; 329 // Fall through 330 case llvm::FMRB_OnlyAccessesArgumentPointees: 331 auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE; 332 for (const auto &Arg : CI->arg_operands()) { 333 if (!Arg->getType()->isPointerTy()) 334 continue; 335 336 auto *ArgSCEV = SE.getSCEVAtScope(Arg, L); 337 if (ArgSCEV->isZero()) 338 continue; 339 340 auto *ArgBasePtr = cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV)); 341 addArrayAccess(Inst, AccType, ArgBasePtr->getValue(), 342 ArgBasePtr->getType(), false, {AF}, {nullptr}, CI); 343 } 344 return true; 345 } 346 347 return true; 348 } 349 350 void ScopBuilder::buildAccessSingleDim(MemAccInst Inst, Loop *L) { 351 Value *Address = Inst.getPointerOperand(); 352 Value *Val = Inst.getValueOperand(); 353 Type *ElementType = Val->getType(); 354 enum MemoryAccess::AccessType AccType = 355 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE; 356 357 const SCEV *AccessFunction = SE.getSCEVAtScope(Address, L); 358 const SCEVUnknown *BasePointer = 359 dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction)); 360 361 assert(BasePointer && "Could not find base pointer"); 362 AccessFunction = SE.getMinusSCEV(AccessFunction, BasePointer); 363 364 // Check if the access depends on a loop contained in a non-affine subregion. 365 bool isVariantInNonAffineLoop = false; 366 SetVector<const Loop *> Loops; 367 auto &BoxedLoops = scop->getBoxedLoops(); 368 findLoops(AccessFunction, Loops); 369 for (const Loop *L : Loops) 370 if (BoxedLoops.count(L)) 371 isVariantInNonAffineLoop = true; 372 373 InvariantLoadsSetTy AccessILS; 374 375 Loop *SurroundingLoop = getFirstNonBoxedLoopFor(L, LI, BoxedLoops); 376 bool IsAffine = !isVariantInNonAffineLoop && 377 isAffineExpr(&scop->getRegion(), SurroundingLoop, 378 AccessFunction, SE, &AccessILS); 379 380 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads(); 381 for (LoadInst *LInst : AccessILS) 382 if (!ScopRIL.count(LInst)) 383 IsAffine = false; 384 385 if (!IsAffine && AccType == MemoryAccess::MUST_WRITE) 386 AccType = MemoryAccess::MAY_WRITE; 387 388 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, IsAffine, 389 {AccessFunction}, {nullptr}, Val); 390 } 391 392 void ScopBuilder::buildMemoryAccess(MemAccInst Inst, Loop *L) { 393 394 if (buildAccessMemIntrinsic(Inst, L)) 395 return; 396 397 if (buildAccessCallInst(Inst, L)) 398 return; 399 400 if (buildAccessMultiDimFixed(Inst, L)) 401 return; 402 403 if (buildAccessMultiDimParam(Inst, L)) 404 return; 405 406 buildAccessSingleDim(Inst, L); 407 } 408 409 void ScopBuilder::buildAccessFunctions(Region &SR) { 410 411 if (scop->isNonAffineSubRegion(&SR)) { 412 for (BasicBlock *BB : SR.blocks()) 413 buildAccessFunctions(*BB, &SR); 414 return; 415 } 416 417 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I) 418 if (I->isSubRegion()) 419 buildAccessFunctions(*I->getNodeAs<Region>()); 420 else 421 buildAccessFunctions(*I->getNodeAs<BasicBlock>()); 422 } 423 424 void ScopBuilder::buildStmts(Region &SR) { 425 426 if (scop->isNonAffineSubRegion(&SR)) { 427 scop->addScopStmt(nullptr, &SR); 428 return; 429 } 430 431 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I) 432 if (I->isSubRegion()) 433 buildStmts(*I->getNodeAs<Region>()); 434 else 435 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr); 436 } 437 438 void ScopBuilder::buildAccessFunctions(BasicBlock &BB, 439 Region *NonAffineSubRegion, 440 bool IsExitBlock) { 441 // We do not build access functions for error blocks, as they may contain 442 // instructions we can not model. 443 if (isErrorBlock(BB, scop->getRegion(), LI, DT) && !IsExitBlock) 444 return; 445 446 Loop *L = LI.getLoopFor(&BB); 447 448 for (Instruction &Inst : BB) { 449 PHINode *PHI = dyn_cast<PHINode>(&Inst); 450 if (PHI) 451 buildPHIAccesses(PHI, NonAffineSubRegion, IsExitBlock); 452 453 // For the exit block we stop modeling after the last PHI node. 454 if (!PHI && IsExitBlock) 455 break; 456 457 if (auto MemInst = MemAccInst::dyn_cast(Inst)) 458 buildMemoryAccess(MemInst, L); 459 460 if (isIgnoredIntrinsic(&Inst)) 461 continue; 462 463 // PHI nodes have already been modeled above and TerminatorInsts that are 464 // not part of a non-affine subregion are fully modeled and regenerated 465 // from the polyhedral domains. Hence, they do not need to be modeled as 466 // explicit data dependences. 467 if (!PHI && (!isa<TerminatorInst>(&Inst) || NonAffineSubRegion)) 468 buildScalarDependences(&Inst); 469 470 if (!IsExitBlock) 471 buildEscapingDependences(&Inst); 472 } 473 } 474 475 MemoryAccess *ScopBuilder::addMemoryAccess( 476 BasicBlock *BB, Instruction *Inst, MemoryAccess::AccessType AccType, 477 Value *BaseAddress, Type *ElementType, bool Affine, Value *AccessValue, 478 ArrayRef<const SCEV *> Subscripts, ArrayRef<const SCEV *> Sizes, 479 ScopArrayInfo::MemoryKind Kind) { 480 ScopStmt *Stmt = scop->getStmtFor(BB); 481 482 // Do not create a memory access for anything not in the SCoP. It would be 483 // ignored anyway. 484 if (!Stmt) 485 return nullptr; 486 487 Value *BaseAddr = BaseAddress; 488 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, ""); 489 490 bool isKnownMustAccess = false; 491 492 // Accesses in single-basic block statements are always excuted. 493 if (Stmt->isBlockStmt()) 494 isKnownMustAccess = true; 495 496 if (Stmt->isRegionStmt()) { 497 // Accesses that dominate the exit block of a non-affine region are always 498 // executed. In non-affine regions there may exist MK_Values that do not 499 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs 500 // only if there is at most one PHI_WRITE in the non-affine region. 501 if (DT.dominates(BB, Stmt->getRegion()->getExit())) 502 isKnownMustAccess = true; 503 } 504 505 // Non-affine PHI writes do not "happen" at a particular instruction, but 506 // after exiting the statement. Therefore they are guaranteed execute and 507 // overwrite the old value. 508 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI) 509 isKnownMustAccess = true; 510 511 if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE) 512 AccType = MemoryAccess::MAY_WRITE; 513 514 auto *Access = 515 new MemoryAccess(Stmt, Inst, AccType, BaseAddress, ElementType, Affine, 516 Subscripts, Sizes, AccessValue, Kind, BaseName); 517 518 scop->addAccessFunction(Access); 519 Stmt->addAccess(Access); 520 return Access; 521 } 522 523 void ScopBuilder::addArrayAccess( 524 MemAccInst MemAccInst, MemoryAccess::AccessType AccType, Value *BaseAddress, 525 Type *ElementType, bool IsAffine, ArrayRef<const SCEV *> Subscripts, 526 ArrayRef<const SCEV *> Sizes, Value *AccessValue) { 527 ArrayBasePointers.insert(BaseAddress); 528 addMemoryAccess(MemAccInst->getParent(), MemAccInst, AccType, BaseAddress, 529 ElementType, IsAffine, AccessValue, Subscripts, Sizes, 530 ScopArrayInfo::MK_Array); 531 } 532 533 void ScopBuilder::ensureValueWrite(Instruction *Inst) { 534 ScopStmt *Stmt = scop->getStmtFor(Inst); 535 536 // Inst not defined within this SCoP. 537 if (!Stmt) 538 return; 539 540 // Do not process further if the instruction is already written. 541 if (Stmt->lookupValueWriteOf(Inst)) 542 return; 543 544 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::MUST_WRITE, Inst, 545 Inst->getType(), true, Inst, ArrayRef<const SCEV *>(), 546 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value); 547 } 548 549 void ScopBuilder::ensureValueRead(Value *V, BasicBlock *UserBB) { 550 551 // There cannot be an "access" for literal constants. BasicBlock references 552 // (jump destinations) also never change. 553 if ((isa<Constant>(V) && !isa<GlobalVariable>(V)) || isa<BasicBlock>(V)) 554 return; 555 556 // If the instruction can be synthesized and the user is in the region we do 557 // not need to add a value dependences. 558 auto *Scope = LI.getLoopFor(UserBB); 559 if (canSynthesize(V, *scop, &LI, &SE, Scope)) 560 return; 561 562 // Do not build scalar dependences for required invariant loads as we will 563 // hoist them later on anyway or drop the SCoP if we cannot. 564 auto &ScopRIL = scop->getRequiredInvariantLoads(); 565 if (ScopRIL.count(dyn_cast<LoadInst>(V))) 566 return; 567 568 // Determine the ScopStmt containing the value's definition and use. There is 569 // no defining ScopStmt if the value is a function argument, a global value, 570 // or defined outside the SCoP. 571 Instruction *ValueInst = dyn_cast<Instruction>(V); 572 ScopStmt *ValueStmt = ValueInst ? scop->getStmtFor(ValueInst) : nullptr; 573 574 ScopStmt *UserStmt = scop->getStmtFor(UserBB); 575 576 // We do not model uses outside the scop. 577 if (!UserStmt) 578 return; 579 580 // Add MemoryAccess for invariant values only if requested. 581 if (!ModelReadOnlyScalars && !ValueStmt) 582 return; 583 584 // Ignore use-def chains within the same ScopStmt. 585 if (ValueStmt == UserStmt) 586 return; 587 588 // Do not create another MemoryAccess for reloading the value if one already 589 // exists. 590 if (UserStmt->lookupValueReadOf(V)) 591 return; 592 593 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, V, V->getType(), true, V, 594 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(), 595 ScopArrayInfo::MK_Value); 596 if (ValueInst) 597 ensureValueWrite(ValueInst); 598 } 599 600 void ScopBuilder::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock, 601 Value *IncomingValue, bool IsExitBlock) { 602 // As the incoming block might turn out to be an error statement ensure we 603 // will create an exit PHI SAI object. It is needed during code generation 604 // and would be created later anyway. 605 if (IsExitBlock) 606 scop->getOrCreateScopArrayInfo(PHI, PHI->getType(), {}, 607 ScopArrayInfo::MK_ExitPHI); 608 609 ScopStmt *IncomingStmt = scop->getStmtFor(IncomingBlock); 610 if (!IncomingStmt) 611 return; 612 613 // Take care for the incoming value being available in the incoming block. 614 // This must be done before the check for multiple PHI writes because multiple 615 // exiting edges from subregion each can be the effective written value of the 616 // subregion. As such, all of them must be made available in the subregion 617 // statement. 618 ensureValueRead(IncomingValue, IncomingBlock); 619 620 // Do not add more than one MemoryAccess per PHINode and ScopStmt. 621 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) { 622 assert(Acc->getAccessInstruction() == PHI); 623 Acc->addIncoming(IncomingBlock, IncomingValue); 624 return; 625 } 626 627 MemoryAccess *Acc = addMemoryAccess( 628 IncomingStmt->getEntryBlock(), PHI, MemoryAccess::MUST_WRITE, PHI, 629 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(), 630 ArrayRef<const SCEV *>(), 631 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI); 632 assert(Acc); 633 Acc->addIncoming(IncomingBlock, IncomingValue); 634 } 635 636 void ScopBuilder::addPHIReadAccess(PHINode *PHI) { 637 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 638 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(), 639 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_PHI); 640 } 641 642 void ScopBuilder::buildScop(Region &R, AssumptionCache &AC) { 643 scop.reset(new Scop(R, SE, LI, *SD.getDetectionContext(&R))); 644 645 buildStmts(R); 646 buildAccessFunctions(R); 647 648 // In case the region does not have an exiting block we will later (during 649 // code generation) split the exit block. This will move potential PHI nodes 650 // from the current exit block into the new region exiting block. Hence, PHI 651 // nodes that are at this point not part of the region will be. 652 // To handle these PHI nodes later we will now model their operands as scalar 653 // accesses. Note that we do not model anything in the exit block if we have 654 // an exiting block in the region, as there will not be any splitting later. 655 if (!scop->hasSingleExitEdge()) 656 buildAccessFunctions(*R.getExit(), nullptr, 657 /* IsExitBlock */ true); 658 659 // Create memory accesses for global reads since all arrays are now known. 660 auto *AF = SE.getConstant(IntegerType::getInt64Ty(SE.getContext()), 0); 661 for (auto *GlobalRead : GlobalReads) 662 for (auto *BP : ArrayBasePointers) 663 addArrayAccess(MemAccInst(GlobalRead), MemoryAccess::READ, BP, 664 BP->getType(), false, {AF}, {nullptr}, GlobalRead); 665 666 scop->init(AA, AC, DT, LI); 667 } 668 669 ScopBuilder::ScopBuilder(Region *R, AssumptionCache &AC, AliasAnalysis &AA, 670 const DataLayout &DL, DominatorTree &DT, LoopInfo &LI, 671 ScopDetection &SD, ScalarEvolution &SE) 672 : AA(AA), DL(DL), DT(DT), LI(LI), SD(SD), SE(SE) { 673 674 Function *F = R->getEntry()->getParent(); 675 676 DebugLoc Beg, End; 677 getDebugLocations(getBBPairForRegion(R), Beg, End); 678 std::string Msg = "SCoP begins here."; 679 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg); 680 681 buildScop(*R, AC); 682 683 DEBUG(scop->print(dbgs())); 684 685 if (!scop->hasFeasibleRuntimeContext()) { 686 Msg = "SCoP ends here but was dismissed."; 687 scop.reset(); 688 } else { 689 Msg = "SCoP ends here."; 690 ++ScopFound; 691 if (scop->getMaxLoopDepth() > 0) 692 ++RichScopFound; 693 } 694 695 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg); 696 } 697