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