1 //===- CodeExtractor.cpp - Pull code region into a new function -----------===// 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 // This file implements the interface to tear out a code region, such as an 10 // individual loop or a parallel section, into a new function, replacing it with 11 // a call to the new function. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Utils/CodeExtractor.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/Optional.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/Analysis/AssumptionCache.h" 24 #include "llvm/Analysis/BlockFrequencyInfo.h" 25 #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 26 #include "llvm/Analysis/BranchProbabilityInfo.h" 27 #include "llvm/Analysis/LoopInfo.h" 28 #include "llvm/IR/Argument.h" 29 #include "llvm/IR/Attributes.h" 30 #include "llvm/IR/BasicBlock.h" 31 #include "llvm/IR/CFG.h" 32 #include "llvm/IR/Constant.h" 33 #include "llvm/IR/Constants.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/DerivedTypes.h" 36 #include "llvm/IR/Dominators.h" 37 #include "llvm/IR/Function.h" 38 #include "llvm/IR/GlobalValue.h" 39 #include "llvm/IR/InstrTypes.h" 40 #include "llvm/IR/Instruction.h" 41 #include "llvm/IR/Instructions.h" 42 #include "llvm/IR/IntrinsicInst.h" 43 #include "llvm/IR/Intrinsics.h" 44 #include "llvm/IR/LLVMContext.h" 45 #include "llvm/IR/MDBuilder.h" 46 #include "llvm/IR/Module.h" 47 #include "llvm/IR/PatternMatch.h" 48 #include "llvm/IR/Type.h" 49 #include "llvm/IR/User.h" 50 #include "llvm/IR/Value.h" 51 #include "llvm/IR/Verifier.h" 52 #include "llvm/Pass.h" 53 #include "llvm/Support/BlockFrequency.h" 54 #include "llvm/Support/BranchProbability.h" 55 #include "llvm/Support/Casting.h" 56 #include "llvm/Support/CommandLine.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/ErrorHandling.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 61 #include "llvm/Transforms/Utils/Local.h" 62 #include <cassert> 63 #include <cstdint> 64 #include <iterator> 65 #include <map> 66 #include <set> 67 #include <utility> 68 #include <vector> 69 70 using namespace llvm; 71 using namespace llvm::PatternMatch; 72 using ProfileCount = Function::ProfileCount; 73 74 #define DEBUG_TYPE "code-extractor" 75 76 // Provide a command-line option to aggregate function arguments into a struct 77 // for functions produced by the code extractor. This is useful when converting 78 // extracted functions to pthread-based code, as only one argument (void*) can 79 // be passed in to pthread_create(). 80 static cl::opt<bool> 81 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden, 82 cl::desc("Aggregate arguments to code-extracted functions")); 83 84 /// Test whether a block is valid for extraction. 85 static bool isBlockValidForExtraction(const BasicBlock &BB, 86 const SetVector<BasicBlock *> &Result, 87 bool AllowVarArgs, bool AllowAlloca) { 88 // taking the address of a basic block moved to another function is illegal 89 if (BB.hasAddressTaken()) 90 return false; 91 92 // don't hoist code that uses another basicblock address, as it's likely to 93 // lead to unexpected behavior, like cross-function jumps 94 SmallPtrSet<User const *, 16> Visited; 95 SmallVector<User const *, 16> ToVisit; 96 97 for (Instruction const &Inst : BB) 98 ToVisit.push_back(&Inst); 99 100 while (!ToVisit.empty()) { 101 User const *Curr = ToVisit.pop_back_val(); 102 if (!Visited.insert(Curr).second) 103 continue; 104 if (isa<BlockAddress const>(Curr)) 105 return false; // even a reference to self is likely to be not compatible 106 107 if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB) 108 continue; 109 110 for (auto const &U : Curr->operands()) { 111 if (auto *UU = dyn_cast<User>(U)) 112 ToVisit.push_back(UU); 113 } 114 } 115 116 // If explicitly requested, allow vastart and alloca. For invoke instructions 117 // verify that extraction is valid. 118 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) { 119 if (isa<AllocaInst>(I)) { 120 if (!AllowAlloca) 121 return false; 122 continue; 123 } 124 125 if (const auto *II = dyn_cast<InvokeInst>(I)) { 126 // Unwind destination (either a landingpad, catchswitch, or cleanuppad) 127 // must be a part of the subgraph which is being extracted. 128 if (auto *UBB = II->getUnwindDest()) 129 if (!Result.count(UBB)) 130 return false; 131 continue; 132 } 133 134 // All catch handlers of a catchswitch instruction as well as the unwind 135 // destination must be in the subgraph. 136 if (const auto *CSI = dyn_cast<CatchSwitchInst>(I)) { 137 if (auto *UBB = CSI->getUnwindDest()) 138 if (!Result.count(UBB)) 139 return false; 140 for (auto *HBB : CSI->handlers()) 141 if (!Result.count(const_cast<BasicBlock*>(HBB))) 142 return false; 143 continue; 144 } 145 146 // Make sure that entire catch handler is within subgraph. It is sufficient 147 // to check that catch return's block is in the list. 148 if (const auto *CPI = dyn_cast<CatchPadInst>(I)) { 149 for (const auto *U : CPI->users()) 150 if (const auto *CRI = dyn_cast<CatchReturnInst>(U)) 151 if (!Result.count(const_cast<BasicBlock*>(CRI->getParent()))) 152 return false; 153 continue; 154 } 155 156 // And do similar checks for cleanup handler - the entire handler must be 157 // in subgraph which is going to be extracted. For cleanup return should 158 // additionally check that the unwind destination is also in the subgraph. 159 if (const auto *CPI = dyn_cast<CleanupPadInst>(I)) { 160 for (const auto *U : CPI->users()) 161 if (const auto *CRI = dyn_cast<CleanupReturnInst>(U)) 162 if (!Result.count(const_cast<BasicBlock*>(CRI->getParent()))) 163 return false; 164 continue; 165 } 166 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I)) { 167 if (auto *UBB = CRI->getUnwindDest()) 168 if (!Result.count(UBB)) 169 return false; 170 continue; 171 } 172 173 if (const CallInst *CI = dyn_cast<CallInst>(I)) { 174 if (const Function *F = CI->getCalledFunction()) { 175 auto IID = F->getIntrinsicID(); 176 if (IID == Intrinsic::vastart) { 177 if (AllowVarArgs) 178 continue; 179 else 180 return false; 181 } 182 183 // Currently, we miscompile outlined copies of eh_typid_for. There are 184 // proposals for fixing this in llvm.org/PR39545. 185 if (IID == Intrinsic::eh_typeid_for) 186 return false; 187 } 188 } 189 } 190 191 return true; 192 } 193 194 /// Build a set of blocks to extract if the input blocks are viable. 195 static SetVector<BasicBlock *> 196 buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, 197 bool AllowVarArgs, bool AllowAlloca) { 198 assert(!BBs.empty() && "The set of blocks to extract must be non-empty"); 199 SetVector<BasicBlock *> Result; 200 201 // Loop over the blocks, adding them to our set-vector, and aborting with an 202 // empty set if we encounter invalid blocks. 203 for (BasicBlock *BB : BBs) { 204 // If this block is dead, don't process it. 205 if (DT && !DT->isReachableFromEntry(BB)) 206 continue; 207 208 if (!Result.insert(BB)) 209 llvm_unreachable("Repeated basic blocks in extraction input"); 210 } 211 212 LLVM_DEBUG(dbgs() << "Region front block: " << Result.front()->getName() 213 << '\n'); 214 215 for (auto *BB : Result) { 216 if (!isBlockValidForExtraction(*BB, Result, AllowVarArgs, AllowAlloca)) 217 return {}; 218 219 // Make sure that the first block is not a landing pad. 220 if (BB == Result.front()) { 221 if (BB->isEHPad()) { 222 LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n"); 223 return {}; 224 } 225 continue; 226 } 227 228 // All blocks other than the first must not have predecessors outside of 229 // the subgraph which is being extracted. 230 for (auto *PBB : predecessors(BB)) 231 if (!Result.count(PBB)) { 232 LLVM_DEBUG(dbgs() << "No blocks in this region may have entries from " 233 "outside the region except for the first block!\n" 234 << "Problematic source BB: " << BB->getName() << "\n" 235 << "Problematic destination BB: " << PBB->getName() 236 << "\n"); 237 return {}; 238 } 239 } 240 241 return Result; 242 } 243 244 CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, 245 bool AggregateArgs, BlockFrequencyInfo *BFI, 246 BranchProbabilityInfo *BPI, AssumptionCache *AC, 247 bool AllowVarArgs, bool AllowAlloca, 248 std::string Suffix) 249 : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), 250 BPI(BPI), AC(AC), AllowVarArgs(AllowVarArgs), 251 Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)), 252 Suffix(Suffix) {} 253 254 CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs, 255 BlockFrequencyInfo *BFI, 256 BranchProbabilityInfo *BPI, AssumptionCache *AC, 257 std::string Suffix) 258 : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), 259 BPI(BPI), AC(AC), AllowVarArgs(false), 260 Blocks(buildExtractionBlockSet(L.getBlocks(), &DT, 261 /* AllowVarArgs */ false, 262 /* AllowAlloca */ false)), 263 Suffix(Suffix) {} 264 265 /// definedInRegion - Return true if the specified value is defined in the 266 /// extracted region. 267 static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) { 268 if (Instruction *I = dyn_cast<Instruction>(V)) 269 if (Blocks.count(I->getParent())) 270 return true; 271 return false; 272 } 273 274 /// definedInCaller - Return true if the specified value is defined in the 275 /// function being code extracted, but not in the region being extracted. 276 /// These values must be passed in as live-ins to the function. 277 static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) { 278 if (isa<Argument>(V)) return true; 279 if (Instruction *I = dyn_cast<Instruction>(V)) 280 if (!Blocks.count(I->getParent())) 281 return true; 282 return false; 283 } 284 285 static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) { 286 BasicBlock *CommonExitBlock = nullptr; 287 auto hasNonCommonExitSucc = [&](BasicBlock *Block) { 288 for (auto *Succ : successors(Block)) { 289 // Internal edges, ok. 290 if (Blocks.count(Succ)) 291 continue; 292 if (!CommonExitBlock) { 293 CommonExitBlock = Succ; 294 continue; 295 } 296 if (CommonExitBlock != Succ) 297 return true; 298 } 299 return false; 300 }; 301 302 if (any_of(Blocks, hasNonCommonExitSucc)) 303 return nullptr; 304 305 return CommonExitBlock; 306 } 307 308 bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers( 309 Instruction *Addr) const { 310 AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets()); 311 Function *Func = (*Blocks.begin())->getParent(); 312 for (BasicBlock &BB : *Func) { 313 if (Blocks.count(&BB)) 314 continue; 315 for (Instruction &II : BB) { 316 if (isa<DbgInfoIntrinsic>(II)) 317 continue; 318 319 unsigned Opcode = II.getOpcode(); 320 Value *MemAddr = nullptr; 321 switch (Opcode) { 322 case Instruction::Store: 323 case Instruction::Load: { 324 if (Opcode == Instruction::Store) { 325 StoreInst *SI = cast<StoreInst>(&II); 326 MemAddr = SI->getPointerOperand(); 327 } else { 328 LoadInst *LI = cast<LoadInst>(&II); 329 MemAddr = LI->getPointerOperand(); 330 } 331 // Global variable can not be aliased with locals. 332 if (dyn_cast<Constant>(MemAddr)) 333 break; 334 Value *Base = MemAddr->stripInBoundsConstantOffsets(); 335 if (!isa<AllocaInst>(Base) || Base == AI) 336 return false; 337 break; 338 } 339 default: { 340 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II); 341 if (IntrInst) { 342 if (IntrInst->isLifetimeStartOrEnd()) 343 break; 344 return false; 345 } 346 // Treat all the other cases conservatively if it has side effects. 347 if (II.mayHaveSideEffects()) 348 return false; 349 } 350 } 351 } 352 } 353 354 return true; 355 } 356 357 BasicBlock * 358 CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) { 359 BasicBlock *SinglePredFromOutlineRegion = nullptr; 360 assert(!Blocks.count(CommonExitBlock) && 361 "Expect a block outside the region!"); 362 for (auto *Pred : predecessors(CommonExitBlock)) { 363 if (!Blocks.count(Pred)) 364 continue; 365 if (!SinglePredFromOutlineRegion) { 366 SinglePredFromOutlineRegion = Pred; 367 } else if (SinglePredFromOutlineRegion != Pred) { 368 SinglePredFromOutlineRegion = nullptr; 369 break; 370 } 371 } 372 373 if (SinglePredFromOutlineRegion) 374 return SinglePredFromOutlineRegion; 375 376 #ifndef NDEBUG 377 auto getFirstPHI = [](BasicBlock *BB) { 378 BasicBlock::iterator I = BB->begin(); 379 PHINode *FirstPhi = nullptr; 380 while (I != BB->end()) { 381 PHINode *Phi = dyn_cast<PHINode>(I); 382 if (!Phi) 383 break; 384 if (!FirstPhi) { 385 FirstPhi = Phi; 386 break; 387 } 388 } 389 return FirstPhi; 390 }; 391 // If there are any phi nodes, the single pred either exists or has already 392 // be created before code extraction. 393 assert(!getFirstPHI(CommonExitBlock) && "Phi not expected"); 394 #endif 395 396 BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock( 397 CommonExitBlock->getFirstNonPHI()->getIterator()); 398 399 for (auto PI = pred_begin(CommonExitBlock), PE = pred_end(CommonExitBlock); 400 PI != PE;) { 401 BasicBlock *Pred = *PI++; 402 if (Blocks.count(Pred)) 403 continue; 404 Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock); 405 } 406 // Now add the old exit block to the outline region. 407 Blocks.insert(CommonExitBlock); 408 return CommonExitBlock; 409 } 410 411 // Find the pair of life time markers for address 'Addr' that are either 412 // defined inside the outline region or can legally be shrinkwrapped into the 413 // outline region. If there are not other untracked uses of the address, return 414 // the pair of markers if found; otherwise return a pair of nullptr. 415 CodeExtractor::LifetimeMarkerInfo 416 CodeExtractor::getLifetimeMarkers(Instruction *Addr, 417 BasicBlock *ExitBlock) const { 418 LifetimeMarkerInfo Info; 419 420 for (User *U : Addr->users()) { 421 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U); 422 if (IntrInst) { 423 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) { 424 // Do not handle the case where Addr has multiple start markers. 425 if (Info.LifeStart) 426 return {}; 427 Info.LifeStart = IntrInst; 428 } 429 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) { 430 if (Info.LifeEnd) 431 return {}; 432 Info.LifeEnd = IntrInst; 433 } 434 continue; 435 } 436 // Find untracked uses of the address, bail. 437 if (!definedInRegion(Blocks, U)) 438 return {}; 439 } 440 441 if (!Info.LifeStart || !Info.LifeEnd) 442 return {}; 443 444 Info.SinkLifeStart = !definedInRegion(Blocks, Info.LifeStart); 445 Info.HoistLifeEnd = !definedInRegion(Blocks, Info.LifeEnd); 446 // Do legality check. 447 if ((Info.SinkLifeStart || Info.HoistLifeEnd) && 448 !isLegalToShrinkwrapLifetimeMarkers(Addr)) 449 return {}; 450 451 // Check to see if we have a place to do hoisting, if not, bail. 452 if (Info.HoistLifeEnd && !ExitBlock) 453 return {}; 454 455 return Info; 456 } 457 458 void CodeExtractor::findAllocas(ValueSet &SinkCands, ValueSet &HoistCands, 459 BasicBlock *&ExitBlock) const { 460 Function *Func = (*Blocks.begin())->getParent(); 461 ExitBlock = getCommonExitBlock(Blocks); 462 463 auto moveOrIgnoreLifetimeMarkers = 464 [&](const LifetimeMarkerInfo &LMI) -> bool { 465 if (!LMI.LifeStart) 466 return false; 467 if (LMI.SinkLifeStart) { 468 LLVM_DEBUG(dbgs() << "Sinking lifetime.start: " << *LMI.LifeStart 469 << "\n"); 470 SinkCands.insert(LMI.LifeStart); 471 } 472 if (LMI.HoistLifeEnd) { 473 LLVM_DEBUG(dbgs() << "Hoisting lifetime.end: " << *LMI.LifeEnd << "\n"); 474 HoistCands.insert(LMI.LifeEnd); 475 } 476 return true; 477 }; 478 479 for (BasicBlock &BB : *Func) { 480 if (Blocks.count(&BB)) 481 continue; 482 for (Instruction &II : BB) { 483 auto *AI = dyn_cast<AllocaInst>(&II); 484 if (!AI) 485 continue; 486 487 LifetimeMarkerInfo MarkerInfo = getLifetimeMarkers(AI, ExitBlock); 488 bool Moved = moveOrIgnoreLifetimeMarkers(MarkerInfo); 489 if (Moved) { 490 LLVM_DEBUG(dbgs() << "Sinking alloca: " << *AI << "\n"); 491 SinkCands.insert(AI); 492 continue; 493 } 494 495 // Follow any bitcasts. 496 SmallVector<Instruction *, 2> Bitcasts; 497 SmallVector<LifetimeMarkerInfo, 2> BitcastLifetimeInfo; 498 for (User *U : AI->users()) { 499 if (U->stripInBoundsConstantOffsets() == AI) { 500 Instruction *Bitcast = cast<Instruction>(U); 501 LifetimeMarkerInfo LMI = getLifetimeMarkers(Bitcast, ExitBlock); 502 if (LMI.LifeStart) { 503 Bitcasts.push_back(Bitcast); 504 BitcastLifetimeInfo.push_back(LMI); 505 continue; 506 } 507 } 508 509 // Found unknown use of AI. 510 if (!definedInRegion(Blocks, U)) { 511 Bitcasts.clear(); 512 break; 513 } 514 } 515 516 // Either no bitcasts reference the alloca or there are unknown uses. 517 if (Bitcasts.empty()) 518 continue; 519 520 LLVM_DEBUG(dbgs() << "Sinking alloca (via bitcast): " << *AI << "\n"); 521 SinkCands.insert(AI); 522 for (unsigned I = 0, E = Bitcasts.size(); I != E; ++I) { 523 Instruction *BitcastAddr = Bitcasts[I]; 524 const LifetimeMarkerInfo &LMI = BitcastLifetimeInfo[I]; 525 assert(LMI.LifeStart && 526 "Unsafe to sink bitcast without lifetime markers"); 527 moveOrIgnoreLifetimeMarkers(LMI); 528 if (!definedInRegion(Blocks, BitcastAddr)) { 529 LLVM_DEBUG(dbgs() << "Sinking bitcast-of-alloca: " << *BitcastAddr 530 << "\n"); 531 SinkCands.insert(BitcastAddr); 532 } 533 } 534 } 535 } 536 } 537 538 void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs, 539 const ValueSet &SinkCands) const { 540 for (BasicBlock *BB : Blocks) { 541 // If a used value is defined outside the region, it's an input. If an 542 // instruction is used outside the region, it's an output. 543 for (Instruction &II : *BB) { 544 for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE; 545 ++OI) { 546 Value *V = *OI; 547 if (!SinkCands.count(V) && definedInCaller(Blocks, V)) 548 Inputs.insert(V); 549 } 550 551 for (User *U : II.users()) 552 if (!definedInRegion(Blocks, U)) { 553 Outputs.insert(&II); 554 break; 555 } 556 } 557 } 558 } 559 560 /// severSplitPHINodesOfEntry - If a PHI node has multiple inputs from outside 561 /// of the region, we need to split the entry block of the region so that the 562 /// PHI node is easier to deal with. 563 void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) { 564 unsigned NumPredsFromRegion = 0; 565 unsigned NumPredsOutsideRegion = 0; 566 567 if (Header != &Header->getParent()->getEntryBlock()) { 568 PHINode *PN = dyn_cast<PHINode>(Header->begin()); 569 if (!PN) return; // No PHI nodes. 570 571 // If the header node contains any PHI nodes, check to see if there is more 572 // than one entry from outside the region. If so, we need to sever the 573 // header block into two. 574 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 575 if (Blocks.count(PN->getIncomingBlock(i))) 576 ++NumPredsFromRegion; 577 else 578 ++NumPredsOutsideRegion; 579 580 // If there is one (or fewer) predecessor from outside the region, we don't 581 // need to do anything special. 582 if (NumPredsOutsideRegion <= 1) return; 583 } 584 585 // Otherwise, we need to split the header block into two pieces: one 586 // containing PHI nodes merging values from outside of the region, and a 587 // second that contains all of the code for the block and merges back any 588 // incoming values from inside of the region. 589 BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT); 590 591 // We only want to code extract the second block now, and it becomes the new 592 // header of the region. 593 BasicBlock *OldPred = Header; 594 Blocks.remove(OldPred); 595 Blocks.insert(NewBB); 596 Header = NewBB; 597 598 // Okay, now we need to adjust the PHI nodes and any branches from within the 599 // region to go to the new header block instead of the old header block. 600 if (NumPredsFromRegion) { 601 PHINode *PN = cast<PHINode>(OldPred->begin()); 602 // Loop over all of the predecessors of OldPred that are in the region, 603 // changing them to branch to NewBB instead. 604 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 605 if (Blocks.count(PN->getIncomingBlock(i))) { 606 Instruction *TI = PN->getIncomingBlock(i)->getTerminator(); 607 TI->replaceUsesOfWith(OldPred, NewBB); 608 } 609 610 // Okay, everything within the region is now branching to the right block, we 611 // just have to update the PHI nodes now, inserting PHI nodes into NewBB. 612 BasicBlock::iterator AfterPHIs; 613 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) { 614 PHINode *PN = cast<PHINode>(AfterPHIs); 615 // Create a new PHI node in the new region, which has an incoming value 616 // from OldPred of PN. 617 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion, 618 PN->getName() + ".ce", &NewBB->front()); 619 PN->replaceAllUsesWith(NewPN); 620 NewPN->addIncoming(PN, OldPred); 621 622 // Loop over all of the incoming value in PN, moving them to NewPN if they 623 // are from the extracted region. 624 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) { 625 if (Blocks.count(PN->getIncomingBlock(i))) { 626 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i)); 627 PN->removeIncomingValue(i); 628 --i; 629 } 630 } 631 } 632 } 633 } 634 635 /// severSplitPHINodesOfExits - if PHI nodes in exit blocks have inputs from 636 /// outlined region, we split these PHIs on two: one with inputs from region 637 /// and other with remaining incoming blocks; then first PHIs are placed in 638 /// outlined region. 639 void CodeExtractor::severSplitPHINodesOfExits( 640 const SmallPtrSetImpl<BasicBlock *> &Exits) { 641 for (BasicBlock *ExitBB : Exits) { 642 BasicBlock *NewBB = nullptr; 643 644 for (PHINode &PN : ExitBB->phis()) { 645 // Find all incoming values from the outlining region. 646 SmallVector<unsigned, 2> IncomingVals; 647 for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i) 648 if (Blocks.count(PN.getIncomingBlock(i))) 649 IncomingVals.push_back(i); 650 651 // Do not process PHI if there is one (or fewer) predecessor from region. 652 // If PHI has exactly one predecessor from region, only this one incoming 653 // will be replaced on codeRepl block, so it should be safe to skip PHI. 654 if (IncomingVals.size() <= 1) 655 continue; 656 657 // Create block for new PHIs and add it to the list of outlined if it 658 // wasn't done before. 659 if (!NewBB) { 660 NewBB = BasicBlock::Create(ExitBB->getContext(), 661 ExitBB->getName() + ".split", 662 ExitBB->getParent(), ExitBB); 663 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBB), 664 pred_end(ExitBB)); 665 for (BasicBlock *PredBB : Preds) 666 if (Blocks.count(PredBB)) 667 PredBB->getTerminator()->replaceUsesOfWith(ExitBB, NewBB); 668 BranchInst::Create(ExitBB, NewBB); 669 Blocks.insert(NewBB); 670 } 671 672 // Split this PHI. 673 PHINode *NewPN = 674 PHINode::Create(PN.getType(), IncomingVals.size(), 675 PN.getName() + ".ce", NewBB->getFirstNonPHI()); 676 for (unsigned i : IncomingVals) 677 NewPN->addIncoming(PN.getIncomingValue(i), PN.getIncomingBlock(i)); 678 for (unsigned i : reverse(IncomingVals)) 679 PN.removeIncomingValue(i, false); 680 PN.addIncoming(NewPN, NewBB); 681 } 682 } 683 } 684 685 void CodeExtractor::splitReturnBlocks() { 686 for (BasicBlock *Block : Blocks) 687 if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) { 688 BasicBlock *New = 689 Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret"); 690 if (DT) { 691 // Old dominates New. New node dominates all other nodes dominated 692 // by Old. 693 DomTreeNode *OldNode = DT->getNode(Block); 694 SmallVector<DomTreeNode *, 8> Children(OldNode->begin(), 695 OldNode->end()); 696 697 DomTreeNode *NewNode = DT->addNewBlock(New, Block); 698 699 for (DomTreeNode *I : Children) 700 DT->changeImmediateDominator(I, NewNode); 701 } 702 } 703 } 704 705 /// constructFunction - make a function based on inputs and outputs, as follows: 706 /// f(in0, ..., inN, out0, ..., outN) 707 Function *CodeExtractor::constructFunction(const ValueSet &inputs, 708 const ValueSet &outputs, 709 BasicBlock *header, 710 BasicBlock *newRootNode, 711 BasicBlock *newHeader, 712 Function *oldFunction, 713 Module *M) { 714 LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n"); 715 LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n"); 716 717 // This function returns unsigned, outputs will go back by reference. 718 switch (NumExitBlocks) { 719 case 0: 720 case 1: RetTy = Type::getVoidTy(header->getContext()); break; 721 case 2: RetTy = Type::getInt1Ty(header->getContext()); break; 722 default: RetTy = Type::getInt16Ty(header->getContext()); break; 723 } 724 725 std::vector<Type *> paramTy; 726 727 // Add the types of the input values to the function's argument list 728 for (Value *value : inputs) { 729 LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n"); 730 paramTy.push_back(value->getType()); 731 } 732 733 // Add the types of the output values to the function's argument list. 734 for (Value *output : outputs) { 735 LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n"); 736 if (AggregateArgs) 737 paramTy.push_back(output->getType()); 738 else 739 paramTy.push_back(PointerType::getUnqual(output->getType())); 740 } 741 742 LLVM_DEBUG({ 743 dbgs() << "Function type: " << *RetTy << " f("; 744 for (Type *i : paramTy) 745 dbgs() << *i << ", "; 746 dbgs() << ")\n"; 747 }); 748 749 StructType *StructTy; 750 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { 751 StructTy = StructType::get(M->getContext(), paramTy); 752 paramTy.clear(); 753 paramTy.push_back(PointerType::getUnqual(StructTy)); 754 } 755 FunctionType *funcType = 756 FunctionType::get(RetTy, paramTy, 757 AllowVarArgs && oldFunction->isVarArg()); 758 759 std::string SuffixToUse = 760 Suffix.empty() 761 ? (header->getName().empty() ? "extracted" : header->getName().str()) 762 : Suffix; 763 // Create the new function 764 Function *newFunction = Function::Create( 765 funcType, GlobalValue::InternalLinkage, oldFunction->getAddressSpace(), 766 oldFunction->getName() + "." + SuffixToUse, M); 767 // If the old function is no-throw, so is the new one. 768 if (oldFunction->doesNotThrow()) 769 newFunction->setDoesNotThrow(); 770 771 // Inherit the uwtable attribute if we need to. 772 if (oldFunction->hasUWTable()) 773 newFunction->setHasUWTable(); 774 775 // Inherit all of the target dependent attributes and white-listed 776 // target independent attributes. 777 // (e.g. If the extracted region contains a call to an x86.sse 778 // instruction we need to make sure that the extracted region has the 779 // "target-features" attribute allowing it to be lowered. 780 // FIXME: This should be changed to check to see if a specific 781 // attribute can not be inherited. 782 for (const auto &Attr : oldFunction->getAttributes().getFnAttributes()) { 783 if (Attr.isStringAttribute()) { 784 if (Attr.getKindAsString() == "thunk") 785 continue; 786 } else 787 switch (Attr.getKindAsEnum()) { 788 // Those attributes cannot be propagated safely. Explicitly list them 789 // here so we get a warning if new attributes are added. This list also 790 // includes non-function attributes. 791 case Attribute::Alignment: 792 case Attribute::AllocSize: 793 case Attribute::ArgMemOnly: 794 case Attribute::Builtin: 795 case Attribute::ByVal: 796 case Attribute::Convergent: 797 case Attribute::Dereferenceable: 798 case Attribute::DereferenceableOrNull: 799 case Attribute::InAlloca: 800 case Attribute::InReg: 801 case Attribute::InaccessibleMemOnly: 802 case Attribute::InaccessibleMemOrArgMemOnly: 803 case Attribute::JumpTable: 804 case Attribute::Naked: 805 case Attribute::Nest: 806 case Attribute::NoAlias: 807 case Attribute::NoBuiltin: 808 case Attribute::NoCapture: 809 case Attribute::NoReturn: 810 case Attribute::NoSync: 811 case Attribute::None: 812 case Attribute::NonNull: 813 case Attribute::ReadNone: 814 case Attribute::ReadOnly: 815 case Attribute::Returned: 816 case Attribute::ReturnsTwice: 817 case Attribute::SExt: 818 case Attribute::Speculatable: 819 case Attribute::StackAlignment: 820 case Attribute::StructRet: 821 case Attribute::SwiftError: 822 case Attribute::SwiftSelf: 823 case Attribute::WillReturn: 824 case Attribute::WriteOnly: 825 case Attribute::ZExt: 826 case Attribute::ImmArg: 827 case Attribute::EndAttrKinds: 828 continue; 829 // Those attributes should be safe to propagate to the extracted function. 830 case Attribute::AlwaysInline: 831 case Attribute::Cold: 832 case Attribute::NoRecurse: 833 case Attribute::InlineHint: 834 case Attribute::MinSize: 835 case Attribute::NoDuplicate: 836 case Attribute::NoFree: 837 case Attribute::NoImplicitFloat: 838 case Attribute::NoInline: 839 case Attribute::NonLazyBind: 840 case Attribute::NoRedZone: 841 case Attribute::NoUnwind: 842 case Attribute::OptForFuzzing: 843 case Attribute::OptimizeNone: 844 case Attribute::OptimizeForSize: 845 case Attribute::SafeStack: 846 case Attribute::ShadowCallStack: 847 case Attribute::SanitizeAddress: 848 case Attribute::SanitizeMemory: 849 case Attribute::SanitizeThread: 850 case Attribute::SanitizeHWAddress: 851 case Attribute::SanitizeMemTag: 852 case Attribute::SpeculativeLoadHardening: 853 case Attribute::StackProtect: 854 case Attribute::StackProtectReq: 855 case Attribute::StackProtectStrong: 856 case Attribute::StrictFP: 857 case Attribute::UWTable: 858 case Attribute::NoCfCheck: 859 break; 860 } 861 862 newFunction->addFnAttr(Attr); 863 } 864 newFunction->getBasicBlockList().push_back(newRootNode); 865 866 // Create an iterator to name all of the arguments we inserted. 867 Function::arg_iterator AI = newFunction->arg_begin(); 868 869 // Rewrite all users of the inputs in the extracted region to use the 870 // arguments (or appropriate addressing into struct) instead. 871 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 872 Value *RewriteVal; 873 if (AggregateArgs) { 874 Value *Idx[2]; 875 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext())); 876 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i); 877 Instruction *TI = newFunction->begin()->getTerminator(); 878 GetElementPtrInst *GEP = GetElementPtrInst::Create( 879 StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI); 880 RewriteVal = new LoadInst(StructTy->getElementType(i), GEP, 881 "loadgep_" + inputs[i]->getName(), TI); 882 } else 883 RewriteVal = &*AI++; 884 885 std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end()); 886 for (User *use : Users) 887 if (Instruction *inst = dyn_cast<Instruction>(use)) 888 if (Blocks.count(inst->getParent())) 889 inst->replaceUsesOfWith(inputs[i], RewriteVal); 890 } 891 892 // Set names for input and output arguments. 893 if (!AggregateArgs) { 894 AI = newFunction->arg_begin(); 895 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI) 896 AI->setName(inputs[i]->getName()); 897 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI) 898 AI->setName(outputs[i]->getName()+".out"); 899 } 900 901 // Rewrite branches to basic blocks outside of the loop to new dummy blocks 902 // within the new function. This must be done before we lose track of which 903 // blocks were originally in the code region. 904 std::vector<User *> Users(header->user_begin(), header->user_end()); 905 for (unsigned i = 0, e = Users.size(); i != e; ++i) 906 // The BasicBlock which contains the branch is not in the region 907 // modify the branch target to a new block 908 if (Instruction *I = dyn_cast<Instruction>(Users[i])) 909 if (I->isTerminator() && !Blocks.count(I->getParent()) && 910 I->getParent()->getParent() == oldFunction) 911 I->replaceUsesOfWith(header, newHeader); 912 913 return newFunction; 914 } 915 916 /// Erase lifetime.start markers which reference inputs to the extraction 917 /// region, and insert the referenced memory into \p LifetimesStart. 918 /// 919 /// The extraction region is defined by a set of blocks (\p Blocks), and a set 920 /// of allocas which will be moved from the caller function into the extracted 921 /// function (\p SunkAllocas). 922 static void eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock *> &Blocks, 923 const SetVector<Value *> &SunkAllocas, 924 SetVector<Value *> &LifetimesStart) { 925 for (BasicBlock *BB : Blocks) { 926 for (auto It = BB->begin(), End = BB->end(); It != End;) { 927 auto *II = dyn_cast<IntrinsicInst>(&*It); 928 ++It; 929 if (!II || !II->isLifetimeStartOrEnd()) 930 continue; 931 932 // Get the memory operand of the lifetime marker. If the underlying 933 // object is a sunk alloca, or is otherwise defined in the extraction 934 // region, the lifetime marker must not be erased. 935 Value *Mem = II->getOperand(1)->stripInBoundsOffsets(); 936 if (SunkAllocas.count(Mem) || definedInRegion(Blocks, Mem)) 937 continue; 938 939 if (II->getIntrinsicID() == Intrinsic::lifetime_start) 940 LifetimesStart.insert(Mem); 941 II->eraseFromParent(); 942 } 943 } 944 } 945 946 /// Insert lifetime start/end markers surrounding the call to the new function 947 /// for objects defined in the caller. 948 static void insertLifetimeMarkersSurroundingCall( 949 Module *M, ArrayRef<Value *> LifetimesStart, ArrayRef<Value *> LifetimesEnd, 950 CallInst *TheCall) { 951 LLVMContext &Ctx = M->getContext(); 952 auto Int8PtrTy = Type::getInt8PtrTy(Ctx); 953 auto NegativeOne = ConstantInt::getSigned(Type::getInt64Ty(Ctx), -1); 954 Instruction *Term = TheCall->getParent()->getTerminator(); 955 956 // The memory argument to a lifetime marker must be a i8*. Cache any bitcasts 957 // needed to satisfy this requirement so they may be reused. 958 DenseMap<Value *, Value *> Bitcasts; 959 960 // Emit lifetime markers for the pointers given in \p Objects. Insert the 961 // markers before the call if \p InsertBefore, and after the call otherwise. 962 auto insertMarkers = [&](Function *MarkerFunc, ArrayRef<Value *> Objects, 963 bool InsertBefore) { 964 for (Value *Mem : Objects) { 965 assert((!isa<Instruction>(Mem) || cast<Instruction>(Mem)->getFunction() == 966 TheCall->getFunction()) && 967 "Input memory not defined in original function"); 968 Value *&MemAsI8Ptr = Bitcasts[Mem]; 969 if (!MemAsI8Ptr) { 970 if (Mem->getType() == Int8PtrTy) 971 MemAsI8Ptr = Mem; 972 else 973 MemAsI8Ptr = 974 CastInst::CreatePointerCast(Mem, Int8PtrTy, "lt.cast", TheCall); 975 } 976 977 auto Marker = CallInst::Create(MarkerFunc, {NegativeOne, MemAsI8Ptr}); 978 if (InsertBefore) 979 Marker->insertBefore(TheCall); 980 else 981 Marker->insertBefore(Term); 982 } 983 }; 984 985 if (!LifetimesStart.empty()) { 986 auto StartFn = llvm::Intrinsic::getDeclaration( 987 M, llvm::Intrinsic::lifetime_start, Int8PtrTy); 988 insertMarkers(StartFn, LifetimesStart, /*InsertBefore=*/true); 989 } 990 991 if (!LifetimesEnd.empty()) { 992 auto EndFn = llvm::Intrinsic::getDeclaration( 993 M, llvm::Intrinsic::lifetime_end, Int8PtrTy); 994 insertMarkers(EndFn, LifetimesEnd, /*InsertBefore=*/false); 995 } 996 } 997 998 /// emitCallAndSwitchStatement - This method sets up the caller side by adding 999 /// the call instruction, splitting any PHI nodes in the header block as 1000 /// necessary. 1001 CallInst *CodeExtractor::emitCallAndSwitchStatement(Function *newFunction, 1002 BasicBlock *codeReplacer, 1003 ValueSet &inputs, 1004 ValueSet &outputs) { 1005 // Emit a call to the new function, passing in: *pointer to struct (if 1006 // aggregating parameters), or plan inputs and allocated memory for outputs 1007 std::vector<Value *> params, StructValues, ReloadOutputs, Reloads; 1008 1009 Module *M = newFunction->getParent(); 1010 LLVMContext &Context = M->getContext(); 1011 const DataLayout &DL = M->getDataLayout(); 1012 CallInst *call = nullptr; 1013 1014 // Add inputs as params, or to be filled into the struct 1015 unsigned ArgNo = 0; 1016 SmallVector<unsigned, 1> SwiftErrorArgs; 1017 for (Value *input : inputs) { 1018 if (AggregateArgs) 1019 StructValues.push_back(input); 1020 else { 1021 params.push_back(input); 1022 if (input->isSwiftError()) 1023 SwiftErrorArgs.push_back(ArgNo); 1024 } 1025 ++ArgNo; 1026 } 1027 1028 // Create allocas for the outputs 1029 for (Value *output : outputs) { 1030 if (AggregateArgs) { 1031 StructValues.push_back(output); 1032 } else { 1033 AllocaInst *alloca = 1034 new AllocaInst(output->getType(), DL.getAllocaAddrSpace(), 1035 nullptr, output->getName() + ".loc", 1036 &codeReplacer->getParent()->front().front()); 1037 ReloadOutputs.push_back(alloca); 1038 params.push_back(alloca); 1039 } 1040 } 1041 1042 StructType *StructArgTy = nullptr; 1043 AllocaInst *Struct = nullptr; 1044 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { 1045 std::vector<Type *> ArgTypes; 1046 for (ValueSet::iterator v = StructValues.begin(), 1047 ve = StructValues.end(); v != ve; ++v) 1048 ArgTypes.push_back((*v)->getType()); 1049 1050 // Allocate a struct at the beginning of this function 1051 StructArgTy = StructType::get(newFunction->getContext(), ArgTypes); 1052 Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr, 1053 "structArg", 1054 &codeReplacer->getParent()->front().front()); 1055 params.push_back(Struct); 1056 1057 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 1058 Value *Idx[2]; 1059 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 1060 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i); 1061 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1062 StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName()); 1063 codeReplacer->getInstList().push_back(GEP); 1064 StoreInst *SI = new StoreInst(StructValues[i], GEP); 1065 codeReplacer->getInstList().push_back(SI); 1066 } 1067 } 1068 1069 // Emit the call to the function 1070 call = CallInst::Create(newFunction, params, 1071 NumExitBlocks > 1 ? "targetBlock" : ""); 1072 // Add debug location to the new call, if the original function has debug 1073 // info. In that case, the terminator of the entry block of the extracted 1074 // function contains the first debug location of the extracted function, 1075 // set in extractCodeRegion. 1076 if (codeReplacer->getParent()->getSubprogram()) { 1077 if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc()) 1078 call->setDebugLoc(DL); 1079 } 1080 codeReplacer->getInstList().push_back(call); 1081 1082 // Set swifterror parameter attributes. 1083 for (unsigned SwiftErrArgNo : SwiftErrorArgs) { 1084 call->addParamAttr(SwiftErrArgNo, Attribute::SwiftError); 1085 newFunction->addParamAttr(SwiftErrArgNo, Attribute::SwiftError); 1086 } 1087 1088 Function::arg_iterator OutputArgBegin = newFunction->arg_begin(); 1089 unsigned FirstOut = inputs.size(); 1090 if (!AggregateArgs) 1091 std::advance(OutputArgBegin, inputs.size()); 1092 1093 // Reload the outputs passed in by reference. 1094 for (unsigned i = 0, e = outputs.size(); i != e; ++i) { 1095 Value *Output = nullptr; 1096 if (AggregateArgs) { 1097 Value *Idx[2]; 1098 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 1099 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i); 1100 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1101 StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName()); 1102 codeReplacer->getInstList().push_back(GEP); 1103 Output = GEP; 1104 } else { 1105 Output = ReloadOutputs[i]; 1106 } 1107 LoadInst *load = new LoadInst(outputs[i]->getType(), Output, 1108 outputs[i]->getName() + ".reload"); 1109 Reloads.push_back(load); 1110 codeReplacer->getInstList().push_back(load); 1111 std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end()); 1112 for (unsigned u = 0, e = Users.size(); u != e; ++u) { 1113 Instruction *inst = cast<Instruction>(Users[u]); 1114 if (!Blocks.count(inst->getParent())) 1115 inst->replaceUsesOfWith(outputs[i], load); 1116 } 1117 } 1118 1119 // Now we can emit a switch statement using the call as a value. 1120 SwitchInst *TheSwitch = 1121 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)), 1122 codeReplacer, 0, codeReplacer); 1123 1124 // Since there may be multiple exits from the original region, make the new 1125 // function return an unsigned, switch on that number. This loop iterates 1126 // over all of the blocks in the extracted region, updating any terminator 1127 // instructions in the to-be-extracted region that branch to blocks that are 1128 // not in the region to be extracted. 1129 std::map<BasicBlock *, BasicBlock *> ExitBlockMap; 1130 1131 unsigned switchVal = 0; 1132 for (BasicBlock *Block : Blocks) { 1133 Instruction *TI = Block->getTerminator(); 1134 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 1135 if (!Blocks.count(TI->getSuccessor(i))) { 1136 BasicBlock *OldTarget = TI->getSuccessor(i); 1137 // add a new basic block which returns the appropriate value 1138 BasicBlock *&NewTarget = ExitBlockMap[OldTarget]; 1139 if (!NewTarget) { 1140 // If we don't already have an exit stub for this non-extracted 1141 // destination, create one now! 1142 NewTarget = BasicBlock::Create(Context, 1143 OldTarget->getName() + ".exitStub", 1144 newFunction); 1145 unsigned SuccNum = switchVal++; 1146 1147 Value *brVal = nullptr; 1148 switch (NumExitBlocks) { 1149 case 0: 1150 case 1: break; // No value needed. 1151 case 2: // Conditional branch, return a bool 1152 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum); 1153 break; 1154 default: 1155 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum); 1156 break; 1157 } 1158 1159 ReturnInst::Create(Context, brVal, NewTarget); 1160 1161 // Update the switch instruction. 1162 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context), 1163 SuccNum), 1164 OldTarget); 1165 } 1166 1167 // rewrite the original branch instruction with this new target 1168 TI->setSuccessor(i, NewTarget); 1169 } 1170 } 1171 1172 // Store the arguments right after the definition of output value. 1173 // This should be proceeded after creating exit stubs to be ensure that invoke 1174 // result restore will be placed in the outlined function. 1175 Function::arg_iterator OAI = OutputArgBegin; 1176 for (unsigned i = 0, e = outputs.size(); i != e; ++i) { 1177 auto *OutI = dyn_cast<Instruction>(outputs[i]); 1178 if (!OutI) 1179 continue; 1180 1181 // Find proper insertion point. 1182 BasicBlock::iterator InsertPt; 1183 // In case OutI is an invoke, we insert the store at the beginning in the 1184 // 'normal destination' BB. Otherwise we insert the store right after OutI. 1185 if (auto *InvokeI = dyn_cast<InvokeInst>(OutI)) 1186 InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt(); 1187 else if (auto *Phi = dyn_cast<PHINode>(OutI)) 1188 InsertPt = Phi->getParent()->getFirstInsertionPt(); 1189 else 1190 InsertPt = std::next(OutI->getIterator()); 1191 1192 Instruction *InsertBefore = &*InsertPt; 1193 assert((InsertBefore->getFunction() == newFunction || 1194 Blocks.count(InsertBefore->getParent())) && 1195 "InsertPt should be in new function"); 1196 assert(OAI != newFunction->arg_end() && 1197 "Number of output arguments should match " 1198 "the amount of defined values"); 1199 if (AggregateArgs) { 1200 Value *Idx[2]; 1201 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 1202 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i); 1203 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1204 StructArgTy, &*OAI, Idx, "gep_" + outputs[i]->getName(), 1205 InsertBefore); 1206 new StoreInst(outputs[i], GEP, InsertBefore); 1207 // Since there should be only one struct argument aggregating 1208 // all the output values, we shouldn't increment OAI, which always 1209 // points to the struct argument, in this case. 1210 } else { 1211 new StoreInst(outputs[i], &*OAI, InsertBefore); 1212 ++OAI; 1213 } 1214 } 1215 1216 // Now that we've done the deed, simplify the switch instruction. 1217 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType(); 1218 switch (NumExitBlocks) { 1219 case 0: 1220 // There are no successors (the block containing the switch itself), which 1221 // means that previously this was the last part of the function, and hence 1222 // this should be rewritten as a `ret' 1223 1224 // Check if the function should return a value 1225 if (OldFnRetTy->isVoidTy()) { 1226 ReturnInst::Create(Context, nullptr, TheSwitch); // Return void 1227 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) { 1228 // return what we have 1229 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch); 1230 } else { 1231 // Otherwise we must have code extracted an unwind or something, just 1232 // return whatever we want. 1233 ReturnInst::Create(Context, 1234 Constant::getNullValue(OldFnRetTy), TheSwitch); 1235 } 1236 1237 TheSwitch->eraseFromParent(); 1238 break; 1239 case 1: 1240 // Only a single destination, change the switch into an unconditional 1241 // branch. 1242 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch); 1243 TheSwitch->eraseFromParent(); 1244 break; 1245 case 2: 1246 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2), 1247 call, TheSwitch); 1248 TheSwitch->eraseFromParent(); 1249 break; 1250 default: 1251 // Otherwise, make the default destination of the switch instruction be one 1252 // of the other successors. 1253 TheSwitch->setCondition(call); 1254 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks)); 1255 // Remove redundant case 1256 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1)); 1257 break; 1258 } 1259 1260 // Insert lifetime markers around the reloads of any output values. The 1261 // allocas output values are stored in are only in-use in the codeRepl block. 1262 insertLifetimeMarkersSurroundingCall(M, ReloadOutputs, ReloadOutputs, call); 1263 1264 return call; 1265 } 1266 1267 void CodeExtractor::moveCodeToFunction(Function *newFunction) { 1268 Function *oldFunc = (*Blocks.begin())->getParent(); 1269 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList(); 1270 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList(); 1271 1272 for (BasicBlock *Block : Blocks) { 1273 // Delete the basic block from the old function, and the list of blocks 1274 oldBlocks.remove(Block); 1275 1276 // Insert this basic block into the new function 1277 newBlocks.push_back(Block); 1278 1279 // Remove @llvm.assume calls that were moved to the new function from the 1280 // old function's assumption cache. 1281 if (AC) 1282 for (auto &I : *Block) 1283 if (match(&I, m_Intrinsic<Intrinsic::assume>())) 1284 AC->unregisterAssumption(cast<CallInst>(&I)); 1285 } 1286 } 1287 1288 void CodeExtractor::calculateNewCallTerminatorWeights( 1289 BasicBlock *CodeReplacer, 1290 DenseMap<BasicBlock *, BlockFrequency> &ExitWeights, 1291 BranchProbabilityInfo *BPI) { 1292 using Distribution = BlockFrequencyInfoImplBase::Distribution; 1293 using BlockNode = BlockFrequencyInfoImplBase::BlockNode; 1294 1295 // Update the branch weights for the exit block. 1296 Instruction *TI = CodeReplacer->getTerminator(); 1297 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0); 1298 1299 // Block Frequency distribution with dummy node. 1300 Distribution BranchDist; 1301 1302 // Add each of the frequencies of the successors. 1303 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) { 1304 BlockNode ExitNode(i); 1305 uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency(); 1306 if (ExitFreq != 0) 1307 BranchDist.addExit(ExitNode, ExitFreq); 1308 else 1309 BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero()); 1310 } 1311 1312 // Check for no total weight. 1313 if (BranchDist.Total == 0) 1314 return; 1315 1316 // Normalize the distribution so that they can fit in unsigned. 1317 BranchDist.normalize(); 1318 1319 // Create normalized branch weights and set the metadata. 1320 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) { 1321 const auto &Weight = BranchDist.Weights[I]; 1322 1323 // Get the weight and update the current BFI. 1324 BranchWeights[Weight.TargetNode.Index] = Weight.Amount; 1325 BranchProbability BP(Weight.Amount, BranchDist.Total); 1326 BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP); 1327 } 1328 TI->setMetadata( 1329 LLVMContext::MD_prof, 1330 MDBuilder(TI->getContext()).createBranchWeights(BranchWeights)); 1331 } 1332 1333 Function *CodeExtractor::extractCodeRegion() { 1334 if (!isEligible()) 1335 return nullptr; 1336 1337 // Assumption: this is a single-entry code region, and the header is the first 1338 // block in the region. 1339 BasicBlock *header = *Blocks.begin(); 1340 Function *oldFunction = header->getParent(); 1341 1342 // For functions with varargs, check that varargs handling is only done in the 1343 // outlined function, i.e vastart and vaend are only used in outlined blocks. 1344 if (AllowVarArgs && oldFunction->getFunctionType()->isVarArg()) { 1345 auto containsVarArgIntrinsic = [](Instruction &I) { 1346 if (const CallInst *CI = dyn_cast<CallInst>(&I)) 1347 if (const Function *F = CI->getCalledFunction()) 1348 return F->getIntrinsicID() == Intrinsic::vastart || 1349 F->getIntrinsicID() == Intrinsic::vaend; 1350 return false; 1351 }; 1352 1353 for (auto &BB : *oldFunction) { 1354 if (Blocks.count(&BB)) 1355 continue; 1356 if (llvm::any_of(BB, containsVarArgIntrinsic)) 1357 return nullptr; 1358 } 1359 } 1360 ValueSet inputs, outputs, SinkingCands, HoistingCands; 1361 BasicBlock *CommonExit = nullptr; 1362 1363 // Calculate the entry frequency of the new function before we change the root 1364 // block. 1365 BlockFrequency EntryFreq; 1366 if (BFI) { 1367 assert(BPI && "Both BPI and BFI are required to preserve profile info"); 1368 for (BasicBlock *Pred : predecessors(header)) { 1369 if (Blocks.count(Pred)) 1370 continue; 1371 EntryFreq += 1372 BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header); 1373 } 1374 } 1375 1376 // If we have any return instructions in the region, split those blocks so 1377 // that the return is not in the region. 1378 splitReturnBlocks(); 1379 1380 // Calculate the exit blocks for the extracted region and the total exit 1381 // weights for each of those blocks. 1382 DenseMap<BasicBlock *, BlockFrequency> ExitWeights; 1383 SmallPtrSet<BasicBlock *, 1> ExitBlocks; 1384 for (BasicBlock *Block : Blocks) { 1385 for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE; 1386 ++SI) { 1387 if (!Blocks.count(*SI)) { 1388 // Update the branch weight for this successor. 1389 if (BFI) { 1390 BlockFrequency &BF = ExitWeights[*SI]; 1391 BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI); 1392 } 1393 ExitBlocks.insert(*SI); 1394 } 1395 } 1396 } 1397 NumExitBlocks = ExitBlocks.size(); 1398 1399 // If we have to split PHI nodes of the entry or exit blocks, do so now. 1400 severSplitPHINodesOfEntry(header); 1401 severSplitPHINodesOfExits(ExitBlocks); 1402 1403 // This takes place of the original loop 1404 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(), 1405 "codeRepl", oldFunction, 1406 header); 1407 1408 // The new function needs a root node because other nodes can branch to the 1409 // head of the region, but the entry node of a function cannot have preds. 1410 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(), 1411 "newFuncRoot"); 1412 auto *BranchI = BranchInst::Create(header); 1413 // If the original function has debug info, we have to add a debug location 1414 // to the new branch instruction from the artificial entry block. 1415 // We use the debug location of the first instruction in the extracted 1416 // blocks, as there is no other equivalent line in the source code. 1417 if (oldFunction->getSubprogram()) { 1418 any_of(Blocks, [&BranchI](const BasicBlock *BB) { 1419 return any_of(*BB, [&BranchI](const Instruction &I) { 1420 if (!I.getDebugLoc()) 1421 return false; 1422 BranchI->setDebugLoc(I.getDebugLoc()); 1423 return true; 1424 }); 1425 }); 1426 } 1427 newFuncRoot->getInstList().push_back(BranchI); 1428 1429 findAllocas(SinkingCands, HoistingCands, CommonExit); 1430 assert(HoistingCands.empty() || CommonExit); 1431 1432 // Find inputs to, outputs from the code region. 1433 findInputsOutputs(inputs, outputs, SinkingCands); 1434 1435 // Now sink all instructions which only have non-phi uses inside the region. 1436 // Group the allocas at the start of the block, so that any bitcast uses of 1437 // the allocas are well-defined. 1438 AllocaInst *FirstSunkAlloca = nullptr; 1439 for (auto *II : SinkingCands) { 1440 if (auto *AI = dyn_cast<AllocaInst>(II)) { 1441 AI->moveBefore(*newFuncRoot, newFuncRoot->getFirstInsertionPt()); 1442 if (!FirstSunkAlloca) 1443 FirstSunkAlloca = AI; 1444 } 1445 } 1446 assert((SinkingCands.empty() || FirstSunkAlloca) && 1447 "Did not expect a sink candidate without any allocas"); 1448 for (auto *II : SinkingCands) { 1449 if (!isa<AllocaInst>(II)) { 1450 cast<Instruction>(II)->moveAfter(FirstSunkAlloca); 1451 } 1452 } 1453 1454 if (!HoistingCands.empty()) { 1455 auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit); 1456 Instruction *TI = HoistToBlock->getTerminator(); 1457 for (auto *II : HoistingCands) 1458 cast<Instruction>(II)->moveBefore(TI); 1459 } 1460 1461 // Collect objects which are inputs to the extraction region and also 1462 // referenced by lifetime start markers within it. The effects of these 1463 // markers must be replicated in the calling function to prevent the stack 1464 // coloring pass from merging slots which store input objects. 1465 ValueSet LifetimesStart; 1466 eraseLifetimeMarkersOnInputs(Blocks, SinkingCands, LifetimesStart); 1467 1468 // Construct new function based on inputs/outputs & add allocas for all defs. 1469 Function *newFunction = 1470 constructFunction(inputs, outputs, header, newFuncRoot, codeReplacer, 1471 oldFunction, oldFunction->getParent()); 1472 1473 // Update the entry count of the function. 1474 if (BFI) { 1475 auto Count = BFI->getProfileCountFromFreq(EntryFreq.getFrequency()); 1476 if (Count.hasValue()) 1477 newFunction->setEntryCount( 1478 ProfileCount(Count.getValue(), Function::PCT_Real)); // FIXME 1479 BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency()); 1480 } 1481 1482 CallInst *TheCall = 1483 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs); 1484 1485 moveCodeToFunction(newFunction); 1486 1487 // Replicate the effects of any lifetime start/end markers which referenced 1488 // input objects in the extraction region by placing markers around the call. 1489 insertLifetimeMarkersSurroundingCall( 1490 oldFunction->getParent(), LifetimesStart.getArrayRef(), {}, TheCall); 1491 1492 // Propagate personality info to the new function if there is one. 1493 if (oldFunction->hasPersonalityFn()) 1494 newFunction->setPersonalityFn(oldFunction->getPersonalityFn()); 1495 1496 // Update the branch weights for the exit block. 1497 if (BFI && NumExitBlocks > 1) 1498 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI); 1499 1500 // Loop over all of the PHI nodes in the header and exit blocks, and change 1501 // any references to the old incoming edge to be the new incoming edge. 1502 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) { 1503 PHINode *PN = cast<PHINode>(I); 1504 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 1505 if (!Blocks.count(PN->getIncomingBlock(i))) 1506 PN->setIncomingBlock(i, newFuncRoot); 1507 } 1508 1509 for (BasicBlock *ExitBB : ExitBlocks) 1510 for (PHINode &PN : ExitBB->phis()) { 1511 Value *IncomingCodeReplacerVal = nullptr; 1512 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 1513 // Ignore incoming values from outside of the extracted region. 1514 if (!Blocks.count(PN.getIncomingBlock(i))) 1515 continue; 1516 1517 // Ensure that there is only one incoming value from codeReplacer. 1518 if (!IncomingCodeReplacerVal) { 1519 PN.setIncomingBlock(i, codeReplacer); 1520 IncomingCodeReplacerVal = PN.getIncomingValue(i); 1521 } else 1522 assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) && 1523 "PHI has two incompatbile incoming values from codeRepl"); 1524 } 1525 } 1526 1527 // Erase debug info intrinsics. Variable updates within the new function are 1528 // invisible to debuggers. This could be improved by defining a DISubprogram 1529 // for the new function. 1530 for (BasicBlock &BB : *newFunction) { 1531 auto BlockIt = BB.begin(); 1532 // Remove debug info intrinsics from the new function. 1533 while (BlockIt != BB.end()) { 1534 Instruction *Inst = &*BlockIt; 1535 ++BlockIt; 1536 if (isa<DbgInfoIntrinsic>(Inst)) 1537 Inst->eraseFromParent(); 1538 } 1539 // Remove debug info intrinsics which refer to values in the new function 1540 // from the old function. 1541 SmallVector<DbgVariableIntrinsic *, 4> DbgUsers; 1542 for (Instruction &I : BB) 1543 findDbgUsers(DbgUsers, &I); 1544 for (DbgVariableIntrinsic *DVI : DbgUsers) 1545 DVI->eraseFromParent(); 1546 } 1547 1548 // Mark the new function `noreturn` if applicable. Terminators which resume 1549 // exception propagation are treated as returning instructions. This is to 1550 // avoid inserting traps after calls to outlined functions which unwind. 1551 bool doesNotReturn = none_of(*newFunction, [](const BasicBlock &BB) { 1552 const Instruction *Term = BB.getTerminator(); 1553 return isa<ReturnInst>(Term) || isa<ResumeInst>(Term); 1554 }); 1555 if (doesNotReturn) 1556 newFunction->setDoesNotReturn(); 1557 1558 LLVM_DEBUG(if (verifyFunction(*newFunction, &errs())) { 1559 newFunction->dump(); 1560 report_fatal_error("verification of newFunction failed!"); 1561 }); 1562 LLVM_DEBUG(if (verifyFunction(*oldFunction)) 1563 report_fatal_error("verification of oldFunction failed!")); 1564 return newFunction; 1565 } 1566