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