1 //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the interface to tear out a code region, such as an
11 // individual loop or a parallel section, into a new function, replacing it with
12 // a call to the new function.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Utils/CodeExtractor.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Analysis/BlockFrequencyInfo.h"
21 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
22 #include "llvm/Analysis/BranchProbabilityInfo.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/RegionInfo.h"
25 #include "llvm/Analysis/RegionIterator.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/MDBuilder.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Verifier.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/BlockFrequency.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #define DEBUG_TYPE "code-extractor"
49 // Provide a command-line option to aggregate function arguments into a struct
50 // for functions produced by the code extractor. This is useful when converting
51 // extracted functions to pthread-based code, as only one argument (void*) can
52 // be passed in to pthread_create().
54 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
55 cl::desc("Aggregate arguments to code-extracted functions"));
57 /// \brief Test whether a block is valid for extraction.
58 bool CodeExtractor::isBlockValidForExtraction(const BasicBlock &BB) {
59 // Landing pads must be in the function where they were inserted for cleanup.
63 // Don't hoist code containing allocas, invokes, or vastarts.
64 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
65 if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
67 if (const CallInst *CI = dyn_cast<CallInst>(I))
68 if (const Function *F = CI->getCalledFunction())
69 if (F->getIntrinsicID() == Intrinsic::vastart)
76 /// \brief Build a set of blocks to extract if the input blocks are viable.
77 static SetVector<BasicBlock *>
78 buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT) {
79 assert(!BBs.empty() && "The set of blocks to extract must be non-empty");
80 SetVector<BasicBlock *> Result;
82 // Loop over the blocks, adding them to our set-vector, and aborting with an
83 // empty set if we encounter invalid blocks.
84 for (BasicBlock *BB : BBs) {
86 // If this block is dead, don't process it.
87 if (DT && !DT->isReachableFromEntry(BB))
90 if (!Result.insert(BB))
91 llvm_unreachable("Repeated basic blocks in extraction input");
92 if (!CodeExtractor::isBlockValidForExtraction(*BB)) {
99 for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()),
102 for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I);
104 assert(Result.count(*PI) &&
105 "No blocks in this region may have entries from outside the region"
106 " except for the first block!");
112 CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
113 bool AggregateArgs, BlockFrequencyInfo *BFI,
114 BranchProbabilityInfo *BPI)
115 : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
116 BPI(BPI), Blocks(buildExtractionBlockSet(BBs, DT)), NumExitBlocks(~0U) {}
118 CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs,
119 BlockFrequencyInfo *BFI,
120 BranchProbabilityInfo *BPI)
121 : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
122 BPI(BPI), Blocks(buildExtractionBlockSet(L.getBlocks(), &DT)),
123 NumExitBlocks(~0U) {}
125 /// definedInRegion - Return true if the specified value is defined in the
126 /// extracted region.
127 static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
128 if (Instruction *I = dyn_cast<Instruction>(V))
129 if (Blocks.count(I->getParent()))
134 /// definedInCaller - Return true if the specified value is defined in the
135 /// function being code extracted, but not in the region being extracted.
136 /// These values must be passed in as live-ins to the function.
137 static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
138 if (isa<Argument>(V)) return true;
139 if (Instruction *I = dyn_cast<Instruction>(V))
140 if (!Blocks.count(I->getParent()))
145 void CodeExtractor::findAllocas(ValueSet &SinkCands) const {
146 Function *Func = (*Blocks.begin())->getParent();
147 for (BasicBlock &BB : *Func) {
148 if (Blocks.count(&BB))
150 for (Instruction &II : BB) {
151 auto *AI = dyn_cast<AllocaInst>(&II);
155 // Returns true if matching life time markers are found within
156 // the outlined region.
157 auto GetLifeTimeMarkers = [&](Instruction *Addr) {
158 Instruction *LifeStart = nullptr, *LifeEnd = nullptr;
159 for (User *U : Addr->users()) {
160 if (!definedInRegion(Blocks, U))
163 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U);
165 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start)
166 LifeStart = IntrInst;
167 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end)
171 return LifeStart && LifeEnd;
174 if (GetLifeTimeMarkers(AI)) {
175 SinkCands.insert(AI);
179 // Follow the bitcast:
180 Instruction *MarkerAddr = nullptr;
181 for (User *U : AI->users()) {
182 if (U->stripPointerCasts() == AI) {
183 Instruction *Bitcast = cast<Instruction>(U);
184 if (GetLifeTimeMarkers(Bitcast)) {
185 MarkerAddr = Bitcast;
189 if (!definedInRegion(Blocks, U)) {
190 MarkerAddr = nullptr;
195 if (!definedInRegion(Blocks, MarkerAddr))
196 SinkCands.insert(MarkerAddr);
197 SinkCands.insert(AI);
203 void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
204 const ValueSet &SinkCands) const {
206 for (BasicBlock *BB : Blocks) {
207 // If a used value is defined outside the region, it's an input. If an
208 // instruction is used outside the region, it's an output.
209 for (Instruction &II : *BB) {
210 for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE;
213 if (!SinkCands.count(V) && definedInCaller(Blocks, V))
217 for (User *U : II.users())
218 if (!definedInRegion(Blocks, U)) {
226 /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
227 /// region, we need to split the entry block of the region so that the PHI node
228 /// is easier to deal with.
229 void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
230 unsigned NumPredsFromRegion = 0;
231 unsigned NumPredsOutsideRegion = 0;
233 if (Header != &Header->getParent()->getEntryBlock()) {
234 PHINode *PN = dyn_cast<PHINode>(Header->begin());
235 if (!PN) return; // No PHI nodes.
237 // If the header node contains any PHI nodes, check to see if there is more
238 // than one entry from outside the region. If so, we need to sever the
239 // header block into two.
240 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
241 if (Blocks.count(PN->getIncomingBlock(i)))
242 ++NumPredsFromRegion;
244 ++NumPredsOutsideRegion;
246 // If there is one (or fewer) predecessor from outside the region, we don't
247 // need to do anything special.
248 if (NumPredsOutsideRegion <= 1) return;
251 // Otherwise, we need to split the header block into two pieces: one
252 // containing PHI nodes merging values from outside of the region, and a
253 // second that contains all of the code for the block and merges back any
254 // incoming values from inside of the region.
255 BasicBlock *NewBB = llvm::SplitBlock(Header, Header->getFirstNonPHI(), DT);
257 // We only want to code extract the second block now, and it becomes the new
258 // header of the region.
259 BasicBlock *OldPred = Header;
260 Blocks.remove(OldPred);
261 Blocks.insert(NewBB);
264 // Okay, now we need to adjust the PHI nodes and any branches from within the
265 // region to go to the new header block instead of the old header block.
266 if (NumPredsFromRegion) {
267 PHINode *PN = cast<PHINode>(OldPred->begin());
268 // Loop over all of the predecessors of OldPred that are in the region,
269 // changing them to branch to NewBB instead.
270 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
271 if (Blocks.count(PN->getIncomingBlock(i))) {
272 TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
273 TI->replaceUsesOfWith(OldPred, NewBB);
276 // Okay, everything within the region is now branching to the right block, we
277 // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
278 BasicBlock::iterator AfterPHIs;
279 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
280 PHINode *PN = cast<PHINode>(AfterPHIs);
281 // Create a new PHI node in the new region, which has an incoming value
282 // from OldPred of PN.
283 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
284 PN->getName() + ".ce", &NewBB->front());
285 PN->replaceAllUsesWith(NewPN);
286 NewPN->addIncoming(PN, OldPred);
288 // Loop over all of the incoming value in PN, moving them to NewPN if they
289 // are from the extracted region.
290 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
291 if (Blocks.count(PN->getIncomingBlock(i))) {
292 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
293 PN->removeIncomingValue(i);
301 void CodeExtractor::splitReturnBlocks() {
302 for (BasicBlock *Block : Blocks)
303 if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
305 Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
307 // Old dominates New. New node dominates all other nodes dominated
309 DomTreeNode *OldNode = DT->getNode(Block);
310 SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
313 DomTreeNode *NewNode = DT->addNewBlock(New, Block);
315 for (DomTreeNode *I : Children)
316 DT->changeImmediateDominator(I, NewNode);
321 /// constructFunction - make a function based on inputs and outputs, as follows:
322 /// f(in0, ..., inN, out0, ..., outN)
324 Function *CodeExtractor::constructFunction(const ValueSet &inputs,
325 const ValueSet &outputs,
327 BasicBlock *newRootNode,
328 BasicBlock *newHeader,
329 Function *oldFunction,
331 DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
332 DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
334 // This function returns unsigned, outputs will go back by reference.
335 switch (NumExitBlocks) {
337 case 1: RetTy = Type::getVoidTy(header->getContext()); break;
338 case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
339 default: RetTy = Type::getInt16Ty(header->getContext()); break;
342 std::vector<Type*> paramTy;
344 // Add the types of the input values to the function's argument list
345 for (Value *value : inputs) {
346 DEBUG(dbgs() << "value used in func: " << *value << "\n");
347 paramTy.push_back(value->getType());
350 // Add the types of the output values to the function's argument list.
351 for (Value *output : outputs) {
352 DEBUG(dbgs() << "instr used in func: " << *output << "\n");
354 paramTy.push_back(output->getType());
356 paramTy.push_back(PointerType::getUnqual(output->getType()));
360 dbgs() << "Function type: " << *RetTy << " f(";
361 for (Type *i : paramTy)
362 dbgs() << *i << ", ";
366 StructType *StructTy;
367 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
368 StructTy = StructType::get(M->getContext(), paramTy);
370 paramTy.push_back(PointerType::getUnqual(StructTy));
372 FunctionType *funcType =
373 FunctionType::get(RetTy, paramTy, false);
375 // Create the new function
376 Function *newFunction = Function::Create(funcType,
377 GlobalValue::InternalLinkage,
378 oldFunction->getName() + "_" +
379 header->getName(), M);
380 // If the old function is no-throw, so is the new one.
381 if (oldFunction->doesNotThrow())
382 newFunction->setDoesNotThrow();
384 // Inherit the uwtable attribute if we need to.
385 if (oldFunction->hasUWTable())
386 newFunction->setHasUWTable();
388 // Inherit all of the target dependent attributes.
389 // (e.g. If the extracted region contains a call to an x86.sse
390 // instruction we need to make sure that the extracted region has the
391 // "target-features" attribute allowing it to be lowered.
392 // FIXME: This should be changed to check to see if a specific
393 // attribute can not be inherited.
394 AttrBuilder AB(oldFunction->getAttributes().getFnAttributes());
395 for (const auto &Attr : AB.td_attrs())
396 newFunction->addFnAttr(Attr.first, Attr.second);
398 newFunction->getBasicBlockList().push_back(newRootNode);
400 // Create an iterator to name all of the arguments we inserted.
401 Function::arg_iterator AI = newFunction->arg_begin();
403 // Rewrite all users of the inputs in the extracted region to use the
404 // arguments (or appropriate addressing into struct) instead.
405 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
409 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
410 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
411 TerminatorInst *TI = newFunction->begin()->getTerminator();
412 GetElementPtrInst *GEP = GetElementPtrInst::Create(
413 StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI);
414 RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
418 std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end());
419 for (User *use : Users)
420 if (Instruction *inst = dyn_cast<Instruction>(use))
421 if (Blocks.count(inst->getParent()))
422 inst->replaceUsesOfWith(inputs[i], RewriteVal);
425 // Set names for input and output arguments.
426 if (!AggregateArgs) {
427 AI = newFunction->arg_begin();
428 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
429 AI->setName(inputs[i]->getName());
430 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
431 AI->setName(outputs[i]->getName()+".out");
434 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
435 // within the new function. This must be done before we lose track of which
436 // blocks were originally in the code region.
437 std::vector<User*> Users(header->user_begin(), header->user_end());
438 for (unsigned i = 0, e = Users.size(); i != e; ++i)
439 // The BasicBlock which contains the branch is not in the region
440 // modify the branch target to a new block
441 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
442 if (!Blocks.count(TI->getParent()) &&
443 TI->getParent()->getParent() == oldFunction)
444 TI->replaceUsesOfWith(header, newHeader);
449 /// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI
450 /// that uses the value within the basic block, and return the predecessor
451 /// block associated with that use, or return 0 if none is found.
452 static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) {
453 for (Use &U : Used->uses()) {
454 PHINode *P = dyn_cast<PHINode>(U.getUser());
455 if (P && P->getParent() == BB)
456 return P->getIncomingBlock(U);
462 /// emitCallAndSwitchStatement - This method sets up the caller side by adding
463 /// the call instruction, splitting any PHI nodes in the header block as
466 emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
467 ValueSet &inputs, ValueSet &outputs) {
468 // Emit a call to the new function, passing in: *pointer to struct (if
469 // aggregating parameters), or plan inputs and allocated memory for outputs
470 std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
472 Module *M = newFunction->getParent();
473 LLVMContext &Context = M->getContext();
474 const DataLayout &DL = M->getDataLayout();
476 // Add inputs as params, or to be filled into the struct
477 for (Value *input : inputs)
479 StructValues.push_back(input);
481 params.push_back(input);
483 // Create allocas for the outputs
484 for (Value *output : outputs) {
486 StructValues.push_back(output);
489 new AllocaInst(output->getType(), DL.getAllocaAddrSpace(),
490 nullptr, output->getName() + ".loc",
491 &codeReplacer->getParent()->front().front());
492 ReloadOutputs.push_back(alloca);
493 params.push_back(alloca);
497 StructType *StructArgTy = nullptr;
498 AllocaInst *Struct = nullptr;
499 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
500 std::vector<Type*> ArgTypes;
501 for (ValueSet::iterator v = StructValues.begin(),
502 ve = StructValues.end(); v != ve; ++v)
503 ArgTypes.push_back((*v)->getType());
505 // Allocate a struct at the beginning of this function
506 StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
507 Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr,
509 &codeReplacer->getParent()->front().front());
510 params.push_back(Struct);
512 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
514 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
515 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
516 GetElementPtrInst *GEP = GetElementPtrInst::Create(
517 StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
518 codeReplacer->getInstList().push_back(GEP);
519 StoreInst *SI = new StoreInst(StructValues[i], GEP);
520 codeReplacer->getInstList().push_back(SI);
524 // Emit the call to the function
525 CallInst *call = CallInst::Create(newFunction, params,
526 NumExitBlocks > 1 ? "targetBlock" : "");
527 codeReplacer->getInstList().push_back(call);
529 Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
530 unsigned FirstOut = inputs.size();
532 std::advance(OutputArgBegin, inputs.size());
534 // Reload the outputs passed in by reference
535 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
536 Value *Output = nullptr;
539 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
540 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
541 GetElementPtrInst *GEP = GetElementPtrInst::Create(
542 StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
543 codeReplacer->getInstList().push_back(GEP);
546 Output = ReloadOutputs[i];
548 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
549 Reloads.push_back(load);
550 codeReplacer->getInstList().push_back(load);
551 std::vector<User*> Users(outputs[i]->user_begin(), outputs[i]->user_end());
552 for (unsigned u = 0, e = Users.size(); u != e; ++u) {
553 Instruction *inst = cast<Instruction>(Users[u]);
554 if (!Blocks.count(inst->getParent()))
555 inst->replaceUsesOfWith(outputs[i], load);
559 // Now we can emit a switch statement using the call as a value.
560 SwitchInst *TheSwitch =
561 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
562 codeReplacer, 0, codeReplacer);
564 // Since there may be multiple exits from the original region, make the new
565 // function return an unsigned, switch on that number. This loop iterates
566 // over all of the blocks in the extracted region, updating any terminator
567 // instructions in the to-be-extracted region that branch to blocks that are
568 // not in the region to be extracted.
569 std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
571 unsigned switchVal = 0;
572 for (BasicBlock *Block : Blocks) {
573 TerminatorInst *TI = Block->getTerminator();
574 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
575 if (!Blocks.count(TI->getSuccessor(i))) {
576 BasicBlock *OldTarget = TI->getSuccessor(i);
577 // add a new basic block which returns the appropriate value
578 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
580 // If we don't already have an exit stub for this non-extracted
581 // destination, create one now!
582 NewTarget = BasicBlock::Create(Context,
583 OldTarget->getName() + ".exitStub",
585 unsigned SuccNum = switchVal++;
587 Value *brVal = nullptr;
588 switch (NumExitBlocks) {
590 case 1: break; // No value needed.
591 case 2: // Conditional branch, return a bool
592 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
595 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
599 ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
601 // Update the switch instruction.
602 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
606 // Restore values just before we exit
607 Function::arg_iterator OAI = OutputArgBegin;
608 for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
609 // For an invoke, the normal destination is the only one that is
610 // dominated by the result of the invocation
611 BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
613 bool DominatesDef = true;
615 BasicBlock *NormalDest = nullptr;
616 if (auto *Invoke = dyn_cast<InvokeInst>(outputs[out]))
617 NormalDest = Invoke->getNormalDest();
620 DefBlock = NormalDest;
622 // Make sure we are looking at the original successor block, not
623 // at a newly inserted exit block, which won't be in the dominator
625 for (const auto &I : ExitBlockMap)
626 if (DefBlock == I.second) {
631 // In the extract block case, if the block we are extracting ends
632 // with an invoke instruction, make sure that we don't emit a
633 // store of the invoke value for the unwind block.
634 if (!DT && DefBlock != OldTarget)
635 DominatesDef = false;
639 DominatesDef = DT->dominates(DefBlock, OldTarget);
641 // If the output value is used by a phi in the target block,
642 // then we need to test for dominance of the phi's predecessor
643 // instead. Unfortunately, this a little complicated since we
644 // have already rewritten uses of the value to uses of the reload.
645 BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out],
647 if (pred && DT && DT->dominates(DefBlock, pred))
654 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
655 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
657 GetElementPtrInst *GEP = GetElementPtrInst::Create(
658 StructArgTy, &*OAI, Idx, "gep_" + outputs[out]->getName(),
660 new StoreInst(outputs[out], GEP, NTRet);
662 new StoreInst(outputs[out], &*OAI, NTRet);
665 // Advance output iterator even if we don't emit a store
666 if (!AggregateArgs) ++OAI;
670 // rewrite the original branch instruction with this new target
671 TI->setSuccessor(i, NewTarget);
675 // Now that we've done the deed, simplify the switch instruction.
676 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
677 switch (NumExitBlocks) {
679 // There are no successors (the block containing the switch itself), which
680 // means that previously this was the last part of the function, and hence
681 // this should be rewritten as a `ret'
683 // Check if the function should return a value
684 if (OldFnRetTy->isVoidTy()) {
685 ReturnInst::Create(Context, nullptr, TheSwitch); // Return void
686 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
687 // return what we have
688 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
690 // Otherwise we must have code extracted an unwind or something, just
691 // return whatever we want.
692 ReturnInst::Create(Context,
693 Constant::getNullValue(OldFnRetTy), TheSwitch);
696 TheSwitch->eraseFromParent();
699 // Only a single destination, change the switch into an unconditional
701 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
702 TheSwitch->eraseFromParent();
705 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
707 TheSwitch->eraseFromParent();
710 // Otherwise, make the default destination of the switch instruction be one
711 // of the other successors.
712 TheSwitch->setCondition(call);
713 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
714 // Remove redundant case
715 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
720 void CodeExtractor::moveCodeToFunction(Function *newFunction) {
721 Function *oldFunc = (*Blocks.begin())->getParent();
722 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
723 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
725 for (BasicBlock *Block : Blocks) {
726 // Delete the basic block from the old function, and the list of blocks
727 oldBlocks.remove(Block);
729 // Insert this basic block into the new function
730 newBlocks.push_back(Block);
734 void CodeExtractor::calculateNewCallTerminatorWeights(
735 BasicBlock *CodeReplacer,
736 DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
737 BranchProbabilityInfo *BPI) {
738 typedef BlockFrequencyInfoImplBase::Distribution Distribution;
739 typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
741 // Update the branch weights for the exit block.
742 TerminatorInst *TI = CodeReplacer->getTerminator();
743 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
745 // Block Frequency distribution with dummy node.
746 Distribution BranchDist;
748 // Add each of the frequencies of the successors.
749 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
750 BlockNode ExitNode(i);
751 uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency();
753 BranchDist.addExit(ExitNode, ExitFreq);
755 BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero());
758 // Check for no total weight.
759 if (BranchDist.Total == 0)
762 // Normalize the distribution so that they can fit in unsigned.
763 BranchDist.normalize();
765 // Create normalized branch weights and set the metadata.
766 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
767 const auto &Weight = BranchDist.Weights[I];
769 // Get the weight and update the current BFI.
770 BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
771 BranchProbability BP(Weight.Amount, BranchDist.Total);
772 BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP);
775 LLVMContext::MD_prof,
776 MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));
779 Function *CodeExtractor::extractCodeRegion() {
783 ValueSet inputs, outputs, SinkingCands;
785 // Assumption: this is a single-entry code region, and the header is the first
786 // block in the region.
787 BasicBlock *header = *Blocks.begin();
789 // Calculate the entry frequency of the new function before we change the root
791 BlockFrequency EntryFreq;
793 assert(BPI && "Both BPI and BFI are required to preserve profile info");
794 for (BasicBlock *Pred : predecessors(header)) {
795 if (Blocks.count(Pred))
798 BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);
802 // If we have to split PHI nodes or the entry block, do so now.
803 severSplitPHINodes(header);
805 // If we have any return instructions in the region, split those blocks so
806 // that the return is not in the region.
809 Function *oldFunction = header->getParent();
811 // This takes place of the original loop
812 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
813 "codeRepl", oldFunction,
816 // The new function needs a root node because other nodes can branch to the
817 // head of the region, but the entry node of a function cannot have preds.
818 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
820 newFuncRoot->getInstList().push_back(BranchInst::Create(header));
822 findAllocas(SinkingCands);
824 // Find inputs to, outputs from the code region.
825 findInputsOutputs(inputs, outputs, SinkingCands);
827 // Now sink all instructions which only have non-phi uses inside the region
828 for (auto *II : SinkingCands)
829 cast<Instruction>(II)->moveBefore(*newFuncRoot,
830 newFuncRoot->getFirstInsertionPt());
832 // Calculate the exit blocks for the extracted region and the total exit
833 // weights for each of those blocks.
834 DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
835 SmallPtrSet<BasicBlock *, 1> ExitBlocks;
836 for (BasicBlock *Block : Blocks) {
837 for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE;
839 if (!Blocks.count(*SI)) {
840 // Update the branch weight for this successor.
842 BlockFrequency &BF = ExitWeights[*SI];
843 BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI);
845 ExitBlocks.insert(*SI);
849 NumExitBlocks = ExitBlocks.size();
851 // Construct new function based on inputs/outputs & add allocas for all defs.
852 Function *newFunction = constructFunction(inputs, outputs, header,
854 codeReplacer, oldFunction,
855 oldFunction->getParent());
857 // Update the entry count of the function.
859 Optional<uint64_t> EntryCount =
860 BFI->getProfileCountFromFreq(EntryFreq.getFrequency());
861 if (EntryCount.hasValue())
862 newFunction->setEntryCount(EntryCount.getValue());
863 BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency());
866 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
868 moveCodeToFunction(newFunction);
870 // Update the branch weights for the exit block.
871 if (BFI && NumExitBlocks > 1)
872 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
874 // Loop over all of the PHI nodes in the header block, and change any
875 // references to the old incoming edge to be the new incoming edge.
876 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
877 PHINode *PN = cast<PHINode>(I);
878 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
879 if (!Blocks.count(PN->getIncomingBlock(i)))
880 PN->setIncomingBlock(i, newFuncRoot);
883 // Look at all successors of the codeReplacer block. If any of these blocks
884 // had PHI nodes in them, we need to update the "from" block to be the code
885 // replacer, not the original block in the extracted region.
886 std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
887 succ_end(codeReplacer));
888 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
889 for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
890 PHINode *PN = cast<PHINode>(I);
891 std::set<BasicBlock*> ProcessedPreds;
892 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
893 if (Blocks.count(PN->getIncomingBlock(i))) {
894 if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
895 PN->setIncomingBlock(i, codeReplacer);
897 // There were multiple entries in the PHI for this block, now there
898 // is only one, so remove the duplicated entries.
899 PN->removeIncomingValue(i, false);
905 //cerr << "NEW FUNCTION: " << *newFunction;
906 // verifyFunction(*newFunction);
908 // cerr << "OLD FUNCTION: " << *oldFunction;
909 // verifyFunction(*oldFunction);
911 DEBUG(if (verifyFunction(*newFunction))
912 report_fatal_error("verifyFunction failed!"));