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/STLExtras.h"
19#include "llvm/ADT/SetVector.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/Analysis/AssumptionCache.h"
23#include "llvm/Analysis/BlockFrequencyInfo.h"
24#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
25#include "llvm/Analysis/BranchProbabilityInfo.h"
26#include "llvm/IR/Argument.h"
27#include "llvm/IR/Attributes.h"
28#include "llvm/IR/CFG.h"
29#include "llvm/IR/Constant.h"
30#include "llvm/IR/Constants.h"
31#include "llvm/IR/DIBuilder.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DebugInfo.h"
34#include "llvm/IR/DebugInfoMetadata.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/InstIterator.h"
40#include "llvm/IR/InstrTypes.h"
41#include "llvm/IR/Instruction.h"
42#include "llvm/IR/Instructions.h"
43#include "llvm/IR/IntrinsicInst.h"
44#include "llvm/IR/Intrinsics.h"
45#include "llvm/IR/LLVMContext.h"
46#include "llvm/IR/MDBuilder.h"
47#include "llvm/IR/Module.h"
48#include "llvm/IR/PatternMatch.h"
49#include "llvm/IR/Type.h"
50#include "llvm/IR/User.h"
51#include "llvm/IR/Value.h"
52#include "llvm/IR/Verifier.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 <cassert>
62#include <cstdint>
63#include <iterator>
64#include <map>
65#include <vector>
66
67using namespace llvm;
68using namespace llvm::PatternMatch;
69
70#define DEBUG_TYPE "code-extractor"
71
72// Provide a command-line option to aggregate function arguments into a struct
73// for functions produced by the code extractor. This is useful when converting
74// extracted functions to pthread-based code, as only one argument (void*) can
75// be passed in to pthread_create().
76static cl::opt<bool>
77AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
78 cl::desc("Aggregate arguments to code-extracted functions"));
79
80/// Test whether a block is valid for extraction.
81static bool isBlockValidForExtraction(const BasicBlock &BB,
82 const SetVector<BasicBlock *> &Result,
83 bool AllowVarArgs, bool AllowAlloca) {
84 // taking the address of a basic block moved to another function is illegal
85 if (BB.hasAddressTaken())
86 return false;
87
88 // don't hoist code that uses another basicblock address, as it's likely to
89 // lead to unexpected behavior, like cross-function jumps
90 SmallPtrSet<User const *, 16> Visited;
91 SmallVector<User const *, 16> ToVisit(llvm::make_pointer_range(Range: BB));
92
93 while (!ToVisit.empty()) {
94 User const *Curr = ToVisit.pop_back_val();
95 if (!Visited.insert(Ptr: Curr).second)
96 continue;
97 if (isa<BlockAddress const>(Val: Curr))
98 return false; // even a reference to self is likely to be not compatible
99
100 if (isa<Instruction>(Val: Curr) && cast<Instruction>(Val: Curr)->getParent() != &BB)
101 continue;
102
103 for (auto const &U : Curr->operands()) {
104 if (auto *UU = dyn_cast<User>(Val: U))
105 ToVisit.push_back(Elt: UU);
106 }
107 }
108
109 // If explicitly requested, allow vastart and alloca. For invoke instructions
110 // verify that extraction is valid.
111 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
112 if (isa<AllocaInst>(Val: I)) {
113 if (!AllowAlloca)
114 return false;
115 continue;
116 }
117
118 if (const auto *II = dyn_cast<InvokeInst>(Val&: I)) {
119 // Unwind destination (either a landingpad, catchswitch, or cleanuppad)
120 // must be a part of the subgraph which is being extracted.
121 if (auto *UBB = II->getUnwindDest())
122 if (!Result.count(key: UBB))
123 return false;
124 continue;
125 }
126
127 // All catch handlers of a catchswitch instruction as well as the unwind
128 // destination must be in the subgraph.
129 if (const auto *CSI = dyn_cast<CatchSwitchInst>(Val&: I)) {
130 if (auto *UBB = CSI->getUnwindDest())
131 if (!Result.count(key: UBB))
132 return false;
133 for (const auto *HBB : CSI->handlers())
134 if (!Result.count(key: const_cast<BasicBlock*>(HBB)))
135 return false;
136 continue;
137 }
138
139 // Make sure that entire catch handler is within subgraph. It is sufficient
140 // to check that catch return's block is in the list.
141 if (const auto *CPI = dyn_cast<CatchPadInst>(Val&: I)) {
142 for (const auto *U : CPI->users())
143 if (const auto *CRI = dyn_cast<CatchReturnInst>(Val: U))
144 if (!Result.count(key: const_cast<BasicBlock*>(CRI->getParent())))
145 return false;
146 continue;
147 }
148
149 // And do similar checks for cleanup handler - the entire handler must be
150 // in subgraph which is going to be extracted. For cleanup return should
151 // additionally check that the unwind destination is also in the subgraph.
152 if (const auto *CPI = dyn_cast<CleanupPadInst>(Val&: I)) {
153 for (const auto *U : CPI->users())
154 if (const auto *CRI = dyn_cast<CleanupReturnInst>(Val: U))
155 if (!Result.count(key: const_cast<BasicBlock*>(CRI->getParent())))
156 return false;
157 continue;
158 }
159 if (const auto *CRI = dyn_cast<CleanupReturnInst>(Val&: I)) {
160 if (auto *UBB = CRI->getUnwindDest())
161 if (!Result.count(key: UBB))
162 return false;
163 continue;
164 }
165
166 // llvm.experimental.deoptimize must return the enclosing function's return
167 // type. Extraction changes the outlined function signature, which can make
168 // the deoptimize call invalid.
169 if (BB.getTerminatingDeoptimizeCall())
170 return false;
171
172 if (const CallInst *CI = dyn_cast<CallInst>(Val&: I)) {
173 // musttail calls have several restrictions, generally enforcing matching
174 // calling conventions between the caller parent and musttail callee.
175 // We can't usually honor them, because the extracted function has a
176 // different signature altogether, taking inputs/outputs and returning
177 // a control-flow identifier rather than the actual return value.
178 if (CI->isMustTailCall())
179 return false;
180
181 if (const Function *F = CI->getCalledFunction()) {
182 auto IID = F->getIntrinsicID();
183 if (IID == Intrinsic::vastart) {
184 if (AllowVarArgs)
185 continue;
186 else
187 return false;
188 }
189
190 // Currently, we miscompile outlined copies of eh_typid_for. There are
191 // proposals for fixing this in llvm.org/PR39545.
192 if (IID == Intrinsic::eh_typeid_for)
193 return false;
194 }
195 }
196 }
197
198 return true;
199}
200
201/// Build a set of blocks to extract if the input blocks are viable.
202static SetVector<BasicBlock *>
203buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
204 bool AllowVarArgs, bool AllowAlloca) {
205 assert(!BBs.empty() && "The set of blocks to extract must be non-empty");
206 SetVector<BasicBlock *> Result;
207
208 // Loop over the blocks, adding them to our set-vector, and aborting with an
209 // empty set if we encounter invalid blocks.
210 for (BasicBlock *BB : BBs) {
211 // If this block is dead, don't process it.
212 if (DT && !DT->isReachableFromEntry(A: BB))
213 continue;
214
215 if (!Result.insert(X: BB))
216 llvm_unreachable("Repeated basic blocks in extraction input");
217 }
218
219 LLVM_DEBUG(dbgs() << "Region front block: " << Result.front()->getName()
220 << '\n');
221
222 for (auto *BB : Result) {
223 if (!isBlockValidForExtraction(BB: *BB, Result, AllowVarArgs, AllowAlloca))
224 return {};
225
226 // Make sure that the first block is not a landing pad.
227 if (BB == Result.front()) {
228 if (BB->isEHPad()) {
229 LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n");
230 return {};
231 }
232 continue;
233 }
234
235 // All blocks other than the first must not have predecessors outside of
236 // the subgraph which is being extracted.
237 for (auto *PBB : predecessors(BB))
238 if (!Result.count(key: PBB)) {
239 LLVM_DEBUG(dbgs() << "No blocks in this region may have entries from "
240 "outside the region except for the first block!\n"
241 << "Problematic source BB: " << BB->getName() << "\n"
242 << "Problematic destination BB: " << PBB->getName()
243 << "\n");
244 return {};
245 }
246 }
247
248 return Result;
249}
250
251/// isAlignmentPreservedForAddrCast - Return true if the cast operation
252/// for specified target preserves original alignment
253static bool isAlignmentPreservedForAddrCast(const Triple &TargetTriple) {
254 switch (TargetTriple.getArch()) {
255 case Triple::ArchType::amdgpu:
256 case Triple::ArchType::r600:
257 return true;
258 // TODO: Add other architectures for which we are certain that alignment
259 // is preserved during address space cast operations.
260 default:
261 return false;
262 }
263 return false;
264}
265
266CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
267 bool AggregateArgs, BlockFrequencyInfo *BFI,
268 BranchProbabilityInfo *BPI, AssumptionCache *AC,
269 bool AllowVarArgs, bool AllowAlloca,
270 BasicBlock *AllocationBlock,
271 ArrayRef<BasicBlock *> DeallocationBlocks,
272 std::string Suffix, bool ArgsInZeroAddressSpace,
273 bool VoidReturnWithSingleOutput)
274 : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
275 BPI(BPI), AC(AC), AllocationBlock(AllocationBlock),
276 DeallocationBlocks(DeallocationBlocks), AllowVarArgs(AllowVarArgs),
277 Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)),
278 Suffix(Suffix), ArgsInZeroAddressSpace(ArgsInZeroAddressSpace),
279 VoidReturnWithSingleOutput(VoidReturnWithSingleOutput) {}
280
281/// definedInRegion - Return true if the specified value is defined in the
282/// extracted region.
283static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
284 if (Instruction *I = dyn_cast<Instruction>(Val: V))
285 if (Blocks.count(key: I->getParent()))
286 return true;
287 return false;
288}
289
290/// definedInCaller - Return true if the specified value is defined in the
291/// function being code extracted, but not in the region being extracted.
292/// These values must be passed in as live-ins to the function.
293static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
294 if (isa<Argument>(Val: V)) return true;
295 if (Instruction *I = dyn_cast<Instruction>(Val: V))
296 if (!Blocks.count(key: I->getParent()))
297 return true;
298 return false;
299}
300
301static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) {
302 BasicBlock *CommonExitBlock = nullptr;
303 auto hasNonCommonExitSucc = [&](BasicBlock *Block) {
304 for (auto *Succ : successors(BB: Block)) {
305 // Internal edges, ok.
306 if (Blocks.count(key: Succ))
307 continue;
308 if (!CommonExitBlock) {
309 CommonExitBlock = Succ;
310 continue;
311 }
312 if (CommonExitBlock != Succ)
313 return true;
314 }
315 return false;
316 };
317
318 if (any_of(Range: Blocks, P: hasNonCommonExitSucc))
319 return nullptr;
320
321 return CommonExitBlock;
322}
323
324CodeExtractorAnalysisCache::CodeExtractorAnalysisCache(Function &F) {
325 for (BasicBlock &BB : F) {
326 for (Instruction &II : BB)
327 if (auto *AI = dyn_cast<AllocaInst>(Val: &II))
328 Allocas.push_back(Elt: AI);
329
330 findSideEffectInfoForBlock(BB);
331 }
332}
333
334void CodeExtractorAnalysisCache::findSideEffectInfoForBlock(BasicBlock &BB) {
335 for (Instruction &II : BB) {
336 unsigned Opcode = II.getOpcode();
337 Value *MemAddr = nullptr;
338 switch (Opcode) {
339 case Instruction::Store:
340 case Instruction::Load: {
341 if (Opcode == Instruction::Store) {
342 StoreInst *SI = cast<StoreInst>(Val: &II);
343 MemAddr = SI->getPointerOperand();
344 } else {
345 LoadInst *LI = cast<LoadInst>(Val: &II);
346 MemAddr = LI->getPointerOperand();
347 }
348 // Global variable can not be aliased with locals.
349 if (isa<Constant>(Val: MemAddr))
350 break;
351 Value *Base = MemAddr->stripInBoundsConstantOffsets();
352 if (!isa<AllocaInst>(Val: Base)) {
353 SideEffectingBlocks.insert(V: &BB);
354 return;
355 }
356 BaseMemAddrs[&BB].insert(V: Base);
357 break;
358 }
359 default: {
360 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(Val: &II);
361 if (IntrInst) {
362 if (IntrInst->isLifetimeStartOrEnd() || isa<PseudoProbeInst>(Val: IntrInst))
363 break;
364 SideEffectingBlocks.insert(V: &BB);
365 return;
366 }
367 // Treat all the other cases conservatively if it has side effects.
368 if (II.mayHaveSideEffects()) {
369 SideEffectingBlocks.insert(V: &BB);
370 return;
371 }
372 }
373 }
374 }
375}
376
377bool CodeExtractorAnalysisCache::doesBlockContainClobberOfAddr(
378 BasicBlock &BB, AllocaInst *Addr) const {
379 if (SideEffectingBlocks.count(V: &BB))
380 return true;
381 auto It = BaseMemAddrs.find(Val: &BB);
382 if (It != BaseMemAddrs.end())
383 return It->second.count(V: Addr);
384 return false;
385}
386
387bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers(
388 const CodeExtractorAnalysisCache &CEAC, Instruction *Addr) const {
389 AllocaInst *AI = cast<AllocaInst>(Val: Addr->stripInBoundsConstantOffsets());
390 Function *Func = (*Blocks.begin())->getParent();
391 for (BasicBlock &BB : *Func) {
392 if (Blocks.count(key: &BB))
393 continue;
394 if (CEAC.doesBlockContainClobberOfAddr(BB, Addr: AI))
395 return false;
396 }
397 return true;
398}
399
400BasicBlock *
401CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) {
402 BasicBlock *SinglePredFromOutlineRegion = nullptr;
403 assert(!Blocks.count(CommonExitBlock) &&
404 "Expect a block outside the region!");
405 for (auto *Pred : predecessors(BB: CommonExitBlock)) {
406 if (!Blocks.count(key: Pred))
407 continue;
408 if (!SinglePredFromOutlineRegion) {
409 SinglePredFromOutlineRegion = Pred;
410 } else if (SinglePredFromOutlineRegion != Pred) {
411 SinglePredFromOutlineRegion = nullptr;
412 break;
413 }
414 }
415
416 if (SinglePredFromOutlineRegion)
417 return SinglePredFromOutlineRegion;
418
419#ifndef NDEBUG
420 auto getFirstPHI = [](BasicBlock *BB) {
421 BasicBlock::iterator I = BB->begin();
422 PHINode *FirstPhi = nullptr;
423 while (I != BB->end()) {
424 PHINode *Phi = dyn_cast<PHINode>(I);
425 if (!Phi)
426 break;
427 if (!FirstPhi) {
428 FirstPhi = Phi;
429 break;
430 }
431 }
432 return FirstPhi;
433 };
434 // If there are any phi nodes, the single pred either exists or has already
435 // be created before code extraction.
436 assert(!getFirstPHI(CommonExitBlock) && "Phi not expected");
437#endif
438
439 BasicBlock *NewExitBlock =
440 CommonExitBlock->splitBasicBlock(I: CommonExitBlock->getFirstNonPHIIt());
441
442 for (BasicBlock *Pred :
443 llvm::make_early_inc_range(Range: predecessors(BB: CommonExitBlock))) {
444 if (Blocks.count(key: Pred))
445 continue;
446 Pred->getTerminator()->replaceUsesOfWith(From: CommonExitBlock, To: NewExitBlock);
447 }
448 // Now add the old exit block to the outline region.
449 Blocks.insert(X: CommonExitBlock);
450 return CommonExitBlock;
451}
452
453Instruction *CodeExtractor::allocateVar(IRBuilder<>::InsertPoint AllocaIP,
454 Type *VarType, const Twine &Name,
455 AddrSpaceCastInst **CastedAlloc) {
456 const DataLayout &DL = AllocaIP.getBlock()->getModule()->getDataLayout();
457 Instruction *Alloca = new AllocaInst(VarType, DL.getAllocaAddrSpace(),
458 nullptr, Name, AllocaIP.getPoint());
459
460 if (CastedAlloc && ArgsInZeroAddressSpace && DL.getAllocaAddrSpace() != 0) {
461 *CastedAlloc = new AddrSpaceCastInst(
462 Alloca, PointerType::get(C&: AllocaIP.getBlock()->getContext(), AddressSpace: 0),
463 Name + ".ascast");
464 (*CastedAlloc)->insertAfter(InsertPos: Alloca->getIterator());
465 }
466 return Alloca;
467}
468
469Instruction *CodeExtractor::deallocateVar(IRBuilder<>::InsertPoint, Value *,
470 Type *) {
471 // Default alloca instructions created by allocateVar are released implicitly.
472 return nullptr;
473}
474
475// Find the pair of life time markers for address 'Addr' that are either
476// defined inside the outline region or can legally be shrinkwrapped into the
477// outline region. If there are not other untracked uses of the address, return
478// the pair of markers if found; otherwise return a pair of nullptr.
479CodeExtractor::LifetimeMarkerInfo
480CodeExtractor::getLifetimeMarkers(const CodeExtractorAnalysisCache &CEAC,
481 Instruction *Addr,
482 BasicBlock *ExitBlock) const {
483 LifetimeMarkerInfo Info;
484
485 for (User *U : Addr->users()) {
486 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(Val: U);
487 if (IntrInst) {
488 // We don't model addresses with multiple start/end markers, but the
489 // markers do not need to be in the region.
490 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) {
491 if (Info.LifeStart)
492 return {};
493 Info.LifeStart = IntrInst;
494 continue;
495 }
496 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) {
497 if (Info.LifeEnd)
498 return {};
499 Info.LifeEnd = IntrInst;
500 continue;
501 }
502 }
503 // Find untracked uses of the address, bail.
504 if (!definedInRegion(Blocks, V: U))
505 return {};
506 }
507
508 if (!Info.LifeStart || !Info.LifeEnd)
509 return {};
510
511 Info.SinkLifeStart = !definedInRegion(Blocks, V: Info.LifeStart);
512 Info.HoistLifeEnd = !definedInRegion(Blocks, V: Info.LifeEnd);
513 // Do legality check.
514 if ((Info.SinkLifeStart || Info.HoistLifeEnd) &&
515 !isLegalToShrinkwrapLifetimeMarkers(CEAC, Addr))
516 return {};
517
518 // Check to see if we have a place to do hoisting, if not, bail.
519 if (Info.HoistLifeEnd && !ExitBlock)
520 return {};
521
522 return Info;
523}
524
525void CodeExtractor::findAllocas(const CodeExtractorAnalysisCache &CEAC,
526 ValueSet &SinkCands, ValueSet &HoistCands,
527 BasicBlock *&ExitBlock) const {
528 Function *Func = (*Blocks.begin())->getParent();
529 ExitBlock = getCommonExitBlock(Blocks);
530
531 auto moveOrIgnoreLifetimeMarkers =
532 [&](const LifetimeMarkerInfo &LMI) -> bool {
533 if (!LMI.LifeStart)
534 return false;
535 if (LMI.SinkLifeStart) {
536 LLVM_DEBUG(dbgs() << "Sinking lifetime.start: " << *LMI.LifeStart
537 << "\n");
538 SinkCands.insert(X: LMI.LifeStart);
539 }
540 if (LMI.HoistLifeEnd) {
541 LLVM_DEBUG(dbgs() << "Hoisting lifetime.end: " << *LMI.LifeEnd << "\n");
542 HoistCands.insert(X: LMI.LifeEnd);
543 }
544 return true;
545 };
546
547 // Look up allocas in the original function in CodeExtractorAnalysisCache, as
548 // this is much faster than walking all the instructions.
549 for (AllocaInst *AI : CEAC.getAllocas()) {
550 BasicBlock *BB = AI->getParent();
551 if (Blocks.count(key: BB))
552 continue;
553
554 // As a prior call to extractCodeRegion() may have shrinkwrapped the alloca,
555 // check whether it is actually still in the original function.
556 Function *AIFunc = BB->getParent();
557 if (AIFunc != Func)
558 continue;
559
560 LifetimeMarkerInfo MarkerInfo = getLifetimeMarkers(CEAC, Addr: AI, ExitBlock);
561 bool Moved = moveOrIgnoreLifetimeMarkers(MarkerInfo);
562 if (Moved) {
563 LLVM_DEBUG(dbgs() << "Sinking alloca: " << *AI << "\n");
564 SinkCands.insert(X: AI);
565 continue;
566 }
567
568 // Find bitcasts in the outlined region that have lifetime marker users
569 // outside that region. Replace the lifetime marker use with an
570 // outside region bitcast to avoid unnecessary alloca/reload instructions
571 // and extra lifetime markers.
572 SmallVector<Instruction *, 2> LifetimeBitcastUsers;
573 for (User *U : AI->users()) {
574 if (!definedInRegion(Blocks, V: U))
575 continue;
576
577 if (U->stripInBoundsConstantOffsets() != AI)
578 continue;
579
580 Instruction *Bitcast = cast<Instruction>(Val: U);
581 for (User *BU : Bitcast->users()) {
582 auto *IntrInst = dyn_cast<LifetimeIntrinsic>(Val: BU);
583 if (!IntrInst)
584 continue;
585
586 if (definedInRegion(Blocks, V: IntrInst))
587 continue;
588
589 LLVM_DEBUG(dbgs() << "Replace use of extracted region bitcast"
590 << *Bitcast << " in out-of-region lifetime marker "
591 << *IntrInst << "\n");
592 LifetimeBitcastUsers.push_back(Elt: IntrInst);
593 }
594 }
595
596 for (Instruction *I : LifetimeBitcastUsers) {
597 Module *M = AIFunc->getParent();
598 LLVMContext &Ctx = M->getContext();
599 auto *Int8PtrTy = PointerType::getUnqual(C&: Ctx);
600 CastInst *CastI =
601 CastInst::CreatePointerCast(S: AI, Ty: Int8PtrTy, Name: "lt.cast", InsertBefore: I->getIterator());
602 I->replaceUsesOfWith(From: I->getOperand(i: 1), To: CastI);
603 }
604
605 // Follow any bitcasts.
606 SmallVector<Instruction *, 2> Bitcasts;
607 SmallVector<LifetimeMarkerInfo, 2> BitcastLifetimeInfo;
608 for (User *U : AI->users()) {
609 if (U->stripInBoundsConstantOffsets() == AI) {
610 Instruction *Bitcast = cast<Instruction>(Val: U);
611 LifetimeMarkerInfo LMI = getLifetimeMarkers(CEAC, Addr: Bitcast, ExitBlock);
612 if (LMI.LifeStart) {
613 Bitcasts.push_back(Elt: Bitcast);
614 BitcastLifetimeInfo.push_back(Elt: LMI);
615 continue;
616 }
617 }
618
619 // Found unknown use of AI.
620 if (!definedInRegion(Blocks, V: U)) {
621 Bitcasts.clear();
622 break;
623 }
624 }
625
626 // Either no bitcasts reference the alloca or there are unknown uses.
627 if (Bitcasts.empty())
628 continue;
629
630 LLVM_DEBUG(dbgs() << "Sinking alloca (via bitcast): " << *AI << "\n");
631 SinkCands.insert(X: AI);
632 for (unsigned I = 0, E = Bitcasts.size(); I != E; ++I) {
633 Instruction *BitcastAddr = Bitcasts[I];
634 const LifetimeMarkerInfo &LMI = BitcastLifetimeInfo[I];
635 assert(LMI.LifeStart &&
636 "Unsafe to sink bitcast without lifetime markers");
637 moveOrIgnoreLifetimeMarkers(LMI);
638 if (!definedInRegion(Blocks, V: BitcastAddr)) {
639 LLVM_DEBUG(dbgs() << "Sinking bitcast-of-alloca: " << *BitcastAddr
640 << "\n");
641 SinkCands.insert(X: BitcastAddr);
642 }
643 }
644 }
645}
646
647bool CodeExtractor::isEligible() const {
648 if (Blocks.empty())
649 return false;
650 BasicBlock *Header = *Blocks.begin();
651 Function *F = Header->getParent();
652
653 // For functions with varargs, check that varargs handling is only done in the
654 // outlined function, i.e vastart and vaend are only used in outlined blocks.
655 if (AllowVarArgs && F->getFunctionType()->isVarArg()) {
656 auto containsVarArgIntrinsic = [](const Instruction &I) {
657 if (const CallInst *CI = dyn_cast<CallInst>(Val: &I))
658 if (const Function *Callee = CI->getCalledFunction())
659 return Callee->getIntrinsicID() == Intrinsic::vastart ||
660 Callee->getIntrinsicID() == Intrinsic::vaend;
661 return false;
662 };
663
664 for (auto &BB : *F) {
665 if (Blocks.count(key: &BB))
666 continue;
667 if (llvm::any_of(Range&: BB, P: containsVarArgIntrinsic))
668 return false;
669 }
670 }
671 // stacksave as input implies stackrestore in the outlined function.
672 // This can confuse prolog epilog insertion phase.
673 // stacksave's uses must not cross outlined function.
674 for (BasicBlock *BB : Blocks) {
675 for (Instruction &I : *BB) {
676 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: &I);
677 if (!II)
678 continue;
679 bool IsSave = II->getIntrinsicID() == Intrinsic::stacksave;
680 bool IsRestore = II->getIntrinsicID() == Intrinsic::stackrestore;
681 if (IsSave && any_of(Range: II->users(), P: [&Blks = this->Blocks](User *U) {
682 return !definedInRegion(Blocks: Blks, V: U);
683 }))
684 return false;
685 if (IsRestore && !definedInRegion(Blocks, V: II->getArgOperand(i: 0)))
686 return false;
687 }
688 }
689 return true;
690}
691
692void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
693 const ValueSet &SinkCands,
694 bool CollectGlobalInputs) {
695 for (BasicBlock *BB : Blocks) {
696 // If a used value is defined outside the region, it's an input. If an
697 // instruction is used outside the region, it's an output.
698 for (Instruction &II : *BB) {
699 for (auto &OI : II.operands()) {
700 Value *V = OI;
701 if (!SinkCands.count(key: V) &&
702 (definedInCaller(Blocks, V) ||
703 (CollectGlobalInputs && llvm::isa<llvm::GlobalVariable>(Val: V))))
704 Inputs.insert(X: V);
705 }
706
707 for (User *U : II.users())
708 if (!definedInRegion(Blocks, V: U)) {
709 Outputs.insert(X: &II);
710 break;
711 }
712 }
713 }
714
715 // Reset stale state from any prior call in HotColdSplitting; the CFG may
716 // have changed since.
717 FuncRetVal = nullptr;
718 if (!VoidReturnWithSingleOutput && !AggregateArgs && Outputs.size() == 1 &&
719 getCommonExitBlock(Blocks)) {
720 FuncRetVal = Outputs[0];
721 Outputs.clear();
722 }
723}
724
725/// severSplitPHINodesOfEntry - If a PHI node has multiple inputs from outside
726/// of the region, we need to split the entry block of the region so that the
727/// PHI node is easier to deal with.
728void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) {
729 unsigned NumPredsFromRegion = 0;
730 unsigned NumPredsOutsideRegion = 0;
731
732 if (Header != &Header->getParent()->getEntryBlock()) {
733 PHINode *PN = dyn_cast<PHINode>(Val: Header->begin());
734 if (!PN) return; // No PHI nodes.
735
736 // If the header node contains any PHI nodes, check to see if there is more
737 // than one entry from outside the region. If so, we need to sever the
738 // header block into two.
739 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
740 if (Blocks.count(key: PN->getIncomingBlock(i)))
741 ++NumPredsFromRegion;
742 else
743 ++NumPredsOutsideRegion;
744
745 // If there is one (or fewer) predecessor from outside the region, we don't
746 // need to do anything special.
747 if (NumPredsOutsideRegion <= 1) return;
748 }
749
750 // Otherwise, we need to split the header block into two pieces: one
751 // containing PHI nodes merging values from outside of the region, and a
752 // second that contains all of the code for the block and merges back any
753 // incoming values from inside of the region.
754 BasicBlock *NewBB = SplitBlock(Old: Header, SplitPt: Header->getFirstNonPHIIt(), DT);
755
756 // We only want to code extract the second block now, and it becomes the new
757 // header of the region.
758 BasicBlock *OldPred = Header;
759 Blocks.remove(X: OldPred);
760 Blocks.insert(X: NewBB);
761 Header = NewBB;
762
763 // Okay, now we need to adjust the PHI nodes and any branches from within the
764 // region to go to the new header block instead of the old header block.
765 if (NumPredsFromRegion) {
766 PHINode *PN = cast<PHINode>(Val: OldPred->begin());
767 // Loop over all of the predecessors of OldPred that are in the region,
768 // changing them to branch to NewBB instead.
769 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
770 if (Blocks.count(key: PN->getIncomingBlock(i))) {
771 Instruction *TI = PN->getIncomingBlock(i)->getTerminator();
772 TI->replaceUsesOfWith(From: OldPred, To: NewBB);
773 }
774
775 // Okay, everything within the region is now branching to the right block, we
776 // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
777 BasicBlock::iterator AfterPHIs;
778 for (AfterPHIs = OldPred->begin(); isa<PHINode>(Val: AfterPHIs); ++AfterPHIs) {
779 PHINode *PN = cast<PHINode>(Val&: AfterPHIs);
780 // Create a new PHI node in the new region, which has an incoming value
781 // from OldPred of PN.
782 PHINode *NewPN = PHINode::Create(Ty: PN->getType(), NumReservedValues: 1 + NumPredsFromRegion,
783 NameStr: PN->getName() + ".ce");
784 NewPN->insertBefore(InsertPos: NewBB->begin());
785 PN->replaceAllUsesWith(V: NewPN);
786 NewPN->addIncoming(V: PN, BB: OldPred);
787
788 // Loop over all of the incoming value in PN, moving them to NewPN if they
789 // are from the extracted region.
790 PN->removeIncomingValueIf(Predicate: [&](unsigned i) {
791 if (Blocks.count(key: PN->getIncomingBlock(i))) {
792 NewPN->addIncoming(V: PN->getIncomingValue(i), BB: PN->getIncomingBlock(i));
793 return true;
794 }
795 return false;
796 });
797 }
798 }
799}
800
801/// severSplitPHINodesOfExits - if PHI nodes in exit blocks have inputs from
802/// outlined region, we split these PHIs on two: one with inputs from region
803/// and other with remaining incoming blocks; then first PHIs are placed in
804/// outlined region.
805void CodeExtractor::severSplitPHINodesOfExits() {
806 for (BasicBlock *ExitBB : ExtractedFuncRetVals) {
807 BasicBlock *NewBB = nullptr;
808
809 for (PHINode &PN : ExitBB->phis()) {
810 // Find all incoming values from the outlining region.
811 SmallVector<unsigned, 2> IncomingVals;
812 for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i)
813 if (Blocks.count(key: PN.getIncomingBlock(i)))
814 IncomingVals.push_back(Elt: i);
815
816 // Do not process PHI if there is one (or fewer) predecessor from region.
817 // If PHI has exactly one predecessor from region, only this one incoming
818 // will be replaced on codeRepl block, so it should be safe to skip PHI.
819 if (IncomingVals.size() <= 1)
820 continue;
821
822 // Create block for new PHIs and add it to the list of outlined if it
823 // wasn't done before.
824 if (!NewBB) {
825 NewBB = BasicBlock::Create(Context&: ExitBB->getContext(),
826 Name: ExitBB->getName() + ".split",
827 Parent: ExitBB->getParent(), InsertBefore: ExitBB);
828 SmallVector<BasicBlock *, 4> Preds(predecessors(BB: ExitBB));
829 for (BasicBlock *PredBB : Preds)
830 if (Blocks.count(key: PredBB))
831 PredBB->getTerminator()->replaceUsesOfWith(From: ExitBB, To: NewBB);
832 UncondBrInst::Create(Target: ExitBB, InsertBefore: NewBB);
833 Blocks.insert(X: NewBB);
834 }
835
836 // Split this PHI.
837 PHINode *NewPN = PHINode::Create(Ty: PN.getType(), NumReservedValues: IncomingVals.size(),
838 NameStr: PN.getName() + ".ce");
839 NewPN->insertBefore(InsertPos: NewBB->getFirstNonPHIIt());
840 for (unsigned i : IncomingVals)
841 NewPN->addIncoming(V: PN.getIncomingValue(i), BB: PN.getIncomingBlock(i));
842 for (unsigned i : reverse(C&: IncomingVals))
843 PN.removeIncomingValue(Idx: i, DeletePHIIfEmpty: false);
844 PN.addIncoming(V: NewPN, BB: NewBB);
845 }
846 }
847}
848
849void CodeExtractor::splitReturnBlocks() {
850 for (BasicBlock *Block : Blocks)
851 if (ReturnInst *RI = dyn_cast<ReturnInst>(Val: Block->getTerminator())) {
852 BasicBlock *New =
853 Block->splitBasicBlock(I: RI->getIterator(), BBName: Block->getName() + ".ret");
854 if (DT) {
855 // Old dominates New. New node dominates all other nodes dominated
856 // by Old.
857 DomTreeNode *OldNode = DT->getNode(BB: Block);
858 SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
859 OldNode->end());
860
861 DomTreeNode *NewNode = DT->addNewBlock(BB: New, DomBB: Block);
862
863 for (DomTreeNode *I : Children)
864 DT->changeImmediateDominator(N: I, NewIDom: NewNode);
865 }
866 }
867}
868
869Function *CodeExtractor::constructFunctionDeclaration(
870 const ValueSet &inputs, const ValueSet &outputs, BlockFrequency EntryFreq,
871 const Twine &Name, ValueSet &StructValues, StructType *&StructTy) {
872 LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
873 LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
874
875 Function *oldFunction = Blocks.front()->getParent();
876 Module *M = Blocks.front()->getModule();
877
878 // Assemble the function's parameter lists.
879 std::vector<Type *> ParamTy;
880 std::vector<Type *> AggParamTy;
881 const DataLayout &DL = M->getDataLayout();
882
883 // Add the types of the input values to the function's argument list
884 for (Value *value : inputs) {
885 LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n");
886 if (AggregateArgs && !ExcludeArgsFromAggregate.contains(key: value)) {
887 AggParamTy.push_back(x: value->getType());
888 StructValues.insert(X: value);
889 } else
890 ParamTy.push_back(x: value->getType());
891 }
892
893 // Add the types of the output values to the function's argument list.
894 for (Value *output : outputs) {
895 LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n");
896 if (AggregateArgs && !ExcludeArgsFromAggregate.contains(key: output)) {
897 AggParamTy.push_back(x: output->getType());
898 StructValues.insert(X: output);
899 } else
900 ParamTy.push_back(
901 x: PointerType::get(C&: output->getContext(), AddressSpace: DL.getAllocaAddrSpace()));
902 }
903
904 assert(
905 (ParamTy.size() + AggParamTy.size()) ==
906 (inputs.size() + outputs.size()) &&
907 "Number of scalar and aggregate params does not match inputs, outputs");
908 assert((StructValues.empty() || AggregateArgs) &&
909 "Expeced StructValues only with AggregateArgs set");
910
911 // Concatenate scalar and aggregate params in ParamTy.
912 if (!AggParamTy.empty()) {
913 StructTy = StructType::get(Context&: M->getContext(), Elements: AggParamTy);
914 ParamTy.push_back(x: PointerType::get(
915 C&: M->getContext(), AddressSpace: ArgsInZeroAddressSpace ? 0 : DL.getAllocaAddrSpace()));
916 }
917
918 Type *RetTy = FuncRetVal ? FuncRetVal->getType() : getSwitchType();
919 LLVM_DEBUG({
920 dbgs() << "Function type: " << *RetTy << " f(";
921 for (Type *i : ParamTy)
922 dbgs() << *i << ", ";
923 dbgs() << ")\n";
924 });
925
926 FunctionType *funcType = FunctionType::get(
927 Result: RetTy, Params: ParamTy, isVarArg: AllowVarArgs && oldFunction->isVarArg());
928
929 // Create the new function
930 Function *newFunction =
931 Function::Create(Ty: funcType, Linkage: GlobalValue::InternalLinkage,
932 AddrSpace: oldFunction->getAddressSpace(), N: Name, M);
933
934 // Propagate personality info to the new function if there is one.
935 if (oldFunction->hasPersonalityFn())
936 newFunction->setPersonalityFn(oldFunction->getPersonalityFn());
937
938 // Inherit all of the target dependent attributes and white-listed
939 // target independent attributes.
940 // (e.g. If the extracted region contains a call to an x86.sse
941 // instruction we need to make sure that the extracted region has the
942 // "target-features" attribute allowing it to be lowered.
943 // FIXME: This should be changed to check to see if a specific
944 // attribute can not be inherited.
945 for (const auto &Attr : oldFunction->getAttributes().getFnAttrs()) {
946 if (Attr.isStringAttribute()) {
947 if (Attr.getKindAsString() == "thunk")
948 continue;
949 } else
950 switch (Attr.getKindAsEnum()) {
951 // Those attributes cannot be propagated safely. Explicitly list them
952 // here so we get a warning if new attributes are added.
953 case Attribute::AllocSize:
954 case Attribute::Builtin:
955 case Attribute::Convergent:
956 case Attribute::JumpTable:
957 case Attribute::Naked:
958 case Attribute::NoBuiltin:
959 case Attribute::NoMerge:
960 case Attribute::NoReturn:
961 case Attribute::NoSync:
962 case Attribute::ReturnsTwice:
963 case Attribute::Speculatable:
964 case Attribute::StackAlignment:
965 case Attribute::WillReturn:
966 case Attribute::AllocKind:
967 case Attribute::PresplitCoroutine:
968 case Attribute::Memory:
969 case Attribute::NoFPClass:
970 case Attribute::CoroDestroyOnlyWhenComplete:
971 case Attribute::CoroElideSafe:
972 case Attribute::NoDivergenceSource:
973 case Attribute::NoCreateUndefOrPoison:
974 continue;
975 // Those attributes should be safe to propagate to the extracted function.
976 case Attribute::AlwaysInline:
977 case Attribute::Cold:
978 case Attribute::DisableSanitizerInstrumentation:
979 case Attribute::Flatten:
980 case Attribute::FnRetThunkExtern:
981 case Attribute::Hot:
982 case Attribute::HybridPatchable:
983 case Attribute::NoRecurse:
984 case Attribute::InlineHint:
985 case Attribute::MinSize:
986 case Attribute::NoCallback:
987 case Attribute::NoDuplicate:
988 case Attribute::NoFree:
989 case Attribute::NoImplicitFloat:
990 case Attribute::NoInline:
991 case Attribute::NoIPA:
992 case Attribute::NoOutline:
993 case Attribute::NonLazyBind:
994 case Attribute::NoRedZone:
995 case Attribute::NoUnwind:
996 case Attribute::NoSanitizeBounds:
997 case Attribute::NoSanitizeCoverage:
998 case Attribute::NullPointerIsValid:
999 case Attribute::OptimizeForDebugging:
1000 case Attribute::OptForFuzzing:
1001 case Attribute::OptimizeNone:
1002 case Attribute::OptimizeForSize:
1003 case Attribute::SafeStack:
1004 case Attribute::ShadowCallStack:
1005 case Attribute::SanitizeAddress:
1006 case Attribute::SanitizeMemory:
1007 case Attribute::SanitizeNumericalStability:
1008 case Attribute::SanitizeThread:
1009 case Attribute::SanitizeType:
1010 case Attribute::SanitizeHWAddress:
1011 case Attribute::SanitizeMemTag:
1012 case Attribute::SanitizeRealtime:
1013 case Attribute::SanitizeRealtimeBlocking:
1014 case Attribute::SanitizeAllocToken:
1015 case Attribute::SpeculativeLoadHardening:
1016 case Attribute::StackProtect:
1017 case Attribute::StackProtectReq:
1018 case Attribute::StackProtectStrong:
1019 case Attribute::StrictFP:
1020 case Attribute::UWTable:
1021 case Attribute::VScaleRange:
1022 case Attribute::NoCfCheck:
1023 case Attribute::MustProgress:
1024 case Attribute::NoProfile:
1025 case Attribute::SkipProfile:
1026 case Attribute::DenormalFPEnv:
1027 break;
1028 // These attributes cannot be applied to functions.
1029 case Attribute::Alignment:
1030 case Attribute::AllocatedPointer:
1031 case Attribute::AllocAlign:
1032 case Attribute::ByVal:
1033 case Attribute::Captures:
1034 case Attribute::Dereferenceable:
1035 case Attribute::DereferenceableOrNull:
1036 case Attribute::ElementType:
1037 case Attribute::InAlloca:
1038 case Attribute::InReg:
1039 case Attribute::Nest:
1040 case Attribute::NoAlias:
1041 case Attribute::NoUndef:
1042 case Attribute::NonNull:
1043 case Attribute::Preallocated:
1044 case Attribute::ReadNone:
1045 case Attribute::ReadOnly:
1046 case Attribute::Returned:
1047 case Attribute::SExt:
1048 case Attribute::StructRet:
1049 case Attribute::SwiftError:
1050 case Attribute::SwiftSelf:
1051 case Attribute::SwiftAsync:
1052 case Attribute::ZExt:
1053 case Attribute::ImmArg:
1054 case Attribute::ByRef:
1055 case Attribute::WriteOnly:
1056 case Attribute::Writable:
1057 case Attribute::DeadOnUnwind:
1058 case Attribute::Range:
1059 case Attribute::Initializes:
1060 case Attribute::NoExt:
1061 case Attribute::NoFreeObj:
1062 // These are not really attributes.
1063 case Attribute::None:
1064 case Attribute::EndAttrKinds:
1065 case Attribute::EmptyKey:
1066 case Attribute::TombstoneKey:
1067 case Attribute::DeadOnReturn:
1068 llvm_unreachable("Not a function attribute");
1069 }
1070
1071 newFunction->addFnAttr(Attr);
1072 }
1073
1074 // Create scalar and aggregate iterators to name all of the arguments we
1075 // inserted.
1076 Function::arg_iterator ScalarAI = newFunction->arg_begin();
1077
1078 // Set names and attributes for input and output arguments.
1079 ScalarAI = newFunction->arg_begin();
1080 for (Value *input : inputs) {
1081 if (StructValues.contains(key: input))
1082 continue;
1083
1084 ScalarAI->setName(input->getName());
1085 if (input->isSwiftError())
1086 newFunction->addParamAttr(ArgNo: ScalarAI - newFunction->arg_begin(),
1087 Kind: Attribute::SwiftError);
1088 ++ScalarAI;
1089 }
1090 for (Value *output : outputs) {
1091 if (StructValues.contains(key: output))
1092 continue;
1093
1094 ScalarAI->setName(output->getName() + ".out");
1095 ++ScalarAI;
1096 }
1097
1098 // Update the entry count of the function.
1099 if (BFI) {
1100 auto Count = BFI->getProfileCountFromFreq(Freq: EntryFreq);
1101 if (Count.has_value())
1102 newFunction->setEntryCount(Count: *Count);
1103 }
1104
1105 return newFunction;
1106}
1107
1108/// If the original function has debug info, we have to add a debug location
1109/// to the new branch instruction from the artificial entry block.
1110/// We use the debug location of the first instruction in the extracted
1111/// blocks, as there is no other equivalent line in the source code.
1112static void applyFirstDebugLoc(Function *oldFunction,
1113 ArrayRef<BasicBlock *> Blocks,
1114 Instruction *BranchI) {
1115 if (oldFunction->getSubprogram()) {
1116 any_of(Range&: Blocks, P: [&BranchI](const BasicBlock *BB) {
1117 return any_of(Range: *BB, P: [&BranchI](const Instruction &I) {
1118 if (!I.getDebugLoc())
1119 return false;
1120 BranchI->setDebugLoc(I.getDebugLoc());
1121 return true;
1122 });
1123 });
1124 }
1125}
1126
1127/// Erase lifetime.start markers which reference inputs to the extraction
1128/// region, and insert the referenced memory into \p LifetimesStart.
1129///
1130/// The extraction region is defined by a set of blocks (\p Blocks), and a set
1131/// of allocas which will be moved from the caller function into the extracted
1132/// function (\p SunkAllocas).
1133static void eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock *> &Blocks,
1134 const SetVector<Value *> &SunkAllocas,
1135 SetVector<Value *> &LifetimesStart) {
1136 for (BasicBlock *BB : Blocks) {
1137 for (Instruction &I : llvm::make_early_inc_range(Range&: *BB)) {
1138 auto *II = dyn_cast<LifetimeIntrinsic>(Val: &I);
1139 if (!II)
1140 continue;
1141
1142 // Get the memory operand of the lifetime marker. If the underlying
1143 // object is a sunk alloca, or is otherwise defined in the extraction
1144 // region, the lifetime marker must not be erased.
1145 Value *Mem = II->getOperand(i_nocapture: 0);
1146 if (SunkAllocas.count(key: Mem) || definedInRegion(Blocks, V: Mem))
1147 continue;
1148
1149 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1150 LifetimesStart.insert(X: Mem);
1151 II->eraseFromParent();
1152 }
1153 }
1154}
1155
1156/// Insert lifetime start/end markers surrounding the call to the new function
1157/// for objects defined in the caller.
1158static void insertLifetimeMarkersSurroundingCall(
1159 Module *M, ArrayRef<Value *> LifetimesStart, ArrayRef<Value *> LifetimesEnd,
1160 CallInst *TheCall) {
1161 Instruction *Term = TheCall->getParent()->getTerminator();
1162
1163 // Emit lifetime markers for the pointers given in \p Objects. Insert the
1164 // markers before the call if \p InsertBefore, and after the call otherwise.
1165 auto insertMarkers = [&](Intrinsic::ID MarkerFunc, ArrayRef<Value *> Objects,
1166 bool InsertBefore) {
1167 for (Value *Mem : Objects) {
1168 assert((!isa<Instruction>(Mem) || cast<Instruction>(Mem)->getFunction() ==
1169 TheCall->getFunction()) &&
1170 "Input memory not defined in original function");
1171
1172 Function *Func =
1173 Intrinsic::getOrInsertDeclaration(M, id: MarkerFunc, OverloadTys: Mem->getType());
1174 auto Marker = CallInst::Create(Func, Args: Mem);
1175 if (InsertBefore)
1176 Marker->insertBefore(InsertPos: TheCall->getIterator());
1177 else
1178 Marker->insertBefore(InsertPos: Term->getIterator());
1179 }
1180 };
1181
1182 if (!LifetimesStart.empty()) {
1183 insertMarkers(Intrinsic::lifetime_start, LifetimesStart,
1184 /*InsertBefore=*/true);
1185 }
1186
1187 if (!LifetimesEnd.empty()) {
1188 insertMarkers(Intrinsic::lifetime_end, LifetimesEnd,
1189 /*InsertBefore=*/false);
1190 }
1191}
1192
1193void CodeExtractor::moveCodeToFunction(Function *newFunction) {
1194 auto newFuncIt = newFunction->begin();
1195 for (BasicBlock *Block : Blocks) {
1196 // Delete the basic block from the old function, and the list of blocks
1197 Block->removeFromParent();
1198
1199 // Insert this basic block into the new function
1200 // Insert the original blocks after the entry block created
1201 // for the new function. The entry block may be followed
1202 // by a set of exit blocks at this point, but these exit
1203 // blocks better be placed at the end of the new function.
1204 newFuncIt = newFunction->insert(Position: std::next(x: newFuncIt), BB: Block);
1205 }
1206}
1207
1208void CodeExtractor::calculateNewCallTerminatorWeights(
1209 BasicBlock *CodeReplacer,
1210 const DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
1211 BranchProbabilityInfo *BPI) {
1212 using Distribution = BlockFrequencyInfoImplBase::Distribution;
1213 using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
1214
1215 // Update the branch weights for the exit block.
1216 Instruction *TI = CodeReplacer->getTerminator();
1217 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
1218
1219 // Block Frequency distribution with dummy node.
1220 Distribution BranchDist;
1221
1222 SmallVector<BranchProbability, 4> EdgeProbabilities(
1223 TI->getNumSuccessors(), BranchProbability::getUnknown());
1224
1225 // Add each of the frequencies of the successors.
1226 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
1227 BlockNode ExitNode(i);
1228 uint64_t ExitFreq = ExitWeights.lookup(Val: TI->getSuccessor(Idx: i)).getFrequency();
1229 if (ExitFreq != 0)
1230 BranchDist.addExit(Node: ExitNode, Amount: ExitFreq);
1231 else
1232 EdgeProbabilities[i] = BranchProbability::getZero();
1233 }
1234
1235 // Check for no total weight.
1236 if (BranchDist.Total == 0) {
1237 BPI->setEdgeProbability(Src: CodeReplacer, Probs: EdgeProbabilities);
1238 return;
1239 }
1240
1241 // Normalize the distribution so that they can fit in unsigned.
1242 BranchDist.normalize();
1243
1244 // Create normalized branch weights and set the metadata.
1245 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
1246 const auto &Weight = BranchDist.Weights[I];
1247
1248 // Get the weight and update the current BFI.
1249 BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
1250 BranchProbability BP(Weight.Amount, BranchDist.Total);
1251 EdgeProbabilities[Weight.TargetNode.Index] = BP;
1252 }
1253 BPI->setEdgeProbability(Src: CodeReplacer, Probs: EdgeProbabilities);
1254 TI->setMetadata(
1255 KindID: LLVMContext::MD_prof,
1256 Node: MDBuilder(TI->getContext()).createBranchWeights(Weights: BranchWeights));
1257}
1258
1259/// Erase debug info intrinsics which refer to values in \p F but aren't in
1260/// \p F.
1261static void eraseDebugIntrinsicsWithNonLocalRefs(Function &F) {
1262 for (Instruction &I : instructions(F)) {
1263 SmallVector<DbgVariableRecord *, 4> DbgVariableRecords;
1264 findDbgUsers(V: &I, DbgVariableRecords);
1265 for (DbgVariableRecord *DVR : DbgVariableRecords)
1266 if (DVR->getFunction() != &F)
1267 DVR->eraseFromParent();
1268 }
1269}
1270
1271/// Fix up the debug info in the old and new functions. Following changes are
1272/// done.
1273/// 1. If a debug record points to a value that has been replaced, update the
1274/// record to use the new value.
1275/// 2. If an Input value that has been replaced was used as a location of a
1276/// debug record in the Parent function, then materealize a similar record in
1277/// the new function.
1278/// 3. Point line locations and debug intrinsics to the new subprogram scope
1279/// 4. Remove intrinsics which point to values outside of the new function.
1280static void fixupDebugInfoPostExtraction(Function &OldFunc, Function &NewFunc,
1281 CallInst &TheCall,
1282 const SetVector<Value *> &Inputs,
1283 ArrayRef<Value *> NewValues) {
1284 DISubprogram *OldSP = OldFunc.getSubprogram();
1285 LLVMContext &Ctx = OldFunc.getContext();
1286
1287 if (!OldSP) {
1288 // Erase any debug info the new function contains.
1289 stripDebugInfo(F&: NewFunc);
1290 // Make sure the old function doesn't contain any non-local metadata refs.
1291 eraseDebugIntrinsicsWithNonLocalRefs(F&: NewFunc);
1292 return;
1293 }
1294
1295 // Create a subprogram for the new function. Leave out a description of the
1296 // function arguments, as the parameters don't correspond to anything at the
1297 // source level.
1298 assert(OldSP->getUnit() && "Missing compile unit for subprogram");
1299 DIBuilder DIB(*OldFunc.getParent(), /*AllowUnresolved=*/false,
1300 OldSP->getUnit());
1301 auto SPType = DIB.createSubroutineType(ParameterTypes: DIB.getOrCreateTypeArray(Elements: {}));
1302 DISubprogram::DISPFlags SPFlags = DISubprogram::SPFlagDefinition |
1303 DISubprogram::SPFlagOptimized |
1304 DISubprogram::SPFlagLocalToUnit;
1305 auto NewSP = DIB.createFunction(
1306 Scope: OldSP->getUnit(), Name: NewFunc.getName(), LinkageName: NewFunc.getName(), File: OldSP->getFile(),
1307 /*LineNo=*/0, Ty: SPType, /*ScopeLine=*/0, Flags: DINode::FlagZero, SPFlags);
1308 NewFunc.setSubprogram(NewSP);
1309
1310 auto UpdateOrInsertDebugRecord = [&](auto *DR, Value *OldLoc, Value *NewLoc,
1311 DIExpression *Expr, bool Declare) {
1312 if (DR->getParent()->getParent() == &NewFunc) {
1313 DR->replaceVariableLocationOp(OldLoc, NewLoc);
1314 return;
1315 }
1316 if (Declare) {
1317 DIB.insertDeclare(NewLoc, DR->getVariable(), Expr, DR->getDebugLoc(),
1318 &NewFunc.getEntryBlock());
1319 return;
1320 }
1321 DIB.insertDbgValue(Val: NewLoc, VarInfo: DR->getVariable(), Expr, DL: DR->getDebugLoc(),
1322 InsertPt: NewFunc.getEntryBlock().getTerminator()->getIterator());
1323 };
1324 for (auto [Input, NewVal] : zip_equal(t: Inputs, u&: NewValues)) {
1325 SmallVector<DbgVariableRecord *, 1> DPUsers;
1326 findDbgUsers(V: Input, DbgVariableRecords&: DPUsers);
1327 DIExpression *Expr = DIB.createExpression();
1328
1329 // Iterate the debud users of the Input values. If they are in the extracted
1330 // function then update their location with the new value. If they are in
1331 // the parent function then create a similar debug record.
1332 for (auto *DVR : DPUsers)
1333 UpdateOrInsertDebugRecord(DVR, Input, NewVal, Expr, DVR->isDbgDeclare());
1334 }
1335
1336 auto IsInvalidLocation = [&NewFunc](Value *Location) {
1337 // Location is invalid if it isn't a constant, an instruction or an
1338 // argument, or is an instruction/argument but isn't in the new function.
1339 if (!Location || (!isa<Constant>(Val: Location) && !isa<Argument>(Val: Location) &&
1340 !isa<Instruction>(Val: Location)))
1341 return true;
1342
1343 if (Argument *Arg = dyn_cast<Argument>(Val: Location))
1344 return Arg->getParent() != &NewFunc;
1345 if (Instruction *LocationInst = dyn_cast<Instruction>(Val: Location))
1346 return LocationInst->getFunction() != &NewFunc;
1347 return false;
1348 };
1349
1350 // Debug intrinsics in the new function need to be updated in one of two
1351 // ways:
1352 // 1) They need to be deleted, because they describe a value in the old
1353 // function.
1354 // 2) They need to point to fresh metadata, e.g. because they currently
1355 // point to a variable in the wrong scope.
1356 SmallDenseMap<DINode *, DINode *> RemappedMetadata;
1357 SmallVector<DbgVariableRecord *, 4> DVRsToDelete;
1358 DenseMap<const MDNode *, MDNode *> Cache;
1359
1360 auto GetUpdatedDIVariable = [&](DILocalVariable *OldVar) {
1361 DINode *&NewVar = RemappedMetadata[OldVar];
1362 if (!NewVar) {
1363 DILocalScope *NewScope = DILocalScope::cloneScopeForSubprogram(
1364 RootScope&: *OldVar->getScope(), NewSP&: *NewSP, Ctx, Cache);
1365 NewVar = DIB.createAutoVariable(
1366 Scope: NewScope, Name: OldVar->getName(), File: OldVar->getFile(), LineNo: OldVar->getLine(),
1367 Ty: OldVar->getType(), /*AlwaysPreserve=*/false, Flags: DINode::FlagZero,
1368 AlignInBits: OldVar->getAlignInBits());
1369 }
1370 return cast<DILocalVariable>(Val: NewVar);
1371 };
1372
1373 auto UpdateDbgLabel = [&](auto *LabelRecord) {
1374 // Point the label record to a fresh label within the new function if
1375 // the record was not inlined from some other function.
1376 if (LabelRecord->getDebugLoc().getInlinedAt())
1377 return;
1378 DILabel *OldLabel = LabelRecord->getLabel();
1379 DINode *&NewLabel = RemappedMetadata[OldLabel];
1380 if (!NewLabel) {
1381 DILocalScope *NewScope = DILocalScope::cloneScopeForSubprogram(
1382 RootScope&: *OldLabel->getScope(), NewSP&: *NewSP, Ctx, Cache);
1383 NewLabel =
1384 DILabel::get(Context&: Ctx, Scope: NewScope, Name: OldLabel->getName(), File: OldLabel->getFile(),
1385 Line: OldLabel->getLine(), Column: OldLabel->getColumn(),
1386 IsArtificial: OldLabel->isArtificial(), CoroSuspendIdx: OldLabel->getCoroSuspendIdx());
1387 }
1388 LabelRecord->setLabel(cast<DILabel>(Val: NewLabel));
1389 };
1390
1391 auto UpdateDbgRecordsOnInst = [&](Instruction &I) -> void {
1392 for (DbgRecord &DR : I.getDbgRecordRange()) {
1393 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(Val: &DR)) {
1394 UpdateDbgLabel(DLR);
1395 continue;
1396 }
1397
1398 DbgVariableRecord &DVR = cast<DbgVariableRecord>(Val&: DR);
1399 // If any of the used locations are invalid, delete the record.
1400 if (any_of(Range: DVR.location_ops(), P: IsInvalidLocation)) {
1401 DVRsToDelete.push_back(Elt: &DVR);
1402 continue;
1403 }
1404
1405 // DbgAssign intrinsics have an extra Value argument:
1406 if (DVR.isDbgAssign() && IsInvalidLocation(DVR.getAddress())) {
1407 DVRsToDelete.push_back(Elt: &DVR);
1408 continue;
1409 }
1410
1411 // If the variable was in the scope of the old function, i.e. it was not
1412 // inlined, point the intrinsic to a fresh variable within the new
1413 // function.
1414 if (!DVR.getDebugLoc().getInlinedAt())
1415 DVR.setVariable(GetUpdatedDIVariable(DVR.getVariable()));
1416 }
1417 };
1418
1419 for (Instruction &I : instructions(F&: NewFunc))
1420 UpdateDbgRecordsOnInst(I);
1421
1422 for (auto *DVR : DVRsToDelete)
1423 DVR->getMarker()->MarkedInstr->dropOneDbgRecord(I: DVR);
1424 DIB.finalizeSubprogram(SP: NewSP);
1425
1426 // Fix up the scope information attached to the line locations and the
1427 // debug assignment metadata in the new function.
1428 DenseMap<DIAssignID *, DIAssignID *> AssignmentIDMap;
1429 for (Instruction &I : instructions(F&: NewFunc)) {
1430 if (const DebugLoc &DL = I.getDebugLoc())
1431 I.setDebugLoc(
1432 DebugLoc::replaceInlinedAtSubprogram(DL, NewSP&: *NewSP, Ctx, Cache));
1433 for (DbgRecord &DR : I.getDbgRecordRange())
1434 DR.setDebugLoc(DebugLoc::replaceInlinedAtSubprogram(DL: DR.getDebugLoc(),
1435 NewSP&: *NewSP, Ctx, Cache));
1436
1437 // Loop info metadata may contain line locations. Fix them up.
1438 auto updateLoopInfoLoc = [&Ctx, &Cache, NewSP](Metadata *MD) -> Metadata * {
1439 if (auto *Loc = dyn_cast_or_null<DILocation>(Val: MD))
1440 return DebugLoc::replaceInlinedAtSubprogram(DL: Loc, NewSP&: *NewSP, Ctx, Cache);
1441 return MD;
1442 };
1443 updateLoopMetadataDebugLocations(I, Updater: updateLoopInfoLoc);
1444 at::remapAssignID(Map&: AssignmentIDMap, I);
1445 }
1446 if (!TheCall.getDebugLoc())
1447 TheCall.setDebugLoc(DILocation::get(Context&: Ctx, Line: 0, Column: 0, Scope: OldSP));
1448
1449 eraseDebugIntrinsicsWithNonLocalRefs(F&: NewFunc);
1450}
1451
1452Function *
1453CodeExtractor::extractCodeRegion(const CodeExtractorAnalysisCache &CEAC) {
1454 ValueSet Inputs, Outputs;
1455 return extractCodeRegion(CEAC, Inputs, Outputs);
1456}
1457
1458Function *
1459CodeExtractor::extractCodeRegion(const CodeExtractorAnalysisCache &CEAC,
1460 ValueSet &inputs, ValueSet &outputs) {
1461 if (!isEligible())
1462 return nullptr;
1463
1464 // Assumption: this is a single-entry code region, and the header is the first
1465 // block in the region.
1466 BasicBlock *header = *Blocks.begin();
1467 Function *oldFunction = header->getParent();
1468
1469 normalizeCFGForExtraction(header);
1470
1471 // Remove @llvm.assume calls that will be moved to the new function from the
1472 // old function's assumption cache.
1473 for (BasicBlock *Block : Blocks) {
1474 for (Instruction &I : llvm::make_early_inc_range(Range&: *Block)) {
1475 if (auto *AI = dyn_cast<AssumeInst>(Val: &I)) {
1476 if (AC)
1477 AC->unregisterAssumption(CI: AI);
1478 AI->eraseFromParent();
1479 }
1480 }
1481 }
1482
1483 ValueSet SinkingCands, HoistingCands;
1484 BasicBlock *CommonExit = nullptr;
1485 findAllocas(CEAC, SinkCands&: SinkingCands, HoistCands&: HoistingCands, ExitBlock&: CommonExit);
1486 assert(HoistingCands.empty() || CommonExit);
1487
1488 // Find inputs to, outputs from the code region.
1489 findInputsOutputs(Inputs&: inputs, Outputs&: outputs, SinkCands: SinkingCands);
1490
1491 // Collect objects which are inputs to the extraction region and also
1492 // referenced by lifetime start markers within it. The effects of these
1493 // markers must be replicated in the calling function to prevent the stack
1494 // coloring pass from merging slots which store input objects.
1495 ValueSet LifetimesStart;
1496 eraseLifetimeMarkersOnInputs(Blocks, SunkAllocas: SinkingCands, LifetimesStart);
1497
1498 if (!HoistingCands.empty()) {
1499 auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExitBlock: CommonExit);
1500 Instruction *TI = HoistToBlock->getTerminator();
1501 for (auto *II : HoistingCands)
1502 cast<Instruction>(Val: II)->moveBefore(InsertPos: TI->getIterator());
1503 computeExtractedFuncRetVals();
1504 }
1505
1506 // CFG/ExitBlocks must not change hereafter
1507
1508 // Calculate the entry frequency of the new function before we change the root
1509 // block.
1510 BlockFrequency EntryFreq;
1511 DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
1512 if (BFI) {
1513 assert(BPI && "Both BPI and BFI are required to preserve profile info");
1514 for (BasicBlock *Pred : predecessors(BB: header)) {
1515 if (Blocks.count(key: Pred))
1516 continue;
1517 EntryFreq +=
1518 BFI->getBlockFreq(BB: Pred) * BPI->getEdgeProbability(Src: Pred, Dst: header);
1519 }
1520
1521 for (BasicBlock *Succ : ExtractedFuncRetVals) {
1522 for (BasicBlock *Block : predecessors(BB: Succ)) {
1523 if (!Blocks.count(key: Block))
1524 continue;
1525
1526 // Update the branch weight for this successor.
1527 BlockFrequency &BF = ExitWeights[Succ];
1528 BF += BFI->getBlockFreq(BB: Block) * BPI->getEdgeProbability(Src: Block, Dst: Succ);
1529 }
1530 }
1531 }
1532
1533 // Determine position for the replacement code. Do so before header is moved
1534 // to the new function.
1535 BasicBlock *ReplIP = header;
1536 while (ReplIP && Blocks.count(key: ReplIP))
1537 ReplIP = ReplIP->getNextNode();
1538
1539 // Construct new function based on inputs/outputs & add allocas for all defs.
1540 std::string SuffixToUse =
1541 Suffix.empty()
1542 ? (header->getName().empty() ? "extracted" : header->getName().str())
1543 : Suffix;
1544
1545 ValueSet StructValues;
1546 StructType *StructTy = nullptr;
1547 Function *newFunction = constructFunctionDeclaration(
1548 inputs, outputs, EntryFreq, Name: oldFunction->getName() + "." + SuffixToUse,
1549 StructValues, StructTy);
1550 SmallVector<Value *> NewValues;
1551
1552 emitFunctionBody(inputs, outputs, StructValues, newFunction, StructArgTy: StructTy, header,
1553 SinkingCands, NewValues);
1554
1555 std::vector<Value *> Reloads;
1556 CallInst *TheCall = emitReplacerCall(
1557 inputs, outputs, StructValues, newFunction, StructArgTy: StructTy, oldFunction, ReplIP,
1558 EntryFreq, LifetimesStart: LifetimesStart.getArrayRef(), Reloads);
1559
1560 insertReplacerCall(oldFunction, header, ReplacerCall: TheCall, outputs, Reloads,
1561 ExitWeights);
1562
1563 fixupDebugInfoPostExtraction(OldFunc&: *oldFunction, NewFunc&: *newFunction, TheCall&: *TheCall, Inputs: inputs,
1564 NewValues);
1565
1566 LLVM_DEBUG(llvm::dbgs() << "After extractCodeRegion - newFunction:\n");
1567 LLVM_DEBUG(newFunction->dump());
1568 LLVM_DEBUG(llvm::dbgs() << "After extractCodeRegion - oldFunction:\n");
1569 LLVM_DEBUG(oldFunction->dump());
1570 LLVM_DEBUG(if (AC && verifyAssumptionCache(*oldFunction, *newFunction, AC))
1571 report_fatal_error("Stale Asumption cache for old Function!"));
1572 return newFunction;
1573}
1574
1575void CodeExtractor::normalizeCFGForExtraction(BasicBlock *&header) {
1576 // If we have any return instructions in the region, split those blocks so
1577 // that the return is not in the region.
1578 splitReturnBlocks();
1579
1580 // If we have to split PHI nodes of the entry or exit blocks, do so now.
1581 severSplitPHINodesOfEntry(Header&: header);
1582
1583 // If a PHI in an exit block has multiple incoming values from the outlined
1584 // region, create a new PHI for those values within the region such that only
1585 // PHI itself becomes an output value, not each of its incoming values
1586 // individually.
1587 computeExtractedFuncRetVals();
1588 severSplitPHINodesOfExits();
1589}
1590
1591void CodeExtractor::computeExtractedFuncRetVals() {
1592 ExtractedFuncRetVals.clear();
1593
1594 SmallPtrSet<BasicBlock *, 2> ExitBlocks;
1595 for (BasicBlock *Block : Blocks) {
1596 for (BasicBlock *Succ : successors(BB: Block)) {
1597 if (Blocks.count(key: Succ))
1598 continue;
1599
1600 bool IsNew = ExitBlocks.insert(Ptr: Succ).second;
1601 if (IsNew)
1602 ExtractedFuncRetVals.push_back(Elt: Succ);
1603 }
1604 }
1605}
1606
1607Type *CodeExtractor::getSwitchType() {
1608 LLVMContext &Context = Blocks.front()->getContext();
1609
1610 assert(ExtractedFuncRetVals.size() < 0xffff &&
1611 "too many exit blocks for switch");
1612 switch (ExtractedFuncRetVals.size()) {
1613 case 0:
1614 case 1:
1615 return Type::getVoidTy(C&: Context);
1616 case 2:
1617 // Conditional branch, return a bool
1618 return Type::getInt1Ty(C&: Context);
1619 default:
1620 return Type::getInt16Ty(C&: Context);
1621 }
1622}
1623
1624void CodeExtractor::emitFunctionBody(
1625 const ValueSet &inputs, const ValueSet &outputs,
1626 const ValueSet &StructValues, Function *newFunction,
1627 StructType *StructArgTy, BasicBlock *header, const ValueSet &SinkingCands,
1628 SmallVectorImpl<Value *> &NewValues) {
1629 Function *oldFunction = header->getParent();
1630 LLVMContext &Context = oldFunction->getContext();
1631
1632 // The new function needs a root node because other nodes can branch to the
1633 // head of the region, but the entry node of a function cannot have preds.
1634 BasicBlock *newFuncRoot =
1635 BasicBlock::Create(Context, Name: "newFuncRoot", Parent: newFunction);
1636
1637 // Now sink all instructions which only have non-phi uses inside the region.
1638 // Group the allocas at the start of the block, so that any bitcast uses of
1639 // the allocas are well-defined.
1640 for (auto *II : SinkingCands) {
1641 if (!isa<AllocaInst>(Val: II)) {
1642 cast<Instruction>(Val: II)->moveBefore(BB&: *newFuncRoot,
1643 I: newFuncRoot->getFirstInsertionPt());
1644 }
1645 }
1646 for (auto *II : SinkingCands) {
1647 if (auto *AI = dyn_cast<AllocaInst>(Val: II)) {
1648 AI->moveBefore(BB&: *newFuncRoot, I: newFuncRoot->getFirstInsertionPt());
1649 }
1650 }
1651
1652 Function::arg_iterator ScalarAI = newFunction->arg_begin();
1653 Argument *AggArg = StructValues.empty()
1654 ? nullptr
1655 : newFunction->getArg(i: newFunction->arg_size() - 1);
1656
1657 // Rewrite all users of the inputs in the extracted region to use the
1658 // arguments (or appropriate addressing into struct) instead.
1659 for (unsigned i = 0, e = inputs.size(), aggIdx = 0; i != e; ++i) {
1660 Value *RewriteVal;
1661 if (StructValues.contains(key: inputs[i])) {
1662 Value *Idx[2];
1663 Idx[0] = Constant::getNullValue(Ty: Type::getInt32Ty(C&: header->getContext()));
1664 Idx[1] = ConstantInt::get(Ty: Type::getInt32Ty(C&: header->getContext()), V: aggIdx);
1665 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1666 PointeeType: StructArgTy, Ptr: AggArg, IdxList: Idx, NameStr: "gep_" + inputs[i]->getName(), InsertBefore: newFuncRoot);
1667 LoadInst *LoadGEP =
1668 new LoadInst(StructArgTy->getElementType(N: aggIdx), GEP,
1669 "loadgep_" + inputs[i]->getName(), newFuncRoot);
1670 // If we load pointer, we can add optional !align metadata
1671 // The existence of the !align metadata on the instruction tells
1672 // the optimizer that the value loaded is known to be aligned to
1673 // a boundary specified by the integer value in the metadata node.
1674 // Example:
1675 // %res = load ptr, ptr %input, align 8, !align !align_md_node
1676 // ^ ^
1677 // | |
1678 // alignment of %input address |
1679 // |
1680 // alignment of %res object
1681 if (StructArgTy->getElementType(N: aggIdx)->isPointerTy()) {
1682 unsigned AlignmentValue;
1683 const Triple &TargetTriple =
1684 newFunction->getParent()->getTargetTriple();
1685 const DataLayout &DL = header->getDataLayout();
1686 // Pointers without casting can provide more information about
1687 // alignment. Use pointers without casts if given target preserves
1688 // alignment information for cast the operation.
1689 if (isAlignmentPreservedForAddrCast(TargetTriple))
1690 AlignmentValue =
1691 inputs[i]->stripPointerCasts()->getPointerAlignment(DL).value();
1692 else
1693 AlignmentValue = inputs[i]->getPointerAlignment(DL).value();
1694 MDBuilder MDB(header->getContext());
1695 LoadGEP->setMetadata(
1696 KindID: LLVMContext::MD_align,
1697 Node: MDNode::get(
1698 Context&: header->getContext(),
1699 MDs: MDB.createConstant(C: ConstantInt::get(
1700 Ty: Type::getInt64Ty(C&: header->getContext()), V: AlignmentValue))));
1701 }
1702 RewriteVal = LoadGEP;
1703 ++aggIdx;
1704 } else
1705 RewriteVal = &*ScalarAI++;
1706
1707 NewValues.push_back(Elt: RewriteVal);
1708 }
1709
1710 moveCodeToFunction(newFunction);
1711
1712 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
1713 Value *RewriteVal = NewValues[i];
1714
1715 std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end());
1716 for (User *use : Users)
1717 if (Instruction *inst = dyn_cast<Instruction>(Val: use))
1718 if (Blocks.count(key: inst->getParent()))
1719 inst->replaceUsesOfWith(From: inputs[i], To: RewriteVal);
1720 }
1721
1722 // Since there may be multiple exits from the original region, make the new
1723 // function return an unsigned, switch on that number. This loop iterates
1724 // over all of the blocks in the extracted region, updating any terminator
1725 // instructions in the to-be-extracted region that branch to blocks that are
1726 // not in the region to be extracted.
1727 std::map<BasicBlock *, BasicBlock *> ExitBlockMap;
1728
1729 // Iterate over the previously collected targets, and create new blocks inside
1730 // the function to branch to.
1731 for (auto P : enumerate(First&: ExtractedFuncRetVals)) {
1732 BasicBlock *OldTarget = P.value();
1733 size_t SuccNum = P.index();
1734
1735 BasicBlock *NewTarget = BasicBlock::Create(
1736 Context, Name: OldTarget->getName() + ".exitStub", Parent: newFunction);
1737 ExitBlockMap[OldTarget] = NewTarget;
1738
1739 Value *brVal = nullptr;
1740 Type *RetTy = FuncRetVal ? FuncRetVal->getType() : getSwitchType();
1741 assert(ExtractedFuncRetVals.size() < 0xffff &&
1742 "too many exit blocks for switch");
1743 switch (ExtractedFuncRetVals.size()) {
1744 case 0:
1745 // No value needed.
1746 break;
1747 case 1:
1748 if (FuncRetVal)
1749 brVal = FuncRetVal;
1750 break;
1751 case 2: // Conditional branch, return a bool
1752 brVal = ConstantInt::get(Ty: RetTy, V: !SuccNum);
1753 break;
1754 default:
1755 brVal = ConstantInt::get(Ty: RetTy, V: SuccNum);
1756 break;
1757 }
1758
1759 ReturnInst::Create(C&: Context, retVal: brVal, InsertBefore: NewTarget);
1760 }
1761
1762 for (BasicBlock *Block : Blocks) {
1763 Instruction *TI = Block->getTerminator();
1764 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1765 if (Blocks.count(key: TI->getSuccessor(Idx: i)))
1766 continue;
1767 BasicBlock *OldTarget = TI->getSuccessor(Idx: i);
1768 // add a new basic block which returns the appropriate value
1769 BasicBlock *NewTarget = ExitBlockMap[OldTarget];
1770 assert(NewTarget && "Unknown target block!");
1771
1772 // rewrite the original branch instruction with this new target
1773 TI->setSuccessor(Idx: i, BB: NewTarget);
1774 }
1775 }
1776
1777 // Loop over all of the PHI nodes in the header and exit blocks, and change
1778 // any references to the old incoming edge to be the new incoming edge.
1779 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(Val: I); ++I) {
1780 PHINode *PN = cast<PHINode>(Val&: I);
1781 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1782 if (!Blocks.count(key: PN->getIncomingBlock(i)))
1783 PN->setIncomingBlock(i, BB: newFuncRoot);
1784 }
1785
1786 // Connect newFunction entry block to new header.
1787 UncondBrInst *BranchI = UncondBrInst::Create(Target: header, InsertBefore: newFuncRoot);
1788 applyFirstDebugLoc(oldFunction, Blocks: Blocks.getArrayRef(), BranchI);
1789
1790 // Store the arguments right after the definition of output value.
1791 // This should be proceeded after creating exit stubs to be ensure that invoke
1792 // result restore will be placed in the outlined function.
1793 ScalarAI = newFunction->arg_begin();
1794 unsigned AggIdx = 0;
1795
1796 for (Value *Input : inputs) {
1797 if (StructValues.contains(key: Input))
1798 ++AggIdx;
1799 else
1800 ++ScalarAI;
1801 }
1802
1803 for (Value *Output : outputs) {
1804 // Find proper insertion point.
1805 // In case Output is an invoke, we insert the store at the beginning in the
1806 // 'normal destination' BB. Otherwise we insert the store right after
1807 // Output.
1808 BasicBlock::iterator InsertPt;
1809 if (auto *InvokeI = dyn_cast<InvokeInst>(Val: Output))
1810 InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt();
1811 else if (auto *Phi = dyn_cast<PHINode>(Val: Output))
1812 InsertPt = Phi->getParent()->getFirstInsertionPt();
1813 else if (auto *OutI = dyn_cast<Instruction>(Val: Output))
1814 InsertPt = std::next(x: OutI->getIterator());
1815 else {
1816 // Globals don't need to be updated, just advance to the next argument.
1817 if (StructValues.contains(key: Output))
1818 ++AggIdx;
1819 else
1820 ++ScalarAI;
1821 continue;
1822 }
1823
1824 assert((InsertPt->getFunction() == newFunction ||
1825 Blocks.count(InsertPt->getParent())) &&
1826 "InsertPt should be in new function");
1827
1828 if (StructValues.contains(key: Output)) {
1829 assert(AggArg && "Number of aggregate output arguments should match "
1830 "the number of defined values");
1831 Value *Idx[2];
1832 Idx[0] = Constant::getNullValue(Ty: Type::getInt32Ty(C&: Context));
1833 Idx[1] = ConstantInt::get(Ty: Type::getInt32Ty(C&: Context), V: AggIdx);
1834 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1835 PointeeType: StructArgTy, Ptr: AggArg, IdxList: Idx, NameStr: "gep_" + Output->getName(), InsertBefore: InsertPt);
1836 new StoreInst(Output, GEP, InsertPt);
1837 ++AggIdx;
1838 } else {
1839 assert(ScalarAI != newFunction->arg_end() &&
1840 "Number of scalar output arguments should match "
1841 "the number of defined values");
1842 new StoreInst(Output, &*ScalarAI, InsertPt);
1843 ++ScalarAI;
1844 }
1845 }
1846
1847 if (ExtractedFuncRetVals.empty()) {
1848 // Mark the new function `noreturn` if applicable. Terminators which resume
1849 // exception propagation are treated as returning instructions. This is to
1850 // avoid inserting traps after calls to outlined functions which unwind.
1851 if (none_of(Range&: Blocks, P: [](const BasicBlock *BB) {
1852 const Instruction *Term = BB->getTerminator();
1853 return isa<ReturnInst>(Val: Term) || isa<ResumeInst>(Val: Term);
1854 }))
1855 newFunction->setDoesNotReturn();
1856 }
1857}
1858
1859CallInst *CodeExtractor::emitReplacerCall(
1860 const ValueSet &inputs, const ValueSet &outputs,
1861 const ValueSet &StructValues, Function *newFunction,
1862 StructType *StructArgTy, Function *oldFunction, BasicBlock *ReplIP,
1863 BlockFrequency EntryFreq, ArrayRef<Value *> LifetimesStart,
1864 std::vector<Value *> &Reloads) {
1865 LLVMContext &Context = oldFunction->getContext();
1866 Module *M = oldFunction->getParent();
1867
1868 // This takes place of the original loop
1869 BasicBlock *codeReplacer =
1870 BasicBlock::Create(Context, Name: "codeRepl", Parent: oldFunction, InsertBefore: ReplIP);
1871 if (AllocationBlock)
1872 assert(AllocationBlock->getParent() == oldFunction &&
1873 "AllocationBlock is not in the same function");
1874 BasicBlock *AllocaBlock =
1875 AllocationBlock ? AllocationBlock : &oldFunction->getEntryBlock();
1876
1877 // Update the entry count of the function.
1878 if (BFI)
1879 BFI->setBlockFreq(BB: codeReplacer, Freq: EntryFreq);
1880
1881 std::vector<Value *> params;
1882
1883 // Add inputs as params, or to be filled into the struct
1884 for (Value *input : inputs) {
1885 if (StructValues.contains(key: input))
1886 continue;
1887
1888 params.push_back(x: input);
1889 }
1890
1891 // Create allocas for the outputs
1892 std::vector<Value *> ReloadOutputs;
1893 for (Value *output : outputs) {
1894 if (StructValues.contains(key: output))
1895 continue;
1896
1897 Value *OutAlloc =
1898 allocateVar(AllocaIP: IRBuilder<>::InsertPoint(
1899 AllocaBlock, AllocaBlock->getFirstInsertionPt()),
1900 VarType: output->getType(), Name: output->getName() + ".loc");
1901 params.push_back(x: OutAlloc);
1902 ReloadOutputs.push_back(x: OutAlloc);
1903 }
1904
1905 Instruction *Struct = nullptr;
1906 if (!StructValues.empty()) {
1907 AddrSpaceCastInst *StructSpaceCast = nullptr;
1908 Struct = allocateVar(AllocaIP: IRBuilder<>::InsertPoint(
1909 AllocaBlock, AllocaBlock->getFirstInsertionPt()),
1910 VarType: StructArgTy, Name: "structArg", CastedAlloc: &StructSpaceCast);
1911 if (StructSpaceCast)
1912 params.push_back(x: StructSpaceCast);
1913 else
1914 params.push_back(x: Struct);
1915
1916 unsigned AggIdx = 0;
1917 for (Value *input : inputs) {
1918 if (!StructValues.contains(key: input))
1919 continue;
1920
1921 Value *Idx[2];
1922 Idx[0] = Constant::getNullValue(Ty: Type::getInt32Ty(C&: Context));
1923 Idx[1] = ConstantInt::get(Ty: Type::getInt32Ty(C&: Context), V: AggIdx);
1924 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1925 PointeeType: StructArgTy, Ptr: Struct, IdxList: Idx, NameStr: "gep_" + input->getName());
1926 GEP->insertInto(ParentBB: codeReplacer, It: codeReplacer->end());
1927 new StoreInst(input, GEP, codeReplacer);
1928
1929 ++AggIdx;
1930 }
1931 }
1932
1933 // Emit the call to the function
1934 CallInst *call = CallInst::Create(
1935 Func: newFunction, Args: params, NameStr: ExtractedFuncRetVals.size() > 1 ? "targetBlock" : "",
1936 InsertBefore: codeReplacer);
1937
1938 // Set swifterror parameter attributes.
1939 unsigned ParamIdx = 0;
1940 unsigned AggIdx = 0;
1941 for (auto input : inputs) {
1942 if (StructValues.contains(key: input)) {
1943 ++AggIdx;
1944 } else {
1945 if (input->isSwiftError())
1946 call->addParamAttr(ArgNo: ParamIdx, Kind: Attribute::SwiftError);
1947 ++ParamIdx;
1948 }
1949 }
1950
1951 // Add debug location to the new call, if the original function has debug
1952 // info. In that case, the terminator of the entry block of the extracted
1953 // function contains the first debug location of the extracted function,
1954 // set in extractCodeRegion.
1955 if (codeReplacer->getParent()->getSubprogram()) {
1956 if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc())
1957 call->setDebugLoc(DL);
1958 }
1959
1960 // Reload the outputs passed in by reference, use the struct if output is in
1961 // the aggregate or reload from the scalar argument.
1962 for (unsigned i = 0, e = outputs.size(), scalarIdx = 0; i != e; ++i) {
1963 Value *Output = nullptr;
1964 if (StructValues.contains(key: outputs[i])) {
1965 Value *Idx[2];
1966 Idx[0] = Constant::getNullValue(Ty: Type::getInt32Ty(C&: Context));
1967 Idx[1] = ConstantInt::get(Ty: Type::getInt32Ty(C&: Context), V: AggIdx);
1968 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1969 PointeeType: StructArgTy, Ptr: Struct, IdxList: Idx, NameStr: "gep_reload_" + outputs[i]->getName());
1970 GEP->insertInto(ParentBB: codeReplacer, It: codeReplacer->end());
1971 Output = GEP;
1972 ++AggIdx;
1973 } else {
1974 Output = ReloadOutputs[scalarIdx];
1975 ++scalarIdx;
1976 }
1977 LoadInst *load =
1978 new LoadInst(outputs[i]->getType(), Output,
1979 outputs[i]->getName() + ".reload", codeReplacer);
1980 Reloads.push_back(x: load);
1981 }
1982
1983 // Now we can emit a switch statement using the call as a value.
1984 SwitchInst *TheSwitch =
1985 SwitchInst::Create(Value: Constant::getNullValue(Ty: Type::getInt16Ty(C&: Context)),
1986 Default: codeReplacer, NumCases: 0, InsertBefore: codeReplacer);
1987 for (auto P : enumerate(First&: ExtractedFuncRetVals)) {
1988 BasicBlock *OldTarget = P.value();
1989 size_t SuccNum = P.index();
1990
1991 TheSwitch->addCase(OnVal: ConstantInt::get(Ty: Type::getInt16Ty(C&: Context), V: SuccNum),
1992 Dest: OldTarget);
1993 }
1994
1995 // Now that we've done the deed, simplify the switch instruction.
1996 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
1997 switch (ExtractedFuncRetVals.size()) {
1998 case 0:
1999 // There are no successors (the block containing the switch itself), which
2000 // means that previously this was the last part of the function, and hence
2001 // this should be rewritten as a `ret` or `unreachable`.
2002 if (newFunction->doesNotReturn()) {
2003 // If fn is no return, end with an unreachable terminator.
2004 (void)new UnreachableInst(Context, TheSwitch->getIterator());
2005 } else if (OldFnRetTy->isVoidTy()) {
2006 // We have no return value.
2007 ReturnInst::Create(C&: Context, retVal: nullptr,
2008 InsertBefore: TheSwitch->getIterator()); // Return void
2009 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
2010 // return what we have
2011 ReturnInst::Create(C&: Context, retVal: TheSwitch->getCondition(),
2012 InsertBefore: TheSwitch->getIterator());
2013 } else {
2014 // Otherwise we must have code extracted an unwind or something, just
2015 // return whatever we want.
2016 ReturnInst::Create(C&: Context, retVal: Constant::getNullValue(Ty: OldFnRetTy),
2017 InsertBefore: TheSwitch->getIterator());
2018 }
2019
2020 TheSwitch->eraseFromParent();
2021 break;
2022 case 1:
2023 // Only a single destination, change the switch into an unconditional
2024 // branch.
2025 UncondBrInst::Create(Target: TheSwitch->getSuccessor(idx: 1), InsertBefore: TheSwitch->getIterator());
2026 TheSwitch->eraseFromParent();
2027 break;
2028 case 2:
2029 // Only two destinations, convert to a condition branch.
2030 // Remark: This also swaps the target branches:
2031 // 0 -> false -> getSuccessor(2); 1 -> true -> getSuccessor(1)
2032 CondBrInst::Create(Cond: call, IfTrue: TheSwitch->getSuccessor(idx: 1),
2033 IfFalse: TheSwitch->getSuccessor(idx: 2), InsertBefore: TheSwitch->getIterator());
2034 TheSwitch->eraseFromParent();
2035 break;
2036 default:
2037 // Otherwise, make the default destination of the switch instruction be one
2038 // of the other successors.
2039 TheSwitch->setCondition(call);
2040 TheSwitch->setDefaultDest(
2041 TheSwitch->getSuccessor(idx: ExtractedFuncRetVals.size()));
2042 // Remove redundant case
2043 TheSwitch->removeCase(
2044 I: SwitchInst::CaseIt(TheSwitch, ExtractedFuncRetVals.size() - 1));
2045 break;
2046 }
2047
2048 // Insert lifetime markers around the reloads of any output values. The
2049 // allocas output values are stored in are only in-use in the codeRepl block.
2050 insertLifetimeMarkersSurroundingCall(M, LifetimesStart: ReloadOutputs, LifetimesEnd: ReloadOutputs, TheCall: call);
2051
2052 // Replicate the effects of any lifetime start/end markers which referenced
2053 // input objects in the extraction region by placing markers around the call.
2054 insertLifetimeMarkersSurroundingCall(M: oldFunction->getParent(), LifetimesStart,
2055 LifetimesEnd: {}, TheCall: call);
2056
2057 // Deallocate intermediate variables if they need explicit deallocation.
2058 auto deallocVars = [&](BasicBlock *DeallocBlock,
2059 BasicBlock::iterator DeallocIP) {
2060 int Index = 0;
2061 for (Value *Output : outputs) {
2062 if (!StructValues.contains(key: Output))
2063 deallocateVar(IRBuilder<>::InsertPoint(DeallocBlock, DeallocIP),
2064 ReloadOutputs[Index++], Output->getType());
2065 }
2066
2067 if (Struct)
2068 deallocateVar(IRBuilder<>::InsertPoint(DeallocBlock, DeallocIP), Struct,
2069 StructArgTy);
2070 };
2071
2072 if (DeallocationBlocks.empty()) {
2073 deallocVars(codeReplacer, codeReplacer->end());
2074 } else {
2075 for (BasicBlock *DeallocationBlock : DeallocationBlocks)
2076 deallocVars(DeallocationBlock, DeallocationBlock->getFirstInsertionPt());
2077 }
2078
2079 return call;
2080}
2081
2082void CodeExtractor::insertReplacerCall(
2083 Function *oldFunction, BasicBlock *header, CallInst *ReplacerCall,
2084 const ValueSet &outputs, ArrayRef<Value *> Reloads,
2085 const DenseMap<BasicBlock *, BlockFrequency> &ExitWeights) {
2086
2087 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
2088 // within the new function. This must be done before we lose track of which
2089 // blocks were originally in the code region.
2090 BasicBlock *codeReplacer = ReplacerCall->getParent();
2091 std::vector<User *> Users(header->user_begin(), header->user_end());
2092 for (auto &U : Users)
2093 // The BasicBlock which contains the branch is not in the region
2094 // modify the branch target to a new block
2095 if (Instruction *I = dyn_cast<Instruction>(Val: U))
2096 if (I->isTerminator() && I->getFunction() == oldFunction &&
2097 !Blocks.count(key: I->getParent()))
2098 I->replaceUsesOfWith(From: header, To: codeReplacer);
2099
2100 // When moving the code region it is sufficient to replace all uses to the
2101 // extracted function values. Since the original definition's block
2102 // dominated its use, it will also be dominated by codeReplacer's switch
2103 // which joined multiple exit blocks.
2104 for (BasicBlock *ExitBB : ExtractedFuncRetVals)
2105 for (PHINode &PN : ExitBB->phis()) {
2106 Value *IncomingCodeReplacerVal = nullptr;
2107 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2108 // Ignore incoming values from outside of the extracted region.
2109 if (!Blocks.count(key: PN.getIncomingBlock(i)))
2110 continue;
2111
2112 // Ensure that there is only one incoming value from codeReplacer.
2113 if (!IncomingCodeReplacerVal) {
2114 PN.setIncomingBlock(i, BB: codeReplacer);
2115 IncomingCodeReplacerVal = PN.getIncomingValue(i);
2116 } else
2117 assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) &&
2118 "PHI has two incompatbile incoming values from codeRepl");
2119 }
2120 }
2121
2122 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
2123 Value *load = Reloads[i];
2124 std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end());
2125 for (User *U : Users) {
2126 Instruction *inst = cast<Instruction>(Val: U);
2127 if (inst->getParent()->getParent() == oldFunction)
2128 inst->replaceUsesOfWith(From: outputs[i], To: load);
2129 }
2130 }
2131
2132 if (FuncRetVal)
2133 FuncRetVal->replaceUsesWithIf(New: ReplacerCall, ShouldReplace: [&](Use &U) {
2134 return cast<Instruction>(Val: U.getUser())->getFunction() == oldFunction;
2135 });
2136
2137 // Update the branch weights for the exit block.
2138 if (BFI && ExtractedFuncRetVals.size() > 1)
2139 calculateNewCallTerminatorWeights(CodeReplacer: codeReplacer, ExitWeights, BPI);
2140}
2141
2142bool CodeExtractor::verifyAssumptionCache(const Function &OldFunc,
2143 const Function &NewFunc,
2144 AssumptionCache *AC) {
2145 for (auto AssumeVH : AC->assumptions()) {
2146 auto *I = dyn_cast_or_null<CallInst>(Val&: AssumeVH);
2147 if (!I)
2148 continue;
2149
2150 // There shouldn't be any llvm.assume intrinsics in the new function.
2151 if (I->getFunction() != &OldFunc)
2152 return true;
2153
2154 // There shouldn't be any stale affected values in the assumption cache
2155 // that were previously in the old function, but that have now been moved
2156 // to the new function.
2157 for (auto AffectedValVH : AC->assumptionsFor(V: I->getOperand(i_nocapture: 0))) {
2158 auto *AffectedCI = dyn_cast_or_null<CallInst>(Val&: AffectedValVH);
2159 if (!AffectedCI)
2160 continue;
2161 if (AffectedCI->getFunction() != &OldFunc)
2162 return true;
2163 auto *AssumedInst = cast<Instruction>(Val: AffectedCI->getOperand(i_nocapture: 0));
2164 if (AssumedInst->getFunction() != &OldFunc)
2165 return true;
2166 }
2167 }
2168 return false;
2169}
2170
2171void CodeExtractor::excludeArgFromAggregate(Value *Arg) {
2172 ExcludeArgsFromAggregate.insert(X: Arg);
2173}
2174