blob: 03e2b9db078fd656e0381b90075dc8f339f49d87 [file] [log] [blame]
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001//===- CodeExtractor.cpp - Pull code region into a new function -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Misha Brukmanb1c93172005-04-21 23:48:37 +00006//
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00007//===----------------------------------------------------------------------===//
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
Chandler Carruth0fde0012012-05-04 10:18:49 +000015#include "llvm/Transforms/Utils/CodeExtractor.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000016#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/Optional.h"
Jakub Staszakf23980a2013-02-09 01:04:28 +000019#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000020#include "llvm/ADT/SetVector.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
Sean Silvaf8015752016-08-02 02:15:45 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
24#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
25#include "llvm/Analysis/BranchProbabilityInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/LoopInfo.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000027#include "llvm/IR/Argument.h"
28#include "llvm/IR/Attributes.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/CFG.h"
31#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Constants.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000033#include "llvm/IR/DataLayout.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000035#include "llvm/IR/Dominators.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000036#include "llvm/IR/Function.h"
37#include "llvm/IR/GlobalValue.h"
38#include "llvm/IR/InstrTypes.h"
39#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Instructions.h"
Xinliang David Li74480ad2017-05-30 21:22:18 +000041#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/Intrinsics.h"
43#include "llvm/IR/LLVMContext.h"
Sean Silvaf8015752016-08-02 02:15:45 +000044#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000045#include "llvm/IR/Module.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000046#include "llvm/IR/Type.h"
47#include "llvm/IR/User.h"
48#include "llvm/IR/Value.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000049#include "llvm/IR/Verifier.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000050#include "llvm/Pass.h"
Sean Silvaf8015752016-08-02 02:15:45 +000051#include "llvm/Support/BlockFrequency.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000052#include "llvm/Support/BranchProbability.h"
53#include "llvm/Support/Casting.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000054#include "llvm/Support/CommandLine.h"
55#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000056#include "llvm/Support/ErrorHandling.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000057#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000058#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Vedant Kumar09b7aa42018-11-06 19:05:53 +000059#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000060#include <cassert>
61#include <cstdint>
62#include <iterator>
63#include <map>
Chris Lattner9c431f62004-03-14 22:34:55 +000064#include <set>
Eugene Zelenko286d5892017-10-11 21:41:43 +000065#include <utility>
66#include <vector>
67
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000068using namespace llvm;
Easwaran Ramane5b8de22018-01-17 22:24:23 +000069using ProfileCount = Function::ProfileCount;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000070
Chandler Carruthe96dd892014-04-21 22:55:11 +000071#define DEBUG_TYPE "code-extractor"
72
Misha Brukman3596f0a2004-04-23 23:54:17 +000073// Provide a command-line option to aggregate function arguments into a struct
Misha Brukman234b44a2008-12-13 05:21:37 +000074// for functions produced by the code extractor. This is useful when converting
Misha Brukman3596f0a2004-04-23 23:54:17 +000075// extracted functions to pthread-based code, as only one argument (void*) can
76// be passed in to pthread_create().
77static cl::opt<bool>
78AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
79 cl::desc("Aggregate arguments to code-extracted functions"));
80
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000081/// Test whether a block is valid for extraction.
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +000082static bool isBlockValidForExtraction(const BasicBlock &BB,
83 const SetVector<BasicBlock *> &Result,
84 bool AllowVarArgs, bool AllowAlloca) {
Serge Guelton7bc405a2017-06-27 18:57:53 +000085 // taking the address of a basic block moved to another function is illegal
86 if (BB.hasAddressTaken())
87 return false;
88
89 // don't hoist code that uses another basicblock address, as it's likely to
90 // lead to unexpected behavior, like cross-function jumps
91 SmallPtrSet<User const *, 16> Visited;
92 SmallVector<User const *, 16> ToVisit;
93
94 for (Instruction const &Inst : BB)
95 ToVisit.push_back(&Inst);
96
97 while (!ToVisit.empty()) {
98 User const *Curr = ToVisit.pop_back_val();
99 if (!Visited.insert(Curr).second)
100 continue;
101 if (isa<BlockAddress const>(Curr))
102 return false; // even a reference to self is likely to be not compatible
103
104 if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB)
105 continue;
106
107 for (auto const &U : Curr->operands()) {
108 if (auto *UU = dyn_cast<User>(U))
109 ToVisit.push_back(UU);
110 }
111 }
Chris Lattner37de2572004-03-18 03:49:40 +0000112
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000113 // If explicitly requested, allow vastart and alloca. For invoke instructions
114 // verify that extraction is valid.
Chandler Carruth0fde0012012-05-04 10:18:49 +0000115 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000116 if (isa<AllocaInst>(I)) {
117 if (!AllowAlloca)
118 return false;
119 continue;
120 }
121
122 if (const auto *II = dyn_cast<InvokeInst>(I)) {
123 // Unwind destination (either a landingpad, catchswitch, or cleanuppad)
124 // must be a part of the subgraph which is being extracted.
125 if (auto *UBB = II->getUnwindDest())
126 if (!Result.count(UBB))
127 return false;
128 continue;
129 }
130
131 // All catch handlers of a catchswitch instruction as well as the unwind
132 // destination must be in the subgraph.
133 if (const auto *CSI = dyn_cast<CatchSwitchInst>(I)) {
134 if (auto *UBB = CSI->getUnwindDest())
135 if (!Result.count(UBB))
136 return false;
137 for (auto *HBB : CSI->handlers())
138 if (!Result.count(const_cast<BasicBlock*>(HBB)))
139 return false;
140 continue;
141 }
142
143 // Make sure that entire catch handler is within subgraph. It is sufficient
144 // to check that catch return's block is in the list.
145 if (const auto *CPI = dyn_cast<CatchPadInst>(I)) {
146 for (const auto *U : CPI->users())
147 if (const auto *CRI = dyn_cast<CatchReturnInst>(U))
148 if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))
149 return false;
150 continue;
151 }
152
153 // And do similar checks for cleanup handler - the entire handler must be
154 // in subgraph which is going to be extracted. For cleanup return should
155 // additionally check that the unwind destination is also in the subgraph.
156 if (const auto *CPI = dyn_cast<CleanupPadInst>(I)) {
157 for (const auto *U : CPI->users())
158 if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
159 if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))
160 return false;
161 continue;
162 }
163 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I)) {
164 if (auto *UBB = CRI->getUnwindDest())
165 if (!Result.count(UBB))
166 return false;
167 continue;
168 }
169
Vedant Kumar1e209e22018-11-06 19:06:08 +0000170 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
171 if (const Function *F = CI->getCalledFunction()) {
172 auto IID = F->getIntrinsicID();
173 if (IID == Intrinsic::vastart) {
Florian Hahn0e9dec62017-11-13 10:35:52 +0000174 if (AllowVarArgs)
175 continue;
176 else
177 return false;
178 }
Vedant Kumar1e209e22018-11-06 19:06:08 +0000179
180 // Currently, we miscompile outlined copies of eh_typid_for. There are
181 // proposals for fixing this in llvm.org/PR39545.
182 if (IID == Intrinsic::eh_typeid_for)
183 return false;
184 }
185 }
Chandler Carruth0fde0012012-05-04 10:18:49 +0000186 }
187
188 return true;
189}
190
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000191/// Build a set of blocks to extract if the input blocks are viable.
Davide Italiano059574c2017-04-21 00:21:09 +0000192static SetVector<BasicBlock *>
Florian Hahn0e9dec62017-11-13 10:35:52 +0000193buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000194 bool AllowVarArgs, bool AllowAlloca) {
Davide Italianofa15de32017-04-21 04:25:00 +0000195 assert(!BBs.empty() && "The set of blocks to extract must be non-empty");
Davide Italiano059574c2017-04-21 00:21:09 +0000196 SetVector<BasicBlock *> Result;
Chandler Carruth2f5d0192012-05-04 10:26:45 +0000197
Chandler Carruth0fde0012012-05-04 10:18:49 +0000198 // Loop over the blocks, adding them to our set-vector, and aborting with an
199 // empty set if we encounter invalid blocks.
Davide Italianofa15de32017-04-21 04:25:00 +0000200 for (BasicBlock *BB : BBs) {
Davide Italianofa15de32017-04-21 04:25:00 +0000201 // If this block is dead, don't process it.
202 if (DT && !DT->isReachableFromEntry(BB))
203 continue;
204
205 if (!Result.insert(BB))
206 llvm_unreachable("Repeated basic blocks in extraction input");
Davide Italianofa15de32017-04-21 04:25:00 +0000207 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000208
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000209 for (auto *BB : Result) {
210 if (!isBlockValidForExtraction(*BB, Result, AllowVarArgs, AllowAlloca))
211 return {};
212
213 // Make sure that the first block is not a landing pad.
214 if (BB == Result.front()) {
215 if (BB->isEHPad()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000216 LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n");
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000217 return {};
218 }
219 continue;
220 }
221
222 // All blocks other than the first must not have predecessors outside of
223 // the subgraph which is being extracted.
224 for (auto *PBB : predecessors(BB))
225 if (!Result.count(PBB)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000226 LLVM_DEBUG(
227 dbgs() << "No blocks in this region may have entries from "
228 "outside the region except for the first block!\n");
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000229 return {};
230 }
231 }
Chandler Carruth2f5d0192012-05-04 10:26:45 +0000232
Chandler Carruth0fde0012012-05-04 10:18:49 +0000233 return Result;
234}
Chris Lattner3b2917b2004-05-12 06:01:40 +0000235
Chandler Carruth0fde0012012-05-04 10:18:49 +0000236CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
Sean Silvaf8015752016-08-02 02:15:45 +0000237 bool AggregateArgs, BlockFrequencyInfo *BFI,
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000238 BranchProbabilityInfo *BPI, bool AllowVarArgs,
Teresa Johnsonc8dba682018-10-24 18:53:47 +0000239 bool AllowAlloca, std::string Suffix)
Sean Silvaf8015752016-08-02 02:15:45 +0000240 : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
Florian Hahn0e9dec62017-11-13 10:35:52 +0000241 BPI(BPI), AllowVarArgs(AllowVarArgs),
Teresa Johnsonc8dba682018-10-24 18:53:47 +0000242 Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)),
243 Suffix(Suffix) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000244
Sean Silvaf8015752016-08-02 02:15:45 +0000245CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs,
246 BlockFrequencyInfo *BFI,
Teresa Johnsonc8dba682018-10-24 18:53:47 +0000247 BranchProbabilityInfo *BPI, std::string Suffix)
Sean Silvaf8015752016-08-02 02:15:45 +0000248 : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
Florian Hahn71147552017-11-13 11:08:47 +0000249 BPI(BPI), AllowVarArgs(false),
250 Blocks(buildExtractionBlockSet(L.getBlocks(), &DT,
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000251 /* AllowVarArgs */ false,
Teresa Johnsonc8dba682018-10-24 18:53:47 +0000252 /* AllowAlloca */ false)),
253 Suffix(Suffix) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000254
Chandler Carruth0fde0012012-05-04 10:18:49 +0000255/// definedInRegion - Return true if the specified value is defined in the
256/// extracted region.
257static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
258 if (Instruction *I = dyn_cast<Instruction>(V))
259 if (Blocks.count(I->getParent()))
260 return true;
261 return false;
262}
263
264/// definedInCaller - Return true if the specified value is defined in the
265/// function being code extracted, but not in the region being extracted.
266/// These values must be passed in as live-ins to the function.
267static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
268 if (isa<Argument>(V)) return true;
269 if (Instruction *I = dyn_cast<Instruction>(V))
270 if (!Blocks.count(I->getParent()))
271 return true;
272 return false;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000273}
274
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000275static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) {
276 BasicBlock *CommonExitBlock = nullptr;
277 auto hasNonCommonExitSucc = [&](BasicBlock *Block) {
278 for (auto *Succ : successors(Block)) {
279 // Internal edges, ok.
280 if (Blocks.count(Succ))
281 continue;
282 if (!CommonExitBlock) {
283 CommonExitBlock = Succ;
284 continue;
285 }
286 if (CommonExitBlock == Succ)
287 continue;
288
289 return true;
290 }
291 return false;
292 };
293
294 if (any_of(Blocks, hasNonCommonExitSucc))
295 return nullptr;
296
297 return CommonExitBlock;
298}
299
300bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers(
301 Instruction *Addr) const {
302 AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets());
Xinliang David Li74480ad2017-05-30 21:22:18 +0000303 Function *Func = (*Blocks.begin())->getParent();
304 for (BasicBlock &BB : *Func) {
305 if (Blocks.count(&BB))
306 continue;
307 for (Instruction &II : BB) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000308 if (isa<DbgInfoIntrinsic>(II))
309 continue;
310
311 unsigned Opcode = II.getOpcode();
312 Value *MemAddr = nullptr;
313 switch (Opcode) {
314 case Instruction::Store:
315 case Instruction::Load: {
316 if (Opcode == Instruction::Store) {
317 StoreInst *SI = cast<StoreInst>(&II);
318 MemAddr = SI->getPointerOperand();
319 } else {
320 LoadInst *LI = cast<LoadInst>(&II);
321 MemAddr = LI->getPointerOperand();
322 }
323 // Global variable can not be aliased with locals.
324 if (dyn_cast<Constant>(MemAddr))
325 break;
326 Value *Base = MemAddr->stripInBoundsConstantOffsets();
327 if (!dyn_cast<AllocaInst>(Base) || Base == AI)
328 return false;
329 break;
330 }
331 default: {
332 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II);
333 if (IntrInst) {
Vedant Kumarb264d692018-12-21 21:49:40 +0000334 if (IntrInst->isLifetimeStartOrEnd())
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000335 break;
336 return false;
337 }
338 // Treat all the other cases conservatively if it has side effects.
339 if (II.mayHaveSideEffects())
340 return false;
341 }
342 }
343 }
344 }
345
346 return true;
347}
348
349BasicBlock *
350CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) {
351 BasicBlock *SinglePredFromOutlineRegion = nullptr;
352 assert(!Blocks.count(CommonExitBlock) &&
353 "Expect a block outside the region!");
354 for (auto *Pred : predecessors(CommonExitBlock)) {
355 if (!Blocks.count(Pred))
356 continue;
357 if (!SinglePredFromOutlineRegion) {
358 SinglePredFromOutlineRegion = Pred;
359 } else if (SinglePredFromOutlineRegion != Pred) {
360 SinglePredFromOutlineRegion = nullptr;
361 break;
362 }
363 }
364
365 if (SinglePredFromOutlineRegion)
366 return SinglePredFromOutlineRegion;
367
368#ifndef NDEBUG
369 auto getFirstPHI = [](BasicBlock *BB) {
370 BasicBlock::iterator I = BB->begin();
371 PHINode *FirstPhi = nullptr;
372 while (I != BB->end()) {
373 PHINode *Phi = dyn_cast<PHINode>(I);
374 if (!Phi)
375 break;
376 if (!FirstPhi) {
377 FirstPhi = Phi;
378 break;
379 }
380 }
381 return FirstPhi;
382 };
383 // If there are any phi nodes, the single pred either exists or has already
384 // be created before code extraction.
385 assert(!getFirstPHI(CommonExitBlock) && "Phi not expected");
386#endif
387
388 BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock(
389 CommonExitBlock->getFirstNonPHI()->getIterator());
390
Florian Hahnb93c0632017-11-01 09:48:12 +0000391 for (auto PI = pred_begin(CommonExitBlock), PE = pred_end(CommonExitBlock);
392 PI != PE;) {
393 BasicBlock *Pred = *PI++;
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000394 if (Blocks.count(Pred))
395 continue;
396 Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock);
397 }
398 // Now add the old exit block to the outline region.
399 Blocks.insert(CommonExitBlock);
400 return CommonExitBlock;
401}
402
403void CodeExtractor::findAllocas(ValueSet &SinkCands, ValueSet &HoistCands,
404 BasicBlock *&ExitBlock) const {
405 Function *Func = (*Blocks.begin())->getParent();
406 ExitBlock = getCommonExitBlock(Blocks);
407
408 for (BasicBlock &BB : *Func) {
409 if (Blocks.count(&BB))
410 continue;
411 for (Instruction &II : BB) {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000412 auto *AI = dyn_cast<AllocaInst>(&II);
413 if (!AI)
414 continue;
415
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000416 // Find the pair of life time markers for address 'Addr' that are either
417 // defined inside the outline region or can legally be shrinkwrapped into
418 // the outline region. If there are not other untracked uses of the
419 // address, return the pair of markers if found; otherwise return a pair
420 // of nullptr.
421 auto GetLifeTimeMarkers =
422 [&](Instruction *Addr, bool &SinkLifeStart,
423 bool &HoistLifeEnd) -> std::pair<Instruction *, Instruction *> {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000424 Instruction *LifeStart = nullptr, *LifeEnd = nullptr;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000425
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000426 for (User *U : Addr->users()) {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000427 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U);
428 if (IntrInst) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000429 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) {
430 // Do not handle the case where AI has multiple start markers.
431 if (LifeStart)
432 return std::make_pair<Instruction *>(nullptr, nullptr);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000433 LifeStart = IntrInst;
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000434 }
435 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) {
436 if (LifeEnd)
437 return std::make_pair<Instruction *>(nullptr, nullptr);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000438 LifeEnd = IntrInst;
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000439 }
440 continue;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000441 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000442 // Find untracked uses of the address, bail.
443 if (!definedInRegion(Blocks, U))
444 return std::make_pair<Instruction *>(nullptr, nullptr);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000445 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000446
447 if (!LifeStart || !LifeEnd)
448 return std::make_pair<Instruction *>(nullptr, nullptr);
449
450 SinkLifeStart = !definedInRegion(Blocks, LifeStart);
451 HoistLifeEnd = !definedInRegion(Blocks, LifeEnd);
452 // Do legality Check.
453 if ((SinkLifeStart || HoistLifeEnd) &&
454 !isLegalToShrinkwrapLifetimeMarkers(Addr))
455 return std::make_pair<Instruction *>(nullptr, nullptr);
456
457 // Check to see if we have a place to do hoisting, if not, bail.
458 if (HoistLifeEnd && !ExitBlock)
459 return std::make_pair<Instruction *>(nullptr, nullptr);
460
461 return std::make_pair(LifeStart, LifeEnd);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000462 };
463
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000464 bool SinkLifeStart = false, HoistLifeEnd = false;
465 auto Markers = GetLifeTimeMarkers(AI, SinkLifeStart, HoistLifeEnd);
466
467 if (Markers.first) {
468 if (SinkLifeStart)
469 SinkCands.insert(Markers.first);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000470 SinkCands.insert(AI);
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000471 if (HoistLifeEnd)
472 HoistCands.insert(Markers.second);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000473 continue;
474 }
475
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000476 // Follow the bitcast.
Xinliang David Li74480ad2017-05-30 21:22:18 +0000477 Instruction *MarkerAddr = nullptr;
478 for (User *U : AI->users()) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000479 if (U->stripInBoundsConstantOffsets() == AI) {
480 SinkLifeStart = false;
481 HoistLifeEnd = false;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000482 Instruction *Bitcast = cast<Instruction>(U);
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000483 Markers = GetLifeTimeMarkers(Bitcast, SinkLifeStart, HoistLifeEnd);
484 if (Markers.first) {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000485 MarkerAddr = Bitcast;
486 continue;
487 }
488 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000489
490 // Found unknown use of AI.
Xinliang David Li74480ad2017-05-30 21:22:18 +0000491 if (!definedInRegion(Blocks, U)) {
492 MarkerAddr = nullptr;
493 break;
494 }
495 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000496
Xinliang David Li74480ad2017-05-30 21:22:18 +0000497 if (MarkerAddr) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000498 if (SinkLifeStart)
499 SinkCands.insert(Markers.first);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000500 if (!definedInRegion(Blocks, MarkerAddr))
501 SinkCands.insert(MarkerAddr);
502 SinkCands.insert(AI);
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000503 if (HoistLifeEnd)
504 HoistCands.insert(Markers.second);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000505 }
506 }
507 }
508}
509
510void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
511 const ValueSet &SinkCands) const {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000512 for (BasicBlock *BB : Blocks) {
Chandler Carruth14316fc2012-05-04 11:20:27 +0000513 // If a used value is defined outside the region, it's an input. If an
514 // instruction is used outside the region, it's an output.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000515 for (Instruction &II : *BB) {
516 for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000517 ++OI) {
518 Value *V = *OI;
519 if (!SinkCands.count(V) && definedInCaller(Blocks, V))
520 Inputs.insert(V);
521 }
Chandler Carruth14316fc2012-05-04 11:20:27 +0000522
Benjamin Kramer135f7352016-06-26 12:28:59 +0000523 for (User *U : II.users())
Chandler Carruthcdf47882014-03-09 03:16:01 +0000524 if (!definedInRegion(Blocks, U)) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000525 Outputs.insert(&II);
Chandler Carruth14316fc2012-05-04 11:20:27 +0000526 break;
527 }
528 }
529 }
530}
531
Vedant Kumard1295692018-12-03 22:40:21 +0000532/// severSplitPHINodesOfEntry - If a PHI node has multiple inputs from outside
533/// of the region, we need to split the entry block of the region so that the
534/// PHI node is easier to deal with.
535void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) {
Jay Foade0938d82011-03-30 11:19:20 +0000536 unsigned NumPredsFromRegion = 0;
Chris Lattner795c9932004-05-12 15:29:13 +0000537 unsigned NumPredsOutsideRegion = 0;
Chris Lattner3b2917b2004-05-12 06:01:40 +0000538
Dan Gohmandcb291f2007-03-22 16:38:57 +0000539 if (Header != &Header->getParent()->getEntryBlock()) {
Chris Lattner795c9932004-05-12 15:29:13 +0000540 PHINode *PN = dyn_cast<PHINode>(Header->begin());
541 if (!PN) return; // No PHI nodes.
Chris Lattner3b2917b2004-05-12 06:01:40 +0000542
Chris Lattner795c9932004-05-12 15:29:13 +0000543 // If the header node contains any PHI nodes, check to see if there is more
544 // than one entry from outside the region. If so, we need to sever the
545 // header block into two.
546 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000547 if (Blocks.count(PN->getIncomingBlock(i)))
Jay Foade0938d82011-03-30 11:19:20 +0000548 ++NumPredsFromRegion;
Chris Lattner795c9932004-05-12 15:29:13 +0000549 else
550 ++NumPredsOutsideRegion;
551
552 // If there is one (or fewer) predecessor from outside the region, we don't
553 // need to do anything special.
554 if (NumPredsOutsideRegion <= 1) return;
555 }
556
557 // Otherwise, we need to split the header block into two pieces: one
558 // containing PHI nodes merging values from outside of the region, and a
559 // second that contains all of the code for the block and merges back any
560 // incoming values from inside of the region.
Eugene Zelenko286d5892017-10-11 21:41:43 +0000561 BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT);
Chris Lattner795c9932004-05-12 15:29:13 +0000562
563 // We only want to code extract the second block now, and it becomes the new
564 // header of the region.
565 BasicBlock *OldPred = Header;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000566 Blocks.remove(OldPred);
567 Blocks.insert(NewBB);
Chris Lattner795c9932004-05-12 15:29:13 +0000568 Header = NewBB;
569
Chris Lattner795c9932004-05-12 15:29:13 +0000570 // Okay, now we need to adjust the PHI nodes and any branches from within the
571 // region to go to the new header block instead of the old header block.
Jay Foade0938d82011-03-30 11:19:20 +0000572 if (NumPredsFromRegion) {
Chris Lattner795c9932004-05-12 15:29:13 +0000573 PHINode *PN = cast<PHINode>(OldPred->begin());
574 // Loop over all of the predecessors of OldPred that are in the region,
575 // changing them to branch to NewBB instead.
576 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000577 if (Blocks.count(PN->getIncomingBlock(i))) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000578 Instruction *TI = PN->getIncomingBlock(i)->getTerminator();
Chris Lattner795c9932004-05-12 15:29:13 +0000579 TI->replaceUsesOfWith(OldPred, NewBB);
580 }
581
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000582 // Okay, everything within the region is now branching to the right block, we
Chris Lattner795c9932004-05-12 15:29:13 +0000583 // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
Xinliang David Li99e3ca12017-04-20 21:40:22 +0000584 BasicBlock::iterator AfterPHIs;
Reid Spencer66149462004-09-15 17:06:42 +0000585 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
586 PHINode *PN = cast<PHINode>(AfterPHIs);
Chris Lattner795c9932004-05-12 15:29:13 +0000587 // Create a new PHI node in the new region, which has an incoming value
588 // from OldPred of PN.
Jay Foad52131342011-03-30 11:28:46 +0000589 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000590 PN->getName() + ".ce", &NewBB->front());
Xinliang David Lif12a0fa2017-04-25 04:51:19 +0000591 PN->replaceAllUsesWith(NewPN);
Chris Lattner795c9932004-05-12 15:29:13 +0000592 NewPN->addIncoming(PN, OldPred);
593
594 // Loop over all of the incoming value in PN, moving them to NewPN if they
595 // are from the extracted region.
596 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000597 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000598 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
599 PN->removeIncomingValue(i);
600 --i;
601 }
602 }
603 }
604 }
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000605}
Chris Lattner795c9932004-05-12 15:29:13 +0000606
Vedant Kumard1295692018-12-03 22:40:21 +0000607/// severSplitPHINodesOfExits - if PHI nodes in exit blocks have inputs from
608/// outlined region, we split these PHIs on two: one with inputs from region
609/// and other with remaining incoming blocks; then first PHIs are placed in
610/// outlined region.
611void CodeExtractor::severSplitPHINodesOfExits(
612 const SmallPtrSetImpl<BasicBlock *> &Exits) {
613 for (BasicBlock *ExitBB : Exits) {
614 BasicBlock *NewBB = nullptr;
615
616 for (PHINode &PN : ExitBB->phis()) {
617 // Find all incoming values from the outlining region.
618 SmallVector<unsigned, 2> IncomingVals;
619 for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i)
620 if (Blocks.count(PN.getIncomingBlock(i)))
621 IncomingVals.push_back(i);
622
623 // Do not process PHI if there is one (or fewer) predecessor from region.
624 // If PHI has exactly one predecessor from region, only this one incoming
625 // will be replaced on codeRepl block, so it should be safe to skip PHI.
626 if (IncomingVals.size() <= 1)
627 continue;
628
629 // Create block for new PHIs and add it to the list of outlined if it
630 // wasn't done before.
631 if (!NewBB) {
632 NewBB = BasicBlock::Create(ExitBB->getContext(),
633 ExitBB->getName() + ".split",
634 ExitBB->getParent(), ExitBB);
635 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBB),
636 pred_end(ExitBB));
637 for (BasicBlock *PredBB : Preds)
638 if (Blocks.count(PredBB))
639 PredBB->getTerminator()->replaceUsesOfWith(ExitBB, NewBB);
640 BranchInst::Create(ExitBB, NewBB);
641 Blocks.insert(NewBB);
642 }
643
644 // Split this PHI.
645 PHINode *NewPN =
646 PHINode::Create(PN.getType(), IncomingVals.size(),
647 PN.getName() + ".ce", NewBB->getFirstNonPHI());
648 for (unsigned i : IncomingVals)
649 NewPN->addIncoming(PN.getIncomingValue(i), PN.getIncomingBlock(i));
650 for (unsigned i : reverse(IncomingVals))
651 PN.removeIncomingValue(i, false);
652 PN.addIncoming(NewPN, NewBB);
653 }
654 }
655}
656
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000657void CodeExtractor::splitReturnBlocks() {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000658 for (BasicBlock *Block : Blocks)
659 if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000660 BasicBlock *New =
Benjamin Kramer135f7352016-06-26 12:28:59 +0000661 Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000662 if (DT) {
Gabor Greif2f5f6962010-09-10 22:25:58 +0000663 // Old dominates New. New node dominates all other nodes dominated
664 // by Old.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000665 DomTreeNode *OldNode = DT->getNode(Block);
666 SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
667 OldNode->end());
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000668
Benjamin Kramer135f7352016-06-26 12:28:59 +0000669 DomTreeNode *NewNode = DT->addNewBlock(New, Block);
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000670
Benjamin Kramer135f7352016-06-26 12:28:59 +0000671 for (DomTreeNode *I : Children)
672 DT->changeImmediateDominator(I, NewNode);
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000673 }
674 }
Chris Lattner3b2917b2004-05-12 06:01:40 +0000675}
676
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000677/// constructFunction - make a function based on inputs and outputs, as follows:
678/// f(in0, ..., inN, out0, ..., outN)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000679Function *CodeExtractor::constructFunction(const ValueSet &inputs,
680 const ValueSet &outputs,
Chris Lattner320d59f2004-03-18 05:28:49 +0000681 BasicBlock *header,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000682 BasicBlock *newRootNode,
683 BasicBlock *newHeader,
Chris Lattner320d59f2004-03-18 05:28:49 +0000684 Function *oldFunction,
685 Module *M) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000686 LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
687 LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000688
689 // This function returns unsigned, outputs will go back by reference.
Chris Lattnerffc49262004-05-12 04:14:24 +0000690 switch (NumExitBlocks) {
691 case 0:
Owen Anderson55f1c092009-08-13 21:58:54 +0000692 case 1: RetTy = Type::getVoidTy(header->getContext()); break;
693 case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
694 default: RetTy = Type::getInt16Ty(header->getContext()); break;
Chris Lattnerffc49262004-05-12 04:14:24 +0000695 }
696
Eugene Zelenko286d5892017-10-11 21:41:43 +0000697 std::vector<Type *> paramTy;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000698
699 // Add the types of the input values to the function's argument list
Benjamin Kramer135f7352016-06-26 12:28:59 +0000700 for (Value *value : inputs) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000701 LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000702 paramTy.push_back(value->getType());
703 }
704
Chris Lattner37de2572004-03-18 03:49:40 +0000705 // Add the types of the output values to the function's argument list.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000706 for (Value *output : outputs) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000707 LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000708 if (AggregateArgs)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000709 paramTy.push_back(output->getType());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000710 else
Benjamin Kramer135f7352016-06-26 12:28:59 +0000711 paramTy.push_back(PointerType::getUnqual(output->getType()));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000712 }
713
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000714 LLVM_DEBUG({
Benjamin Kramer706e48832016-06-26 13:39:33 +0000715 dbgs() << "Function type: " << *RetTy << " f(";
716 for (Type *i : paramTy)
717 dbgs() << *i << ", ";
718 dbgs() << ")\n";
719 });
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000720
David Blaikie741c8f82015-03-14 01:53:18 +0000721 StructType *StructTy;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000722 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
David Blaikie741c8f82015-03-14 01:53:18 +0000723 StructTy = StructType::get(M->getContext(), paramTy);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000724 paramTy.clear();
David Blaikie741c8f82015-03-14 01:53:18 +0000725 paramTy.push_back(PointerType::getUnqual(StructTy));
Misha Brukman3596f0a2004-04-23 23:54:17 +0000726 }
Chris Lattner229907c2011-07-18 04:54:35 +0000727 FunctionType *funcType =
Florian Hahn0e9dec62017-11-13 10:35:52 +0000728 FunctionType::get(RetTy, paramTy,
729 AllowVarArgs && oldFunction->isVarArg());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000730
Teresa Johnsonc8dba682018-10-24 18:53:47 +0000731 std::string SuffixToUse =
732 Suffix.empty()
733 ? (header->getName().empty() ? "extracted" : header->getName().str())
734 : Suffix;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000735 // Create the new function
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +0000736 Function *newFunction = Function::Create(
737 funcType, GlobalValue::InternalLinkage, oldFunction->getAddressSpace(),
Teresa Johnsonc8dba682018-10-24 18:53:47 +0000738 oldFunction->getName() + "." + SuffixToUse, M);
Chris Lattner4caf5eb2008-12-18 05:52:56 +0000739 // If the old function is no-throw, so is the new one.
740 if (oldFunction->doesNotThrow())
Bill Wendlingf319e992012-10-10 03:12:49 +0000741 newFunction->setDoesNotThrow();
Sean Silvaa0a802a2016-08-01 03:15:32 +0000742
743 // Inherit the uwtable attribute if we need to.
744 if (oldFunction->hasUWTable())
745 newFunction->setHasUWTable();
746
Florian Hahn55be37e2018-01-07 11:22:25 +0000747 // Inherit all of the target dependent attributes and white-listed
748 // target independent attributes.
Sean Silvaa0a802a2016-08-01 03:15:32 +0000749 // (e.g. If the extracted region contains a call to an x86.sse
750 // instruction we need to make sure that the extracted region has the
751 // "target-features" attribute allowing it to be lowered.
752 // FIXME: This should be changed to check to see if a specific
753 // attribute can not be inherited.
Florian Hahn55be37e2018-01-07 11:22:25 +0000754 for (const auto &Attr : oldFunction->getAttributes().getFnAttributes()) {
755 if (Attr.isStringAttribute()) {
756 if (Attr.getKindAsString() == "thunk")
757 continue;
758 } else
759 switch (Attr.getKindAsEnum()) {
760 // Those attributes cannot be propagated safely. Explicitly list them
761 // here so we get a warning if new attributes are added. This list also
762 // includes non-function attributes.
763 case Attribute::Alignment:
764 case Attribute::AllocSize:
765 case Attribute::ArgMemOnly:
766 case Attribute::Builtin:
767 case Attribute::ByVal:
768 case Attribute::Convergent:
769 case Attribute::Dereferenceable:
770 case Attribute::DereferenceableOrNull:
771 case Attribute::InAlloca:
772 case Attribute::InReg:
773 case Attribute::InaccessibleMemOnly:
774 case Attribute::InaccessibleMemOrArgMemOnly:
775 case Attribute::JumpTable:
776 case Attribute::Naked:
777 case Attribute::Nest:
778 case Attribute::NoAlias:
779 case Attribute::NoBuiltin:
780 case Attribute::NoCapture:
781 case Attribute::NoReturn:
782 case Attribute::None:
783 case Attribute::NonNull:
784 case Attribute::ReadNone:
785 case Attribute::ReadOnly:
786 case Attribute::Returned:
787 case Attribute::ReturnsTwice:
788 case Attribute::SExt:
789 case Attribute::Speculatable:
790 case Attribute::StackAlignment:
791 case Attribute::StructRet:
792 case Attribute::SwiftError:
793 case Attribute::SwiftSelf:
794 case Attribute::WriteOnly:
795 case Attribute::ZExt:
796 case Attribute::EndAttrKinds:
797 continue;
798 // Those attributes should be safe to propagate to the extracted function.
799 case Attribute::AlwaysInline:
800 case Attribute::Cold:
801 case Attribute::NoRecurse:
802 case Attribute::InlineHint:
803 case Attribute::MinSize:
804 case Attribute::NoDuplicate:
805 case Attribute::NoImplicitFloat:
806 case Attribute::NoInline:
807 case Attribute::NonLazyBind:
808 case Attribute::NoRedZone:
809 case Attribute::NoUnwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +0000810 case Attribute::OptForFuzzing:
Florian Hahn55be37e2018-01-07 11:22:25 +0000811 case Attribute::OptimizeNone:
812 case Attribute::OptimizeForSize:
813 case Attribute::SafeStack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +0000814 case Attribute::ShadowCallStack:
Florian Hahn55be37e2018-01-07 11:22:25 +0000815 case Attribute::SanitizeAddress:
816 case Attribute::SanitizeMemory:
817 case Attribute::SanitizeThread:
818 case Attribute::SanitizeHWAddress:
Chandler Carruth664aa862018-09-04 12:38:00 +0000819 case Attribute::SpeculativeLoadHardening:
Florian Hahn55be37e2018-01-07 11:22:25 +0000820 case Attribute::StackProtect:
821 case Attribute::StackProtectReq:
822 case Attribute::StackProtectStrong:
823 case Attribute::StrictFP:
824 case Attribute::UWTable:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +0000825 case Attribute::NoCfCheck:
Florian Hahn55be37e2018-01-07 11:22:25 +0000826 break;
827 }
Sean Silvaa0a802a2016-08-01 03:15:32 +0000828
Florian Hahn55be37e2018-01-07 11:22:25 +0000829 newFunction->addFnAttr(Attr);
830 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000831 newFunction->getBasicBlockList().push_back(newRootNode);
832
Chris Lattner37de2572004-03-18 03:49:40 +0000833 // Create an iterator to name all of the arguments we inserted.
Chris Lattner531f9e92005-03-15 04:54:21 +0000834 Function::arg_iterator AI = newFunction->arg_begin();
Chris Lattner37de2572004-03-18 03:49:40 +0000835
836 // Rewrite all users of the inputs in the extracted region to use the
Misha Brukman3596f0a2004-04-23 23:54:17 +0000837 // arguments (or appropriate addressing into struct) instead.
838 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
839 Value *RewriteVal;
840 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000841 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000842 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
843 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
Chandler Carruthedb12a82018-10-15 10:04:59 +0000844 Instruction *TI = newFunction->begin()->getTerminator();
David Blaikie741c8f82015-03-14 01:53:18 +0000845 GetElementPtrInst *GEP = GetElementPtrInst::Create(
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000846 StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI);
Daniel Dunbar123686852009-07-24 08:24:36 +0000847 RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000848 } else
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000849 RewriteVal = &*AI++;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000850
Eugene Zelenko286d5892017-10-11 21:41:43 +0000851 std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end());
Benjamin Kramer135f7352016-06-26 12:28:59 +0000852 for (User *use : Users)
853 if (Instruction *inst = dyn_cast<Instruction>(use))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000854 if (Blocks.count(inst->getParent()))
Misha Brukman3596f0a2004-04-23 23:54:17 +0000855 inst->replaceUsesOfWith(inputs[i], RewriteVal);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000856 }
857
Misha Brukman3596f0a2004-04-23 23:54:17 +0000858 // Set names for input and output arguments.
859 if (!AggregateArgs) {
Chris Lattner531f9e92005-03-15 04:54:21 +0000860 AI = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000861 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
Owen Anderson7629b712008-04-14 17:38:21 +0000862 AI->setName(inputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000863 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
Misha Brukmanb1c93172005-04-21 23:48:37 +0000864 AI->setName(outputs[i]->getName()+".out");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000865 }
Chris Lattner37de2572004-03-18 03:49:40 +0000866
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000867 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
868 // within the new function. This must be done before we lose track of which
869 // blocks were originally in the code region.
Eugene Zelenko286d5892017-10-11 21:41:43 +0000870 std::vector<User *> Users(header->user_begin(), header->user_end());
Chris Lattner320d59f2004-03-18 05:28:49 +0000871 for (unsigned i = 0, e = Users.size(); i != e; ++i)
872 // The BasicBlock which contains the branch is not in the region
873 // modify the branch target to a new block
Chandler Carruth8b7a8122018-10-18 00:38:54 +0000874 if (Instruction *I = dyn_cast<Instruction>(Users[i]))
875 if (I->isTerminator() && !Blocks.count(I->getParent()) &&
876 I->getParent()->getParent() == oldFunction)
877 I->replaceUsesOfWith(header, newHeader);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000878
879 return newFunction;
880}
881
Vedant Kumar17d9f142019-01-19 02:37:59 +0000882/// Scan the extraction region for lifetime markers which reference inputs.
883/// Erase these markers. Return the inputs which were referenced.
884///
885/// The extraction region is defined by a set of blocks (\p Blocks), and a set
886/// of allocas which will be moved from the caller function into the extracted
887/// function (\p SunkAllocas).
888static SetVector<Value *>
889eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock *> &Blocks,
890 const SetVector<Value *> &SunkAllocas) {
891 SetVector<Value *> InputObjectsWithLifetime;
892 for (BasicBlock *BB : Blocks) {
893 for (auto It = BB->begin(), End = BB->end(); It != End;) {
894 auto *II = dyn_cast<IntrinsicInst>(&*It);
895 ++It;
896 if (!II || !II->isLifetimeStartOrEnd())
897 continue;
898
899 // Get the memory operand of the lifetime marker. If the underlying
900 // object is a sunk alloca, or is otherwise defined in the extraction
901 // region, the lifetime marker must not be erased.
902 Value *Mem = II->getOperand(1)->stripInBoundsOffsets();
903 if (SunkAllocas.count(Mem) || definedInRegion(Blocks, Mem))
904 continue;
905
906 InputObjectsWithLifetime.insert(Mem);
907 II->eraseFromParent();
908 }
909 }
910 return InputObjectsWithLifetime;
911}
912
913/// Insert lifetime start/end markers surrounding the call to the new function
914/// for objects defined in the caller.
915static void insertLifetimeMarkersSurroundingCall(Module *M,
916 ArrayRef<Value *> Objects,
917 CallInst *TheCall) {
918 if (Objects.empty())
919 return;
920
921 LLVMContext &Ctx = M->getContext();
922 auto Int8PtrTy = Type::getInt8PtrTy(Ctx);
923 auto NegativeOne = ConstantInt::getSigned(Type::getInt64Ty(Ctx), -1);
924 auto StartFn = llvm::Intrinsic::getDeclaration(
925 M, llvm::Intrinsic::lifetime_start, Int8PtrTy);
926 auto EndFn = llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::lifetime_end,
927 Int8PtrTy);
928 Instruction *Term = TheCall->getParent()->getTerminator();
929 for (Value *Mem : Objects) {
930 assert((!isa<Instruction>(Mem) ||
931 cast<Instruction>(Mem)->getFunction() == TheCall->getFunction()) &&
932 "Input memory not defined in original function");
933 Value *MemAsI8Ptr = nullptr;
934 if (Mem->getType() == Int8PtrTy)
935 MemAsI8Ptr = Mem;
936 else
937 MemAsI8Ptr =
938 CastInst::CreatePointerCast(Mem, Int8PtrTy, "lt.cast", TheCall);
939
940 auto StartMarker = CallInst::Create(StartFn, {NegativeOne, MemAsI8Ptr});
941 StartMarker->insertBefore(TheCall);
942 auto EndMarker = CallInst::Create(EndFn, {NegativeOne, MemAsI8Ptr});
943 EndMarker->insertBefore(Term);
944 }
945}
946
Chris Lattner3b2917b2004-05-12 06:01:40 +0000947/// emitCallAndSwitchStatement - This method sets up the caller side by adding
948/// the call instruction, splitting any PHI nodes in the header block as
949/// necessary.
Vedant Kumara1778df2019-01-04 17:43:22 +0000950CallInst *CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,
951 BasicBlock *codeReplacer,
952 ValueSet &inputs,
953 ValueSet &outputs) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000954 // Emit a call to the new function, passing in: *pointer to struct (if
955 // aggregating parameters), or plan inputs and allocated memory for outputs
Eugene Zelenko286d5892017-10-11 21:41:43 +0000956 std::vector<Value *> params, StructValues, ReloadOutputs, Reloads;
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000957
958 Module *M = newFunction->getParent();
959 LLVMContext &Context = M->getContext();
960 const DataLayout &DL = M->getDataLayout();
Vedant Kumara1778df2019-01-04 17:43:22 +0000961 CallInst *call = nullptr;
Chris Lattnerd8017a32004-03-18 04:12:05 +0000962
Misha Brukman3596f0a2004-04-23 23:54:17 +0000963 // Add inputs as params, or to be filled into the struct
Benjamin Kramer135f7352016-06-26 12:28:59 +0000964 for (Value *input : inputs)
Misha Brukman3596f0a2004-04-23 23:54:17 +0000965 if (AggregateArgs)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000966 StructValues.push_back(input);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000967 else
Benjamin Kramer135f7352016-06-26 12:28:59 +0000968 params.push_back(input);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000969
970 // Create allocas for the outputs
Benjamin Kramer135f7352016-06-26 12:28:59 +0000971 for (Value *output : outputs) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000972 if (AggregateArgs) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000973 StructValues.push_back(output);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000974 } else {
975 AllocaInst *alloca =
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000976 new AllocaInst(output->getType(), DL.getAllocaAddrSpace(),
977 nullptr, output->getName() + ".loc",
978 &codeReplacer->getParent()->front().front());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000979 ReloadOutputs.push_back(alloca);
980 params.push_back(alloca);
981 }
982 }
983
David Blaikie741c8f82015-03-14 01:53:18 +0000984 StructType *StructArgTy = nullptr;
Craig Topperf40110f2014-04-25 05:29:35 +0000985 AllocaInst *Struct = nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000986 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
Eugene Zelenko286d5892017-10-11 21:41:43 +0000987 std::vector<Type *> ArgTypes;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000988 for (ValueSet::iterator v = StructValues.begin(),
Misha Brukman3596f0a2004-04-23 23:54:17 +0000989 ve = StructValues.end(); v != ve; ++v)
990 ArgTypes.push_back((*v)->getType());
991
992 // Allocate a struct at the beginning of this function
David Blaikie741c8f82015-03-14 01:53:18 +0000993 StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000994 Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr,
995 "structArg",
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000996 &codeReplacer->getParent()->front().front());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000997 params.push_back(Struct);
998
999 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
David Greenec656cbb2007-09-04 15:46:09 +00001000 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +00001001 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
1002 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
David Blaikie741c8f82015-03-14 01:53:18 +00001003 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1004 StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +00001005 codeReplacer->getInstList().push_back(GEP);
1006 StoreInst *SI = new StoreInst(StructValues[i], GEP);
1007 codeReplacer->getInstList().push_back(SI);
1008 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001009 }
Misha Brukman3596f0a2004-04-23 23:54:17 +00001010
1011 // Emit the call to the function
Vedant Kumara1778df2019-01-04 17:43:22 +00001012 call = CallInst::Create(newFunction, params,
1013 NumExitBlocks > 1 ? "targetBlock" : "");
Florian Hahne5089e22017-12-08 21:49:03 +00001014 // Add debug location to the new call, if the original function has debug
1015 // info. In that case, the terminator of the entry block of the extracted
1016 // function contains the first debug location of the extracted function,
1017 // set in extractCodeRegion.
1018 if (codeReplacer->getParent()->getSubprogram()) {
1019 if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc())
1020 call->setDebugLoc(DL);
1021 }
Misha Brukman3596f0a2004-04-23 23:54:17 +00001022 codeReplacer->getInstList().push_back(call);
1023
Chris Lattner531f9e92005-03-15 04:54:21 +00001024 Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +00001025 unsigned FirstOut = inputs.size();
1026 if (!AggregateArgs)
1027 std::advance(OutputArgBegin, inputs.size());
1028
Jakub Kuderskicbe9fae2017-10-06 03:37:06 +00001029 // Reload the outputs passed in by reference.
1030 Function::arg_iterator OAI = OutputArgBegin;
Misha Brukman3596f0a2004-04-23 23:54:17 +00001031 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +00001032 Value *Output = nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +00001033 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +00001034 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +00001035 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
1036 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
David Blaikie741c8f82015-03-14 01:53:18 +00001037 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1038 StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +00001039 codeReplacer->getInstList().push_back(GEP);
1040 Output = GEP;
1041 } else {
1042 Output = ReloadOutputs[i];
1043 }
1044 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
Owen Anderson34e61482009-08-25 00:54:39 +00001045 Reloads.push_back(load);
Chris Lattner37de2572004-03-18 03:49:40 +00001046 codeReplacer->getInstList().push_back(load);
Eugene Zelenko286d5892017-10-11 21:41:43 +00001047 std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end());
Chris Lattner37de2572004-03-18 03:49:40 +00001048 for (unsigned u = 0, e = Users.size(); u != e; ++u) {
1049 Instruction *inst = cast<Instruction>(Users[u]);
Chandler Carruth0fde0012012-05-04 10:18:49 +00001050 if (!Blocks.count(inst->getParent()))
Chris Lattner37de2572004-03-18 03:49:40 +00001051 inst->replaceUsesOfWith(outputs[i], load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001052 }
Jakub Kuderskicbe9fae2017-10-06 03:37:06 +00001053
1054 // Store to argument right after the definition of output value.
1055 auto *OutI = dyn_cast<Instruction>(outputs[i]);
1056 if (!OutI)
1057 continue;
Florian Hahn7cdf52e2018-08-21 20:07:46 +00001058
Jakub Kuderskicbe9fae2017-10-06 03:37:06 +00001059 // Find proper insertion point.
Vedant Kumarb2a6f8e2018-12-07 03:01:54 +00001060 BasicBlock::iterator InsertPt;
Florian Hahn7cdf52e2018-08-21 20:07:46 +00001061 // In case OutI is an invoke, we insert the store at the beginning in the
1062 // 'normal destination' BB. Otherwise we insert the store right after OutI.
1063 if (auto *InvokeI = dyn_cast<InvokeInst>(OutI))
Vedant Kumarb2a6f8e2018-12-07 03:01:54 +00001064 InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt();
1065 else if (auto *Phi = dyn_cast<PHINode>(OutI))
1066 InsertPt = Phi->getParent()->getFirstInsertionPt();
Florian Hahn7cdf52e2018-08-21 20:07:46 +00001067 else
Vedant Kumarb2a6f8e2018-12-07 03:01:54 +00001068 InsertPt = std::next(OutI->getIterator());
Jakub Kuderskicbe9fae2017-10-06 03:37:06 +00001069
1070 assert(OAI != newFunction->arg_end() &&
1071 "Number of output arguments should match "
1072 "the amount of defined values");
1073 if (AggregateArgs) {
1074 Value *Idx[2];
1075 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
1076 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
1077 GetElementPtrInst *GEP = GetElementPtrInst::Create(
Vedant Kumarb2a6f8e2018-12-07 03:01:54 +00001078 StructArgTy, &*OAI, Idx, "gep_" + outputs[i]->getName(), &*InsertPt);
1079 new StoreInst(outputs[i], GEP, &*InsertPt);
Jakub Kuderskicbe9fae2017-10-06 03:37:06 +00001080 // Since there should be only one struct argument aggregating
1081 // all the output values, we shouldn't increment OAI, which always
1082 // points to the struct argument, in this case.
1083 } else {
Vedant Kumarb2a6f8e2018-12-07 03:01:54 +00001084 new StoreInst(outputs[i], &*OAI, &*InsertPt);
Jakub Kuderskicbe9fae2017-10-06 03:37:06 +00001085 ++OAI;
1086 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001087 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +00001088
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001089 // Now we can emit a switch statement using the call as a value.
Chris Lattnerffc49262004-05-12 04:14:24 +00001090 SwitchInst *TheSwitch =
Owen Anderson55f1c092009-08-13 21:58:54 +00001091 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
Gabor Greife9ecc682008-04-06 20:25:17 +00001092 codeReplacer, 0, codeReplacer);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001093
1094 // Since there may be multiple exits from the original region, make the new
Chris Lattnerb4d8bf32004-03-14 23:05:49 +00001095 // function return an unsigned, switch on that number. This loop iterates
1096 // over all of the blocks in the extracted region, updating any terminator
1097 // instructions in the to-be-extracted region that branch to blocks that are
1098 // not in the region to be extracted.
Eugene Zelenko286d5892017-10-11 21:41:43 +00001099 std::map<BasicBlock *, BasicBlock *> ExitBlockMap;
Chris Lattnerb4d8bf32004-03-14 23:05:49 +00001100
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001101 unsigned switchVal = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001102 for (BasicBlock *Block : Blocks) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001103 Instruction *TI = Block->getTerminator();
Chris Lattnerb4d8bf32004-03-14 23:05:49 +00001104 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +00001105 if (!Blocks.count(TI->getSuccessor(i))) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +00001106 BasicBlock *OldTarget = TI->getSuccessor(i);
1107 // add a new basic block which returns the appropriate value
1108 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
1109 if (!NewTarget) {
1110 // If we don't already have an exit stub for this non-extracted
1111 // destination, create one now!
Owen Anderson55f1c092009-08-13 21:58:54 +00001112 NewTarget = BasicBlock::Create(Context,
1113 OldTarget->getName() + ".exitStub",
Gabor Greife9ecc682008-04-06 20:25:17 +00001114 newFunction);
Chris Lattnerffc49262004-05-12 04:14:24 +00001115 unsigned SuccNum = switchVal++;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001116
Craig Topperf40110f2014-04-25 05:29:35 +00001117 Value *brVal = nullptr;
Chris Lattnerffc49262004-05-12 04:14:24 +00001118 switch (NumExitBlocks) {
1119 case 0:
1120 case 1: break; // No value needed.
1121 case 2: // Conditional branch, return a bool
Owen Anderson55f1c092009-08-13 21:58:54 +00001122 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +00001123 break;
1124 default:
Owen Anderson55f1c092009-08-13 21:58:54 +00001125 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +00001126 break;
1127 }
1128
Jakub Kuderskicbe9fae2017-10-06 03:37:06 +00001129 ReturnInst::Create(Context, brVal, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001130
Chris Lattnerb4d8bf32004-03-14 23:05:49 +00001131 // Update the switch instruction.
Owen Anderson55f1c092009-08-13 21:58:54 +00001132 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
1133 SuccNum),
Chris Lattnerffc49262004-05-12 04:14:24 +00001134 OldTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001135 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +00001136
1137 // rewrite the original branch instruction with this new target
1138 TI->setSuccessor(i, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001139 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001140 }
Chris Lattner5b2072e2004-03-14 23:43:24 +00001141
Chris Lattner3d1ca672004-05-12 03:22:33 +00001142 // Now that we've done the deed, simplify the switch instruction.
Chris Lattner229907c2011-07-18 04:54:35 +00001143 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
Chris Lattnerffc49262004-05-12 04:14:24 +00001144 switch (NumExitBlocks) {
1145 case 0:
Chris Lattner7f1c7ed2004-08-12 03:17:02 +00001146 // There are no successors (the block containing the switch itself), which
Misha Brukman3596f0a2004-04-23 23:54:17 +00001147 // means that previously this was the last part of the function, and hence
1148 // this should be rewritten as a `ret'
Misha Brukmanb1c93172005-04-21 23:48:37 +00001149
Misha Brukman3596f0a2004-04-23 23:54:17 +00001150 // Check if the function should return a value
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001151 if (OldFnRetTy->isVoidTy()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001152 ReturnInst::Create(Context, nullptr, TheSwitch); // Return void
Chris Lattner7f1c7ed2004-08-12 03:17:02 +00001153 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
Misha Brukman3596f0a2004-04-23 23:54:17 +00001154 // return what we have
Owen Anderson55f1c092009-08-13 21:58:54 +00001155 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +00001156 } else {
1157 // Otherwise we must have code extracted an unwind or something, just
1158 // return whatever we want.
Fangrui Songf78650a2018-07-30 19:41:25 +00001159 ReturnInst::Create(Context,
Owen Anderson55f1c092009-08-13 21:58:54 +00001160 Constant::getNullValue(OldFnRetTy), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +00001161 }
Misha Brukman3596f0a2004-04-23 23:54:17 +00001162
Dan Gohman158ff2c2008-06-21 22:08:46 +00001163 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +00001164 break;
1165 case 1:
1166 // Only a single destination, change the switch into an unconditional
1167 // branch.
Gabor Greife9ecc682008-04-06 20:25:17 +00001168 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +00001169 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +00001170 break;
1171 case 2:
Gabor Greife9ecc682008-04-06 20:25:17 +00001172 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
1173 call, TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +00001174 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +00001175 break;
1176 default:
1177 // Otherwise, make the default destination of the switch instruction be one
1178 // of the other successors.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001179 TheSwitch->setCondition(call);
1180 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001181 // Remove redundant case
Bob Wilsone4077362013-09-09 19:14:35 +00001182 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
Chris Lattnerffc49262004-05-12 04:14:24 +00001183 break;
Chris Lattner5b2072e2004-03-14 23:43:24 +00001184 }
Vedant Kumara1778df2019-01-04 17:43:22 +00001185
Vedant Kumar17d9f142019-01-19 02:37:59 +00001186 // Insert lifetime markers around the reloads of any output values. The
1187 // allocas output values are stored in are only in-use in the codeRepl block.
1188 insertLifetimeMarkersSurroundingCall(M, ReloadOutputs, call);
1189
Vedant Kumara1778df2019-01-04 17:43:22 +00001190 return call;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001191}
1192
Chris Lattner3b2917b2004-05-12 06:01:40 +00001193void CodeExtractor::moveCodeToFunction(Function *newFunction) {
Chandler Carruth0fde0012012-05-04 10:18:49 +00001194 Function *oldFunc = (*Blocks.begin())->getParent();
Chris Lattner3b2917b2004-05-12 06:01:40 +00001195 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
1196 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
1197
Benjamin Kramer135f7352016-06-26 12:28:59 +00001198 for (BasicBlock *Block : Blocks) {
Chris Lattner3b2917b2004-05-12 06:01:40 +00001199 // Delete the basic block from the old function, and the list of blocks
Benjamin Kramer135f7352016-06-26 12:28:59 +00001200 oldBlocks.remove(Block);
Chris Lattner3b2917b2004-05-12 06:01:40 +00001201
1202 // Insert this basic block into the new function
Benjamin Kramer135f7352016-06-26 12:28:59 +00001203 newBlocks.push_back(Block);
Chris Lattner3b2917b2004-05-12 06:01:40 +00001204 }
1205}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001206
Sean Silvaf8015752016-08-02 02:15:45 +00001207void CodeExtractor::calculateNewCallTerminatorWeights(
1208 BasicBlock *CodeReplacer,
1209 DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
1210 BranchProbabilityInfo *BPI) {
Eugene Zelenko286d5892017-10-11 21:41:43 +00001211 using Distribution = BlockFrequencyInfoImplBase::Distribution;
1212 using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
Sean Silvaf8015752016-08-02 02:15:45 +00001213
1214 // Update the branch weights for the exit block.
Chandler Carruthedb12a82018-10-15 10:04:59 +00001215 Instruction *TI = CodeReplacer->getTerminator();
Sean Silvaf8015752016-08-02 02:15:45 +00001216 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
1217
1218 // Block Frequency distribution with dummy node.
1219 Distribution BranchDist;
1220
1221 // Add each of the frequencies of the successors.
1222 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
1223 BlockNode ExitNode(i);
1224 uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency();
1225 if (ExitFreq != 0)
1226 BranchDist.addExit(ExitNode, ExitFreq);
1227 else
1228 BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero());
1229 }
1230
1231 // Check for no total weight.
1232 if (BranchDist.Total == 0)
1233 return;
1234
1235 // Normalize the distribution so that they can fit in unsigned.
1236 BranchDist.normalize();
1237
1238 // Create normalized branch weights and set the metadata.
1239 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
1240 const auto &Weight = BranchDist.Weights[I];
1241
1242 // Get the weight and update the current BFI.
1243 BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
1244 BranchProbability BP(Weight.Amount, BranchDist.Total);
1245 BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP);
1246 }
1247 TI->setMetadata(
1248 LLVMContext::MD_prof,
1249 MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));
1250}
1251
Chandler Carruth0fde0012012-05-04 10:18:49 +00001252Function *CodeExtractor::extractCodeRegion() {
1253 if (!isEligible())
Craig Topperf40110f2014-04-25 05:29:35 +00001254 return nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +00001255
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001256 // Assumption: this is a single-entry code region, and the header is the first
Chris Lattner73ab1fa2004-03-15 01:18:23 +00001257 // block in the region.
Chandler Carruth0fde0012012-05-04 10:18:49 +00001258 BasicBlock *header = *Blocks.begin();
Florian Hahn0e9dec62017-11-13 10:35:52 +00001259 Function *oldFunction = header->getParent();
1260
1261 // For functions with varargs, check that varargs handling is only done in the
1262 // outlined function, i.e vastart and vaend are only used in outlined blocks.
1263 if (AllowVarArgs && oldFunction->getFunctionType()->isVarArg()) {
1264 auto containsVarArgIntrinsic = [](Instruction &I) {
1265 if (const CallInst *CI = dyn_cast<CallInst>(&I))
1266 if (const Function *F = CI->getCalledFunction())
1267 return F->getIntrinsicID() == Intrinsic::vastart ||
1268 F->getIntrinsicID() == Intrinsic::vaend;
1269 return false;
1270 };
1271
1272 for (auto &BB : *oldFunction) {
1273 if (Blocks.count(&BB))
1274 continue;
1275 if (llvm::any_of(BB, containsVarArgIntrinsic))
1276 return nullptr;
1277 }
1278 }
1279 ValueSet inputs, outputs, SinkingCands, HoistingCands;
1280 BasicBlock *CommonExit = nullptr;
Chris Lattner3b2917b2004-05-12 06:01:40 +00001281
Sean Silvaf8015752016-08-02 02:15:45 +00001282 // Calculate the entry frequency of the new function before we change the root
1283 // block.
1284 BlockFrequency EntryFreq;
1285 if (BFI) {
1286 assert(BPI && "Both BPI and BFI are required to preserve profile info");
1287 for (BasicBlock *Pred : predecessors(header)) {
1288 if (Blocks.count(Pred))
1289 continue;
1290 EntryFreq +=
1291 BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);
1292 }
1293 }
1294
Chris Lattner13d2ddf2004-05-12 16:07:41 +00001295 // If we have any return instructions in the region, split those blocks so
1296 // that the return is not in the region.
1297 splitReturnBlocks();
1298
Vedant Kumard1295692018-12-03 22:40:21 +00001299 // Calculate the exit blocks for the extracted region and the total exit
1300 // weights for each of those blocks.
1301 DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
1302 SmallPtrSet<BasicBlock *, 1> ExitBlocks;
1303 for (BasicBlock *Block : Blocks) {
1304 for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE;
1305 ++SI) {
1306 if (!Blocks.count(*SI)) {
1307 // Update the branch weight for this successor.
1308 if (BFI) {
1309 BlockFrequency &BF = ExitWeights[*SI];
1310 BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI);
1311 }
1312 ExitBlocks.insert(*SI);
1313 }
1314 }
1315 }
1316 NumExitBlocks = ExitBlocks.size();
1317
1318 // If we have to split PHI nodes of the entry or exit blocks, do so now.
1319 severSplitPHINodesOfEntry(header);
1320 severSplitPHINodesOfExits(ExitBlocks);
1321
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001322 // This takes place of the original loop
Fangrui Songf78650a2018-07-30 19:41:25 +00001323 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001324 "codeRepl", oldFunction,
Gabor Greif697e94c2008-05-15 10:04:30 +00001325 header);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001326
1327 // The new function needs a root node because other nodes can branch to the
Chris Lattner3b2917b2004-05-12 06:01:40 +00001328 // head of the region, but the entry node of a function cannot have preds.
Fangrui Songf78650a2018-07-30 19:41:25 +00001329 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001330 "newFuncRoot");
Florian Hahne5089e22017-12-08 21:49:03 +00001331 auto *BranchI = BranchInst::Create(header);
1332 // If the original function has debug info, we have to add a debug location
1333 // to the new branch instruction from the artificial entry block.
1334 // We use the debug location of the first instruction in the extracted
1335 // blocks, as there is no other equivalent line in the source code.
1336 if (oldFunction->getSubprogram()) {
1337 any_of(Blocks, [&BranchI](const BasicBlock *BB) {
1338 return any_of(*BB, [&BranchI](const Instruction &I) {
1339 if (!I.getDebugLoc())
1340 return false;
1341 BranchI->setDebugLoc(I.getDebugLoc());
1342 return true;
1343 });
1344 });
1345 }
1346 newFuncRoot->getInstList().push_back(BranchI);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001347
Xinliang David Li7ed6cd32017-06-11 20:46:05 +00001348 findAllocas(SinkingCands, HoistingCands, CommonExit);
1349 assert(HoistingCands.empty() || CommonExit);
Xinliang David Li74480ad2017-05-30 21:22:18 +00001350
Chris Lattner3b2917b2004-05-12 06:01:40 +00001351 // Find inputs to, outputs from the code region.
Xinliang David Li74480ad2017-05-30 21:22:18 +00001352 findInputsOutputs(inputs, outputs, SinkingCands);
1353
1354 // Now sink all instructions which only have non-phi uses inside the region
1355 for (auto *II : SinkingCands)
1356 cast<Instruction>(II)->moveBefore(*newFuncRoot,
1357 newFuncRoot->getFirstInsertionPt());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001358
Xinliang David Li7ed6cd32017-06-11 20:46:05 +00001359 if (!HoistingCands.empty()) {
1360 auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit);
1361 Instruction *TI = HoistToBlock->getTerminator();
1362 for (auto *II : HoistingCands)
1363 cast<Instruction>(II)->moveBefore(TI);
1364 }
1365
Vedant Kumara1778df2019-01-04 17:43:22 +00001366 // Collect objects which are inputs to the extraction region and also
1367 // referenced by lifetime start/end markers within it. The effects of these
1368 // markers must be replicated in the calling function to prevent the stack
1369 // coloring pass from merging slots which store input objects.
1370 ValueSet InputObjectsWithLifetime =
1371 eraseLifetimeMarkersOnInputs(Blocks, SinkingCands);
1372
Chris Lattner3b2917b2004-05-12 06:01:40 +00001373 // Construct new function based on inputs/outputs & add allocas for all defs.
Vedant Kumara1778df2019-01-04 17:43:22 +00001374 Function *newFunction =
1375 constructFunction(inputs, outputs, header, newFuncRoot, codeReplacer,
1376 oldFunction, oldFunction->getParent());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001377
Sean Silvaf8015752016-08-02 02:15:45 +00001378 // Update the entry count of the function.
1379 if (BFI) {
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001380 auto Count = BFI->getProfileCountFromFreq(EntryFreq.getFrequency());
1381 if (Count.hasValue())
1382 newFunction->setEntryCount(
1383 ProfileCount(Count.getValue(), Function::PCT_Real)); // FIXME
Sean Silvaf8015752016-08-02 02:15:45 +00001384 BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency());
1385 }
1386
Vedant Kumara1778df2019-01-04 17:43:22 +00001387 CallInst *TheCall =
1388 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001389
Chris Lattner9c431f62004-03-14 22:34:55 +00001390 moveCodeToFunction(newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001391
Vedant Kumara1778df2019-01-04 17:43:22 +00001392 // Replicate the effects of any lifetime start/end markers which referenced
1393 // input objects in the extraction region by placing markers around the call.
1394 insertLifetimeMarkersSurroundingCall(oldFunction->getParent(),
Vedant Kumar17d9f142019-01-19 02:37:59 +00001395 InputObjectsWithLifetime.getArrayRef(),
1396 TheCall);
Vedant Kumara1778df2019-01-04 17:43:22 +00001397
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +00001398 // Propagate personality info to the new function if there is one.
1399 if (oldFunction->hasPersonalityFn())
1400 newFunction->setPersonalityFn(oldFunction->getPersonalityFn());
1401
Sean Silvaf8015752016-08-02 02:15:45 +00001402 // Update the branch weights for the exit block.
1403 if (BFI && NumExitBlocks > 1)
1404 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
1405
Vedant Kumard1295692018-12-03 22:40:21 +00001406 // Loop over all of the PHI nodes in the header and exit blocks, and change
1407 // any references to the old incoming edge to be the new incoming edge.
Reid Spencer66149462004-09-15 17:06:42 +00001408 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
1409 PHINode *PN = cast<PHINode>(I);
Chris Lattner320d59f2004-03-18 05:28:49 +00001410 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +00001411 if (!Blocks.count(PN->getIncomingBlock(i)))
Chris Lattner320d59f2004-03-18 05:28:49 +00001412 PN->setIncomingBlock(i, newFuncRoot);
Reid Spencer66149462004-09-15 17:06:42 +00001413 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001414
Vedant Kumard1295692018-12-03 22:40:21 +00001415 for (BasicBlock *ExitBB : ExitBlocks)
1416 for (PHINode &PN : ExitBB->phis()) {
Vedant Kumarc2990062018-10-24 22:15:41 +00001417 Value *IncomingCodeReplacerVal = nullptr;
Vedant Kumard1295692018-12-03 22:40:21 +00001418 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Vedant Kumarc2990062018-10-24 22:15:41 +00001419 // Ignore incoming values from outside of the extracted region.
Vedant Kumard1295692018-12-03 22:40:21 +00001420 if (!Blocks.count(PN.getIncomingBlock(i)))
Vedant Kumarc2990062018-10-24 22:15:41 +00001421 continue;
1422
1423 // Ensure that there is only one incoming value from codeReplacer.
1424 if (!IncomingCodeReplacerVal) {
Vedant Kumard1295692018-12-03 22:40:21 +00001425 PN.setIncomingBlock(i, codeReplacer);
1426 IncomingCodeReplacerVal = PN.getIncomingValue(i);
1427 } else
1428 assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) &&
Vedant Kumarc2990062018-10-24 22:15:41 +00001429 "PHI has two incompatbile incoming values from codeRepl");
Vedant Kumarc2990062018-10-24 22:15:41 +00001430 }
Chris Lattner56273822004-08-13 03:27:07 +00001431 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001432
Vedant Kumar15718a62018-10-15 19:22:20 +00001433 // Erase debug info intrinsics. Variable updates within the new function are
1434 // invisible to debuggers. This could be improved by defining a DISubprogram
1435 // for the new function.
1436 for (BasicBlock &BB : *newFunction) {
1437 auto BlockIt = BB.begin();
Vedant Kumar09b7aa42018-11-06 19:05:53 +00001438 // Remove debug info intrinsics from the new function.
Vedant Kumar15718a62018-10-15 19:22:20 +00001439 while (BlockIt != BB.end()) {
1440 Instruction *Inst = &*BlockIt;
1441 ++BlockIt;
1442 if (isa<DbgInfoIntrinsic>(Inst))
1443 Inst->eraseFromParent();
1444 }
Vedant Kumar09b7aa42018-11-06 19:05:53 +00001445 // Remove debug info intrinsics which refer to values in the new function
1446 // from the old function.
1447 SmallVector<DbgVariableIntrinsic *, 4> DbgUsers;
1448 for (Instruction &I : BB)
1449 findDbgUsers(DbgUsers, &I);
1450 for (DbgVariableIntrinsic *DVI : DbgUsers)
1451 DVI->eraseFromParent();
Vedant Kumar15718a62018-10-15 19:22:20 +00001452 }
1453
Vedant Kumar09415a82018-12-05 19:35:37 +00001454 // Mark the new function `noreturn` if applicable. Terminators which resume
1455 // exception propagation are treated as returning instructions. This is to
1456 // avoid inserting traps after calls to outlined functions which unwind.
Vedant Kumard6699422018-11-08 17:57:09 +00001457 bool doesNotReturn = none_of(*newFunction, [](const BasicBlock &BB) {
Vedant Kumar09415a82018-12-05 19:35:37 +00001458 const Instruction *Term = BB.getTerminator();
1459 return isa<ReturnInst>(Term) || isa<ResumeInst>(Term);
Vedant Kumard6699422018-11-08 17:57:09 +00001460 });
1461 if (doesNotReturn)
1462 newFunction->setDoesNotReturn();
1463
Vedant Kumarb2a6f8e2018-12-07 03:01:54 +00001464 LLVM_DEBUG(if (verifyFunction(*newFunction, &errs())) {
1465 newFunction->dump();
1466 report_fatal_error("verification of newFunction failed!");
1467 });
Vedant Kumard1295692018-12-03 22:40:21 +00001468 LLVM_DEBUG(if (verifyFunction(*oldFunction))
1469 report_fatal_error("verification of oldFunction failed!"));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001470 return newFunction;
1471}