blob: 4db895feaa3434aa660f3335a84477f12aac4def [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"
Sergey Dmitriev807960e2019-02-08 06:55:18 +000023#include "llvm/Analysis/AssumptionCache.h"
Sean Silvaf8015752016-08-02 02:15:45 +000024#include "llvm/Analysis/BlockFrequencyInfo.h"
25#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
26#include "llvm/Analysis/BranchProbabilityInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/LoopInfo.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000028#include "llvm/IR/Argument.h"
29#include "llvm/IR/Attributes.h"
30#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/CFG.h"
32#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Constants.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000034#include "llvm/IR/DataLayout.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000036#include "llvm/IR/Dominators.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000037#include "llvm/IR/Function.h"
38#include "llvm/IR/GlobalValue.h"
39#include "llvm/IR/InstrTypes.h"
40#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Instructions.h"
Xinliang David Li74480ad2017-05-30 21:22:18 +000042#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Intrinsics.h"
44#include "llvm/IR/LLVMContext.h"
Sean Silvaf8015752016-08-02 02:15:45 +000045#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/Module.h"
Sergey Dmitriev807960e2019-02-08 06:55:18 +000047#include "llvm/IR/PatternMatch.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000048#include "llvm/IR/Type.h"
49#include "llvm/IR/User.h"
50#include "llvm/IR/Value.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000051#include "llvm/IR/Verifier.h"
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000052#include "llvm/Pass.h"
Sean Silvaf8015752016-08-02 02:15:45 +000053#include "llvm/Support/BlockFrequency.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000054#include "llvm/Support/BranchProbability.h"
55#include "llvm/Support/Casting.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000056#include "llvm/Support/CommandLine.h"
57#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000058#include "llvm/Support/ErrorHandling.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000059#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Vedant Kumar09b7aa42018-11-06 19:05:53 +000061#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko286d5892017-10-11 21:41:43 +000062#include <cassert>
63#include <cstdint>
64#include <iterator>
65#include <map>
Chris Lattner9c431f62004-03-14 22:34:55 +000066#include <set>
Eugene Zelenko286d5892017-10-11 21:41:43 +000067#include <utility>
68#include <vector>
69
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000070using namespace llvm;
Sergey Dmitriev807960e2019-02-08 06:55:18 +000071using namespace llvm::PatternMatch;
Easwaran Ramane5b8de22018-01-17 22:24:23 +000072using ProfileCount = Function::ProfileCount;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +000073
Chandler Carruthe96dd892014-04-21 22:55:11 +000074#define DEBUG_TYPE "code-extractor"
75
Misha Brukman3596f0a2004-04-23 23:54:17 +000076// Provide a command-line option to aggregate function arguments into a struct
Misha Brukman234b44a2008-12-13 05:21:37 +000077// for functions produced by the code extractor. This is useful when converting
Misha Brukman3596f0a2004-04-23 23:54:17 +000078// extracted functions to pthread-based code, as only one argument (void*) can
79// be passed in to pthread_create().
80static cl::opt<bool>
81AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
82 cl::desc("Aggregate arguments to code-extracted functions"));
83
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000084/// Test whether a block is valid for extraction.
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +000085static bool isBlockValidForExtraction(const BasicBlock &BB,
86 const SetVector<BasicBlock *> &Result,
87 bool AllowVarArgs, bool AllowAlloca) {
Serge Guelton7bc405a2017-06-27 18:57:53 +000088 // taking the address of a basic block moved to another function is illegal
89 if (BB.hasAddressTaken())
90 return false;
91
92 // don't hoist code that uses another basicblock address, as it's likely to
93 // lead to unexpected behavior, like cross-function jumps
94 SmallPtrSet<User const *, 16> Visited;
95 SmallVector<User const *, 16> ToVisit;
96
97 for (Instruction const &Inst : BB)
98 ToVisit.push_back(&Inst);
99
100 while (!ToVisit.empty()) {
101 User const *Curr = ToVisit.pop_back_val();
102 if (!Visited.insert(Curr).second)
103 continue;
104 if (isa<BlockAddress const>(Curr))
105 return false; // even a reference to self is likely to be not compatible
106
107 if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB)
108 continue;
109
110 for (auto const &U : Curr->operands()) {
111 if (auto *UU = dyn_cast<User>(U))
112 ToVisit.push_back(UU);
113 }
114 }
Chris Lattner37de2572004-03-18 03:49:40 +0000115
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000116 // If explicitly requested, allow vastart and alloca. For invoke instructions
117 // verify that extraction is valid.
Chandler Carruth0fde0012012-05-04 10:18:49 +0000118 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000119 if (isa<AllocaInst>(I)) {
120 if (!AllowAlloca)
121 return false;
122 continue;
123 }
124
125 if (const auto *II = dyn_cast<InvokeInst>(I)) {
126 // Unwind destination (either a landingpad, catchswitch, or cleanuppad)
127 // must be a part of the subgraph which is being extracted.
128 if (auto *UBB = II->getUnwindDest())
129 if (!Result.count(UBB))
130 return false;
131 continue;
132 }
133
134 // All catch handlers of a catchswitch instruction as well as the unwind
135 // destination must be in the subgraph.
136 if (const auto *CSI = dyn_cast<CatchSwitchInst>(I)) {
137 if (auto *UBB = CSI->getUnwindDest())
138 if (!Result.count(UBB))
139 return false;
140 for (auto *HBB : CSI->handlers())
141 if (!Result.count(const_cast<BasicBlock*>(HBB)))
142 return false;
143 continue;
144 }
145
146 // Make sure that entire catch handler is within subgraph. It is sufficient
147 // to check that catch return's block is in the list.
148 if (const auto *CPI = dyn_cast<CatchPadInst>(I)) {
149 for (const auto *U : CPI->users())
150 if (const auto *CRI = dyn_cast<CatchReturnInst>(U))
151 if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))
152 return false;
153 continue;
154 }
155
156 // And do similar checks for cleanup handler - the entire handler must be
157 // in subgraph which is going to be extracted. For cleanup return should
158 // additionally check that the unwind destination is also in the subgraph.
159 if (const auto *CPI = dyn_cast<CleanupPadInst>(I)) {
160 for (const auto *U : CPI->users())
161 if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
162 if (!Result.count(const_cast<BasicBlock*>(CRI->getParent())))
163 return false;
164 continue;
165 }
166 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I)) {
167 if (auto *UBB = CRI->getUnwindDest())
168 if (!Result.count(UBB))
169 return false;
170 continue;
171 }
172
Vedant Kumar1e209e22018-11-06 19:06:08 +0000173 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
174 if (const Function *F = CI->getCalledFunction()) {
175 auto IID = F->getIntrinsicID();
176 if (IID == Intrinsic::vastart) {
Florian Hahn0e9dec62017-11-13 10:35:52 +0000177 if (AllowVarArgs)
178 continue;
179 else
180 return false;
181 }
Vedant Kumar1e209e22018-11-06 19:06:08 +0000182
183 // Currently, we miscompile outlined copies of eh_typid_for. There are
184 // proposals for fixing this in llvm.org/PR39545.
185 if (IID == Intrinsic::eh_typeid_for)
186 return false;
187 }
188 }
Chandler Carruth0fde0012012-05-04 10:18:49 +0000189 }
190
191 return true;
192}
193
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000194/// Build a set of blocks to extract if the input blocks are viable.
Davide Italiano059574c2017-04-21 00:21:09 +0000195static SetVector<BasicBlock *>
Florian Hahn0e9dec62017-11-13 10:35:52 +0000196buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000197 bool AllowVarArgs, bool AllowAlloca) {
Davide Italianofa15de32017-04-21 04:25:00 +0000198 assert(!BBs.empty() && "The set of blocks to extract must be non-empty");
Davide Italiano059574c2017-04-21 00:21:09 +0000199 SetVector<BasicBlock *> Result;
Chandler Carruth2f5d0192012-05-04 10:26:45 +0000200
Chandler Carruth0fde0012012-05-04 10:18:49 +0000201 // Loop over the blocks, adding them to our set-vector, and aborting with an
202 // empty set if we encounter invalid blocks.
Davide Italianofa15de32017-04-21 04:25:00 +0000203 for (BasicBlock *BB : BBs) {
Davide Italianofa15de32017-04-21 04:25:00 +0000204 // If this block is dead, don't process it.
205 if (DT && !DT->isReachableFromEntry(BB))
206 continue;
207
208 if (!Result.insert(BB))
209 llvm_unreachable("Repeated basic blocks in extraction input");
Davide Italianofa15de32017-04-21 04:25:00 +0000210 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000211
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000212 for (auto *BB : Result) {
213 if (!isBlockValidForExtraction(*BB, Result, AllowVarArgs, AllowAlloca))
214 return {};
215
216 // Make sure that the first block is not a landing pad.
217 if (BB == Result.front()) {
218 if (BB->isEHPad()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000219 LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n");
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000220 return {};
221 }
222 continue;
223 }
224
225 // All blocks other than the first must not have predecessors outside of
226 // the subgraph which is being extracted.
227 for (auto *PBB : predecessors(BB))
228 if (!Result.count(PBB)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000229 LLVM_DEBUG(
230 dbgs() << "No blocks in this region may have entries from "
231 "outside the region except for the first block!\n");
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000232 return {};
233 }
234 }
Chandler Carruth2f5d0192012-05-04 10:26:45 +0000235
Chandler Carruth0fde0012012-05-04 10:18:49 +0000236 return Result;
237}
Chris Lattner3b2917b2004-05-12 06:01:40 +0000238
Chandler Carruth0fde0012012-05-04 10:18:49 +0000239CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT,
Sean Silvaf8015752016-08-02 02:15:45 +0000240 bool AggregateArgs, BlockFrequencyInfo *BFI,
Sergey Dmitriev807960e2019-02-08 06:55:18 +0000241 BranchProbabilityInfo *BPI, AssumptionCache *AC,
242 bool AllowVarArgs, bool AllowAlloca,
243 std::string Suffix)
Sean Silvaf8015752016-08-02 02:15:45 +0000244 : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
Sergey Dmitriev807960e2019-02-08 06:55:18 +0000245 BPI(BPI), AC(AC), AllowVarArgs(AllowVarArgs),
Teresa Johnsonc8dba682018-10-24 18:53:47 +0000246 Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)),
247 Suffix(Suffix) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000248
Sean Silvaf8015752016-08-02 02:15:45 +0000249CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs,
250 BlockFrequencyInfo *BFI,
Sergey Dmitriev807960e2019-02-08 06:55:18 +0000251 BranchProbabilityInfo *BPI, AssumptionCache *AC,
252 std::string Suffix)
Sean Silvaf8015752016-08-02 02:15:45 +0000253 : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI),
Sergey Dmitriev807960e2019-02-08 06:55:18 +0000254 BPI(BPI), AC(AC), AllowVarArgs(false),
Florian Hahn71147552017-11-13 11:08:47 +0000255 Blocks(buildExtractionBlockSet(L.getBlocks(), &DT,
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +0000256 /* AllowVarArgs */ false,
Teresa Johnsonc8dba682018-10-24 18:53:47 +0000257 /* AllowAlloca */ false)),
258 Suffix(Suffix) {}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000259
Chandler Carruth0fde0012012-05-04 10:18:49 +0000260/// definedInRegion - Return true if the specified value is defined in the
261/// extracted region.
262static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) {
263 if (Instruction *I = dyn_cast<Instruction>(V))
264 if (Blocks.count(I->getParent()))
265 return true;
266 return false;
267}
268
269/// definedInCaller - Return true if the specified value is defined in the
270/// function being code extracted, but not in the region being extracted.
271/// These values must be passed in as live-ins to the function.
272static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) {
273 if (isa<Argument>(V)) return true;
274 if (Instruction *I = dyn_cast<Instruction>(V))
275 if (!Blocks.count(I->getParent()))
276 return true;
277 return false;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000278}
279
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000280static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) {
281 BasicBlock *CommonExitBlock = nullptr;
282 auto hasNonCommonExitSucc = [&](BasicBlock *Block) {
283 for (auto *Succ : successors(Block)) {
284 // Internal edges, ok.
285 if (Blocks.count(Succ))
286 continue;
287 if (!CommonExitBlock) {
288 CommonExitBlock = Succ;
289 continue;
290 }
291 if (CommonExitBlock == Succ)
292 continue;
293
294 return true;
295 }
296 return false;
297 };
298
299 if (any_of(Blocks, hasNonCommonExitSucc))
300 return nullptr;
301
302 return CommonExitBlock;
303}
304
305bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers(
306 Instruction *Addr) const {
307 AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets());
Xinliang David Li74480ad2017-05-30 21:22:18 +0000308 Function *Func = (*Blocks.begin())->getParent();
309 for (BasicBlock &BB : *Func) {
310 if (Blocks.count(&BB))
311 continue;
312 for (Instruction &II : BB) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000313 if (isa<DbgInfoIntrinsic>(II))
314 continue;
315
316 unsigned Opcode = II.getOpcode();
317 Value *MemAddr = nullptr;
318 switch (Opcode) {
319 case Instruction::Store:
320 case Instruction::Load: {
321 if (Opcode == Instruction::Store) {
322 StoreInst *SI = cast<StoreInst>(&II);
323 MemAddr = SI->getPointerOperand();
324 } else {
325 LoadInst *LI = cast<LoadInst>(&II);
326 MemAddr = LI->getPointerOperand();
327 }
328 // Global variable can not be aliased with locals.
329 if (dyn_cast<Constant>(MemAddr))
330 break;
331 Value *Base = MemAddr->stripInBoundsConstantOffsets();
332 if (!dyn_cast<AllocaInst>(Base) || Base == AI)
333 return false;
334 break;
335 }
336 default: {
337 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II);
338 if (IntrInst) {
Vedant Kumarb264d692018-12-21 21:49:40 +0000339 if (IntrInst->isLifetimeStartOrEnd())
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000340 break;
341 return false;
342 }
343 // Treat all the other cases conservatively if it has side effects.
344 if (II.mayHaveSideEffects())
345 return false;
346 }
347 }
348 }
349 }
350
351 return true;
352}
353
354BasicBlock *
355CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) {
356 BasicBlock *SinglePredFromOutlineRegion = nullptr;
357 assert(!Blocks.count(CommonExitBlock) &&
358 "Expect a block outside the region!");
359 for (auto *Pred : predecessors(CommonExitBlock)) {
360 if (!Blocks.count(Pred))
361 continue;
362 if (!SinglePredFromOutlineRegion) {
363 SinglePredFromOutlineRegion = Pred;
364 } else if (SinglePredFromOutlineRegion != Pred) {
365 SinglePredFromOutlineRegion = nullptr;
366 break;
367 }
368 }
369
370 if (SinglePredFromOutlineRegion)
371 return SinglePredFromOutlineRegion;
372
373#ifndef NDEBUG
374 auto getFirstPHI = [](BasicBlock *BB) {
375 BasicBlock::iterator I = BB->begin();
376 PHINode *FirstPhi = nullptr;
377 while (I != BB->end()) {
378 PHINode *Phi = dyn_cast<PHINode>(I);
379 if (!Phi)
380 break;
381 if (!FirstPhi) {
382 FirstPhi = Phi;
383 break;
384 }
385 }
386 return FirstPhi;
387 };
388 // If there are any phi nodes, the single pred either exists or has already
389 // be created before code extraction.
390 assert(!getFirstPHI(CommonExitBlock) && "Phi not expected");
391#endif
392
393 BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock(
394 CommonExitBlock->getFirstNonPHI()->getIterator());
395
Florian Hahnb93c0632017-11-01 09:48:12 +0000396 for (auto PI = pred_begin(CommonExitBlock), PE = pred_end(CommonExitBlock);
397 PI != PE;) {
398 BasicBlock *Pred = *PI++;
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000399 if (Blocks.count(Pred))
400 continue;
401 Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock);
402 }
403 // Now add the old exit block to the outline region.
404 Blocks.insert(CommonExitBlock);
405 return CommonExitBlock;
406}
407
408void CodeExtractor::findAllocas(ValueSet &SinkCands, ValueSet &HoistCands,
409 BasicBlock *&ExitBlock) const {
410 Function *Func = (*Blocks.begin())->getParent();
411 ExitBlock = getCommonExitBlock(Blocks);
412
413 for (BasicBlock &BB : *Func) {
414 if (Blocks.count(&BB))
415 continue;
416 for (Instruction &II : BB) {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000417 auto *AI = dyn_cast<AllocaInst>(&II);
418 if (!AI)
419 continue;
420
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000421 // Find the pair of life time markers for address 'Addr' that are either
422 // defined inside the outline region or can legally be shrinkwrapped into
423 // the outline region. If there are not other untracked uses of the
424 // address, return the pair of markers if found; otherwise return a pair
425 // of nullptr.
426 auto GetLifeTimeMarkers =
427 [&](Instruction *Addr, bool &SinkLifeStart,
428 bool &HoistLifeEnd) -> std::pair<Instruction *, Instruction *> {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000429 Instruction *LifeStart = nullptr, *LifeEnd = nullptr;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000430
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000431 for (User *U : Addr->users()) {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000432 IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U);
433 if (IntrInst) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000434 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) {
435 // Do not handle the case where AI has multiple start markers.
436 if (LifeStart)
437 return std::make_pair<Instruction *>(nullptr, nullptr);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000438 LifeStart = IntrInst;
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000439 }
440 if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) {
441 if (LifeEnd)
442 return std::make_pair<Instruction *>(nullptr, nullptr);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000443 LifeEnd = IntrInst;
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000444 }
445 continue;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000446 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000447 // Find untracked uses of the address, bail.
448 if (!definedInRegion(Blocks, U))
449 return std::make_pair<Instruction *>(nullptr, nullptr);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000450 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000451
452 if (!LifeStart || !LifeEnd)
453 return std::make_pair<Instruction *>(nullptr, nullptr);
454
455 SinkLifeStart = !definedInRegion(Blocks, LifeStart);
456 HoistLifeEnd = !definedInRegion(Blocks, LifeEnd);
457 // Do legality Check.
458 if ((SinkLifeStart || HoistLifeEnd) &&
459 !isLegalToShrinkwrapLifetimeMarkers(Addr))
460 return std::make_pair<Instruction *>(nullptr, nullptr);
461
462 // Check to see if we have a place to do hoisting, if not, bail.
463 if (HoistLifeEnd && !ExitBlock)
464 return std::make_pair<Instruction *>(nullptr, nullptr);
465
466 return std::make_pair(LifeStart, LifeEnd);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000467 };
468
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000469 bool SinkLifeStart = false, HoistLifeEnd = false;
470 auto Markers = GetLifeTimeMarkers(AI, SinkLifeStart, HoistLifeEnd);
471
472 if (Markers.first) {
473 if (SinkLifeStart)
474 SinkCands.insert(Markers.first);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000475 SinkCands.insert(AI);
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000476 if (HoistLifeEnd)
477 HoistCands.insert(Markers.second);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000478 continue;
479 }
480
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000481 // Follow the bitcast.
Xinliang David Li74480ad2017-05-30 21:22:18 +0000482 Instruction *MarkerAddr = nullptr;
483 for (User *U : AI->users()) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000484 if (U->stripInBoundsConstantOffsets() == AI) {
485 SinkLifeStart = false;
486 HoistLifeEnd = false;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000487 Instruction *Bitcast = cast<Instruction>(U);
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000488 Markers = GetLifeTimeMarkers(Bitcast, SinkLifeStart, HoistLifeEnd);
489 if (Markers.first) {
Xinliang David Li74480ad2017-05-30 21:22:18 +0000490 MarkerAddr = Bitcast;
491 continue;
492 }
493 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000494
495 // Found unknown use of AI.
Xinliang David Li74480ad2017-05-30 21:22:18 +0000496 if (!definedInRegion(Blocks, U)) {
497 MarkerAddr = nullptr;
498 break;
499 }
500 }
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000501
Xinliang David Li74480ad2017-05-30 21:22:18 +0000502 if (MarkerAddr) {
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000503 if (SinkLifeStart)
504 SinkCands.insert(Markers.first);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000505 if (!definedInRegion(Blocks, MarkerAddr))
506 SinkCands.insert(MarkerAddr);
507 SinkCands.insert(AI);
Xinliang David Li7ed6cd32017-06-11 20:46:05 +0000508 if (HoistLifeEnd)
509 HoistCands.insert(Markers.second);
Xinliang David Li74480ad2017-05-30 21:22:18 +0000510 }
511 }
512 }
513}
514
515void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
516 const ValueSet &SinkCands) const {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000517 for (BasicBlock *BB : Blocks) {
Chandler Carruth14316fc2012-05-04 11:20:27 +0000518 // If a used value is defined outside the region, it's an input. If an
519 // instruction is used outside the region, it's an output.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000520 for (Instruction &II : *BB) {
521 for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE;
Xinliang David Li74480ad2017-05-30 21:22:18 +0000522 ++OI) {
523 Value *V = *OI;
524 if (!SinkCands.count(V) && definedInCaller(Blocks, V))
525 Inputs.insert(V);
526 }
Chandler Carruth14316fc2012-05-04 11:20:27 +0000527
Benjamin Kramer135f7352016-06-26 12:28:59 +0000528 for (User *U : II.users())
Chandler Carruthcdf47882014-03-09 03:16:01 +0000529 if (!definedInRegion(Blocks, U)) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000530 Outputs.insert(&II);
Chandler Carruth14316fc2012-05-04 11:20:27 +0000531 break;
532 }
533 }
534 }
535}
536
Vedant Kumard1295692018-12-03 22:40:21 +0000537/// severSplitPHINodesOfEntry - If a PHI node has multiple inputs from outside
538/// of the region, we need to split the entry block of the region so that the
539/// PHI node is easier to deal with.
540void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) {
Jay Foade0938d82011-03-30 11:19:20 +0000541 unsigned NumPredsFromRegion = 0;
Chris Lattner795c9932004-05-12 15:29:13 +0000542 unsigned NumPredsOutsideRegion = 0;
Chris Lattner3b2917b2004-05-12 06:01:40 +0000543
Dan Gohmandcb291f2007-03-22 16:38:57 +0000544 if (Header != &Header->getParent()->getEntryBlock()) {
Chris Lattner795c9932004-05-12 15:29:13 +0000545 PHINode *PN = dyn_cast<PHINode>(Header->begin());
546 if (!PN) return; // No PHI nodes.
Chris Lattner3b2917b2004-05-12 06:01:40 +0000547
Chris Lattner795c9932004-05-12 15:29:13 +0000548 // If the header node contains any PHI nodes, check to see if there is more
549 // than one entry from outside the region. If so, we need to sever the
550 // header block into two.
551 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000552 if (Blocks.count(PN->getIncomingBlock(i)))
Jay Foade0938d82011-03-30 11:19:20 +0000553 ++NumPredsFromRegion;
Chris Lattner795c9932004-05-12 15:29:13 +0000554 else
555 ++NumPredsOutsideRegion;
556
557 // If there is one (or fewer) predecessor from outside the region, we don't
558 // need to do anything special.
559 if (NumPredsOutsideRegion <= 1) return;
560 }
561
562 // Otherwise, we need to split the header block into two pieces: one
563 // containing PHI nodes merging values from outside of the region, and a
564 // second that contains all of the code for the block and merges back any
565 // incoming values from inside of the region.
Eugene Zelenko286d5892017-10-11 21:41:43 +0000566 BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT);
Chris Lattner795c9932004-05-12 15:29:13 +0000567
568 // We only want to code extract the second block now, and it becomes the new
569 // header of the region.
570 BasicBlock *OldPred = Header;
Chandler Carruth0fde0012012-05-04 10:18:49 +0000571 Blocks.remove(OldPred);
572 Blocks.insert(NewBB);
Chris Lattner795c9932004-05-12 15:29:13 +0000573 Header = NewBB;
574
Chris Lattner795c9932004-05-12 15:29:13 +0000575 // Okay, now we need to adjust the PHI nodes and any branches from within the
576 // region to go to the new header block instead of the old header block.
Jay Foade0938d82011-03-30 11:19:20 +0000577 if (NumPredsFromRegion) {
Chris Lattner795c9932004-05-12 15:29:13 +0000578 PHINode *PN = cast<PHINode>(OldPred->begin());
579 // Loop over all of the predecessors of OldPred that are in the region,
580 // changing them to branch to NewBB instead.
581 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000582 if (Blocks.count(PN->getIncomingBlock(i))) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000583 Instruction *TI = PN->getIncomingBlock(i)->getTerminator();
Chris Lattner795c9932004-05-12 15:29:13 +0000584 TI->replaceUsesOfWith(OldPred, NewBB);
585 }
586
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000587 // Okay, everything within the region is now branching to the right block, we
Chris Lattner795c9932004-05-12 15:29:13 +0000588 // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
Xinliang David Li99e3ca12017-04-20 21:40:22 +0000589 BasicBlock::iterator AfterPHIs;
Reid Spencer66149462004-09-15 17:06:42 +0000590 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
591 PHINode *PN = cast<PHINode>(AfterPHIs);
Chris Lattner795c9932004-05-12 15:29:13 +0000592 // Create a new PHI node in the new region, which has an incoming value
593 // from OldPred of PN.
Jay Foad52131342011-03-30 11:28:46 +0000594 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000595 PN->getName() + ".ce", &NewBB->front());
Xinliang David Lif12a0fa2017-04-25 04:51:19 +0000596 PN->replaceAllUsesWith(NewPN);
Chris Lattner795c9932004-05-12 15:29:13 +0000597 NewPN->addIncoming(PN, OldPred);
598
599 // Loop over all of the incoming value in PN, moving them to NewPN if they
600 // are from the extracted region.
601 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
Chandler Carruth0fde0012012-05-04 10:18:49 +0000602 if (Blocks.count(PN->getIncomingBlock(i))) {
Chris Lattner795c9932004-05-12 15:29:13 +0000603 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
604 PN->removeIncomingValue(i);
605 --i;
606 }
607 }
608 }
609 }
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000610}
Chris Lattner795c9932004-05-12 15:29:13 +0000611
Vedant Kumard1295692018-12-03 22:40:21 +0000612/// severSplitPHINodesOfExits - if PHI nodes in exit blocks have inputs from
613/// outlined region, we split these PHIs on two: one with inputs from region
614/// and other with remaining incoming blocks; then first PHIs are placed in
615/// outlined region.
616void CodeExtractor::severSplitPHINodesOfExits(
617 const SmallPtrSetImpl<BasicBlock *> &Exits) {
618 for (BasicBlock *ExitBB : Exits) {
619 BasicBlock *NewBB = nullptr;
620
621 for (PHINode &PN : ExitBB->phis()) {
622 // Find all incoming values from the outlining region.
623 SmallVector<unsigned, 2> IncomingVals;
624 for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i)
625 if (Blocks.count(PN.getIncomingBlock(i)))
626 IncomingVals.push_back(i);
627
628 // Do not process PHI if there is one (or fewer) predecessor from region.
629 // If PHI has exactly one predecessor from region, only this one incoming
630 // will be replaced on codeRepl block, so it should be safe to skip PHI.
631 if (IncomingVals.size() <= 1)
632 continue;
633
634 // Create block for new PHIs and add it to the list of outlined if it
635 // wasn't done before.
636 if (!NewBB) {
637 NewBB = BasicBlock::Create(ExitBB->getContext(),
638 ExitBB->getName() + ".split",
639 ExitBB->getParent(), ExitBB);
640 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBB),
641 pred_end(ExitBB));
642 for (BasicBlock *PredBB : Preds)
643 if (Blocks.count(PredBB))
644 PredBB->getTerminator()->replaceUsesOfWith(ExitBB, NewBB);
645 BranchInst::Create(ExitBB, NewBB);
646 Blocks.insert(NewBB);
647 }
648
649 // Split this PHI.
650 PHINode *NewPN =
651 PHINode::Create(PN.getType(), IncomingVals.size(),
652 PN.getName() + ".ce", NewBB->getFirstNonPHI());
653 for (unsigned i : IncomingVals)
654 NewPN->addIncoming(PN.getIncomingValue(i), PN.getIncomingBlock(i));
655 for (unsigned i : reverse(IncomingVals))
656 PN.removeIncomingValue(i, false);
657 PN.addIncoming(NewPN, NewBB);
658 }
659 }
660}
661
Chris Lattner13d2ddf2004-05-12 16:07:41 +0000662void CodeExtractor::splitReturnBlocks() {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000663 for (BasicBlock *Block : Blocks)
664 if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000665 BasicBlock *New =
Benjamin Kramer135f7352016-06-26 12:28:59 +0000666 Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret");
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000667 if (DT) {
Gabor Greif2f5f6962010-09-10 22:25:58 +0000668 // Old dominates New. New node dominates all other nodes dominated
669 // by Old.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000670 DomTreeNode *OldNode = DT->getNode(Block);
671 SmallVector<DomTreeNode *, 8> Children(OldNode->begin(),
672 OldNode->end());
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000673
Benjamin Kramer135f7352016-06-26 12:28:59 +0000674 DomTreeNode *NewNode = DT->addNewBlock(New, Block);
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000675
Benjamin Kramer135f7352016-06-26 12:28:59 +0000676 for (DomTreeNode *I : Children)
677 DT->changeImmediateDominator(I, NewNode);
Owen Andersonb4aa5b12009-08-24 23:32:14 +0000678 }
679 }
Chris Lattner3b2917b2004-05-12 06:01:40 +0000680}
681
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000682/// constructFunction - make a function based on inputs and outputs, as follows:
683/// f(in0, ..., inN, out0, ..., outN)
Chandler Carruth0fde0012012-05-04 10:18:49 +0000684Function *CodeExtractor::constructFunction(const ValueSet &inputs,
685 const ValueSet &outputs,
Chris Lattner320d59f2004-03-18 05:28:49 +0000686 BasicBlock *header,
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000687 BasicBlock *newRootNode,
688 BasicBlock *newHeader,
Chris Lattner320d59f2004-03-18 05:28:49 +0000689 Function *oldFunction,
690 Module *M) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000691 LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n");
692 LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000693
694 // This function returns unsigned, outputs will go back by reference.
Chris Lattnerffc49262004-05-12 04:14:24 +0000695 switch (NumExitBlocks) {
696 case 0:
Owen Anderson55f1c092009-08-13 21:58:54 +0000697 case 1: RetTy = Type::getVoidTy(header->getContext()); break;
698 case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
699 default: RetTy = Type::getInt16Ty(header->getContext()); break;
Chris Lattnerffc49262004-05-12 04:14:24 +0000700 }
701
Eugene Zelenko286d5892017-10-11 21:41:43 +0000702 std::vector<Type *> paramTy;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000703
704 // Add the types of the input values to the function's argument list
Benjamin Kramer135f7352016-06-26 12:28:59 +0000705 for (Value *value : inputs) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000706 LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n");
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000707 paramTy.push_back(value->getType());
708 }
709
Chris Lattner37de2572004-03-18 03:49:40 +0000710 // Add the types of the output values to the function's argument list.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000711 for (Value *output : outputs) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000712 LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000713 if (AggregateArgs)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000714 paramTy.push_back(output->getType());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000715 else
Benjamin Kramer135f7352016-06-26 12:28:59 +0000716 paramTy.push_back(PointerType::getUnqual(output->getType()));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000717 }
718
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000719 LLVM_DEBUG({
Benjamin Kramer706e48832016-06-26 13:39:33 +0000720 dbgs() << "Function type: " << *RetTy << " f(";
721 for (Type *i : paramTy)
722 dbgs() << *i << ", ";
723 dbgs() << ")\n";
724 });
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000725
David Blaikie741c8f82015-03-14 01:53:18 +0000726 StructType *StructTy;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000727 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
David Blaikie741c8f82015-03-14 01:53:18 +0000728 StructTy = StructType::get(M->getContext(), paramTy);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000729 paramTy.clear();
David Blaikie741c8f82015-03-14 01:53:18 +0000730 paramTy.push_back(PointerType::getUnqual(StructTy));
Misha Brukman3596f0a2004-04-23 23:54:17 +0000731 }
Chris Lattner229907c2011-07-18 04:54:35 +0000732 FunctionType *funcType =
Florian Hahn0e9dec62017-11-13 10:35:52 +0000733 FunctionType::get(RetTy, paramTy,
734 AllowVarArgs && oldFunction->isVarArg());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000735
Teresa Johnsonc8dba682018-10-24 18:53:47 +0000736 std::string SuffixToUse =
737 Suffix.empty()
738 ? (header->getName().empty() ? "extracted" : header->getName().str())
739 : Suffix;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000740 // Create the new function
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +0000741 Function *newFunction = Function::Create(
742 funcType, GlobalValue::InternalLinkage, oldFunction->getAddressSpace(),
Teresa Johnsonc8dba682018-10-24 18:53:47 +0000743 oldFunction->getName() + "." + SuffixToUse, M);
Chris Lattner4caf5eb2008-12-18 05:52:56 +0000744 // If the old function is no-throw, so is the new one.
745 if (oldFunction->doesNotThrow())
Bill Wendlingf319e992012-10-10 03:12:49 +0000746 newFunction->setDoesNotThrow();
Sean Silvaa0a802a2016-08-01 03:15:32 +0000747
748 // Inherit the uwtable attribute if we need to.
749 if (oldFunction->hasUWTable())
750 newFunction->setHasUWTable();
751
Florian Hahn55be37e2018-01-07 11:22:25 +0000752 // Inherit all of the target dependent attributes and white-listed
753 // target independent attributes.
Sean Silvaa0a802a2016-08-01 03:15:32 +0000754 // (e.g. If the extracted region contains a call to an x86.sse
755 // instruction we need to make sure that the extracted region has the
756 // "target-features" attribute allowing it to be lowered.
757 // FIXME: This should be changed to check to see if a specific
758 // attribute can not be inherited.
Florian Hahn55be37e2018-01-07 11:22:25 +0000759 for (const auto &Attr : oldFunction->getAttributes().getFnAttributes()) {
760 if (Attr.isStringAttribute()) {
761 if (Attr.getKindAsString() == "thunk")
762 continue;
763 } else
764 switch (Attr.getKindAsEnum()) {
765 // Those attributes cannot be propagated safely. Explicitly list them
766 // here so we get a warning if new attributes are added. This list also
767 // includes non-function attributes.
768 case Attribute::Alignment:
769 case Attribute::AllocSize:
770 case Attribute::ArgMemOnly:
771 case Attribute::Builtin:
772 case Attribute::ByVal:
773 case Attribute::Convergent:
774 case Attribute::Dereferenceable:
775 case Attribute::DereferenceableOrNull:
776 case Attribute::InAlloca:
777 case Attribute::InReg:
778 case Attribute::InaccessibleMemOnly:
779 case Attribute::InaccessibleMemOrArgMemOnly:
780 case Attribute::JumpTable:
781 case Attribute::Naked:
782 case Attribute::Nest:
783 case Attribute::NoAlias:
784 case Attribute::NoBuiltin:
785 case Attribute::NoCapture:
786 case Attribute::NoReturn:
787 case Attribute::None:
788 case Attribute::NonNull:
789 case Attribute::ReadNone:
790 case Attribute::ReadOnly:
791 case Attribute::Returned:
792 case Attribute::ReturnsTwice:
793 case Attribute::SExt:
794 case Attribute::Speculatable:
795 case Attribute::StackAlignment:
796 case Attribute::StructRet:
797 case Attribute::SwiftError:
798 case Attribute::SwiftSelf:
799 case Attribute::WriteOnly:
800 case Attribute::ZExt:
Matt Arsenaultcaf13162019-03-12 21:02:54 +0000801 case Attribute::ImmArg:
Florian Hahn55be37e2018-01-07 11:22:25 +0000802 case Attribute::EndAttrKinds:
803 continue;
804 // Those attributes should be safe to propagate to the extracted function.
805 case Attribute::AlwaysInline:
806 case Attribute::Cold:
807 case Attribute::NoRecurse:
808 case Attribute::InlineHint:
809 case Attribute::MinSize:
810 case Attribute::NoDuplicate:
811 case Attribute::NoImplicitFloat:
812 case Attribute::NoInline:
813 case Attribute::NonLazyBind:
814 case Attribute::NoRedZone:
815 case Attribute::NoUnwind:
Matt Morehouse236cdaf2018-03-22 17:07:51 +0000816 case Attribute::OptForFuzzing:
Florian Hahn55be37e2018-01-07 11:22:25 +0000817 case Attribute::OptimizeNone:
818 case Attribute::OptimizeForSize:
819 case Attribute::SafeStack:
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +0000820 case Attribute::ShadowCallStack:
Florian Hahn55be37e2018-01-07 11:22:25 +0000821 case Attribute::SanitizeAddress:
822 case Attribute::SanitizeMemory:
823 case Attribute::SanitizeThread:
824 case Attribute::SanitizeHWAddress:
Chandler Carruth664aa862018-09-04 12:38:00 +0000825 case Attribute::SpeculativeLoadHardening:
Florian Hahn55be37e2018-01-07 11:22:25 +0000826 case Attribute::StackProtect:
827 case Attribute::StackProtectReq:
828 case Attribute::StackProtectStrong:
829 case Attribute::StrictFP:
830 case Attribute::UWTable:
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +0000831 case Attribute::NoCfCheck:
Florian Hahn55be37e2018-01-07 11:22:25 +0000832 break;
833 }
Sean Silvaa0a802a2016-08-01 03:15:32 +0000834
Florian Hahn55be37e2018-01-07 11:22:25 +0000835 newFunction->addFnAttr(Attr);
836 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000837 newFunction->getBasicBlockList().push_back(newRootNode);
838
Chris Lattner37de2572004-03-18 03:49:40 +0000839 // Create an iterator to name all of the arguments we inserted.
Chris Lattner531f9e92005-03-15 04:54:21 +0000840 Function::arg_iterator AI = newFunction->arg_begin();
Chris Lattner37de2572004-03-18 03:49:40 +0000841
842 // Rewrite all users of the inputs in the extracted region to use the
Misha Brukman3596f0a2004-04-23 23:54:17 +0000843 // arguments (or appropriate addressing into struct) instead.
844 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
845 Value *RewriteVal;
846 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +0000847 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +0000848 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
849 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
Chandler Carruthedb12a82018-10-15 10:04:59 +0000850 Instruction *TI = newFunction->begin()->getTerminator();
David Blaikie741c8f82015-03-14 01:53:18 +0000851 GetElementPtrInst *GEP = GetElementPtrInst::Create(
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000852 StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI);
James Y Knight14359ef2019-02-01 20:44:24 +0000853 RewriteVal = new LoadInst(StructTy->getElementType(i), GEP,
854 "loadgep_" + inputs[i]->getName(), TI);
Misha Brukman3596f0a2004-04-23 23:54:17 +0000855 } else
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000856 RewriteVal = &*AI++;
Misha Brukman3596f0a2004-04-23 23:54:17 +0000857
Eugene Zelenko286d5892017-10-11 21:41:43 +0000858 std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end());
Benjamin Kramer135f7352016-06-26 12:28:59 +0000859 for (User *use : Users)
860 if (Instruction *inst = dyn_cast<Instruction>(use))
Chandler Carruth0fde0012012-05-04 10:18:49 +0000861 if (Blocks.count(inst->getParent()))
Misha Brukman3596f0a2004-04-23 23:54:17 +0000862 inst->replaceUsesOfWith(inputs[i], RewriteVal);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000863 }
864
Misha Brukman3596f0a2004-04-23 23:54:17 +0000865 // Set names for input and output arguments.
866 if (!AggregateArgs) {
Chris Lattner531f9e92005-03-15 04:54:21 +0000867 AI = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +0000868 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
Owen Anderson7629b712008-04-14 17:38:21 +0000869 AI->setName(inputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +0000870 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
Misha Brukmanb1c93172005-04-21 23:48:37 +0000871 AI->setName(outputs[i]->getName()+".out");
Misha Brukman3596f0a2004-04-23 23:54:17 +0000872 }
Chris Lattner37de2572004-03-18 03:49:40 +0000873
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000874 // Rewrite branches to basic blocks outside of the loop to new dummy blocks
875 // within the new function. This must be done before we lose track of which
876 // blocks were originally in the code region.
Eugene Zelenko286d5892017-10-11 21:41:43 +0000877 std::vector<User *> Users(header->user_begin(), header->user_end());
Chris Lattner320d59f2004-03-18 05:28:49 +0000878 for (unsigned i = 0, e = Users.size(); i != e; ++i)
879 // The BasicBlock which contains the branch is not in the region
880 // modify the branch target to a new block
Chandler Carruth8b7a8122018-10-18 00:38:54 +0000881 if (Instruction *I = dyn_cast<Instruction>(Users[i]))
882 if (I->isTerminator() && !Blocks.count(I->getParent()) &&
883 I->getParent()->getParent() == oldFunction)
884 I->replaceUsesOfWith(header, newHeader);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +0000885
886 return newFunction;
887}
888
Vedant Kumar4b0cc9a2019-02-13 19:53:38 +0000889/// Erase lifetime.start markers which reference inputs to the extraction
Vedant Kumar5f5cac32019-02-15 18:46:58 +0000890/// region, and insert the referenced memory into \p LifetimesStart.
Vedant Kumar17d9f142019-01-19 02:37:59 +0000891///
892/// The extraction region is defined by a set of blocks (\p Blocks), and a set
893/// of allocas which will be moved from the caller function into the extracted
894/// function (\p SunkAllocas).
Vedant Kumar4b0cc9a2019-02-13 19:53:38 +0000895static void eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock *> &Blocks,
896 const SetVector<Value *> &SunkAllocas,
Vedant Kumar5f5cac32019-02-15 18:46:58 +0000897 SetVector<Value *> &LifetimesStart) {
Vedant Kumar17d9f142019-01-19 02:37:59 +0000898 for (BasicBlock *BB : Blocks) {
899 for (auto It = BB->begin(), End = BB->end(); It != End;) {
900 auto *II = dyn_cast<IntrinsicInst>(&*It);
901 ++It;
902 if (!II || !II->isLifetimeStartOrEnd())
903 continue;
904
905 // Get the memory operand of the lifetime marker. If the underlying
906 // object is a sunk alloca, or is otherwise defined in the extraction
907 // region, the lifetime marker must not be erased.
908 Value *Mem = II->getOperand(1)->stripInBoundsOffsets();
909 if (SunkAllocas.count(Mem) || definedInRegion(Blocks, Mem))
910 continue;
911
Vedant Kumar4b0cc9a2019-02-13 19:53:38 +0000912 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
913 LifetimesStart.insert(Mem);
Vedant Kumar17d9f142019-01-19 02:37:59 +0000914 II->eraseFromParent();
915 }
916 }
Vedant Kumar17d9f142019-01-19 02:37:59 +0000917}
918
919/// Insert lifetime start/end markers surrounding the call to the new function
920/// for objects defined in the caller.
Vedant Kumar4b0cc9a2019-02-13 19:53:38 +0000921static void insertLifetimeMarkersSurroundingCall(
922 Module *M, ArrayRef<Value *> LifetimesStart, ArrayRef<Value *> LifetimesEnd,
923 CallInst *TheCall) {
Vedant Kumar17d9f142019-01-19 02:37:59 +0000924 LLVMContext &Ctx = M->getContext();
925 auto Int8PtrTy = Type::getInt8PtrTy(Ctx);
926 auto NegativeOne = ConstantInt::getSigned(Type::getInt64Ty(Ctx), -1);
Vedant Kumar17d9f142019-01-19 02:37:59 +0000927 Instruction *Term = TheCall->getParent()->getTerminator();
Vedant Kumar17d9f142019-01-19 02:37:59 +0000928
Vedant Kumar4b0cc9a2019-02-13 19:53:38 +0000929 // The memory argument to a lifetime marker must be a i8*. Cache any bitcasts
930 // needed to satisfy this requirement so they may be reused.
931 DenseMap<Value *, Value *> Bitcasts;
932
933 // Emit lifetime markers for the pointers given in \p Objects. Insert the
934 // markers before the call if \p InsertBefore, and after the call otherwise.
935 auto insertMarkers = [&](Function *MarkerFunc, ArrayRef<Value *> Objects,
936 bool InsertBefore) {
937 for (Value *Mem : Objects) {
938 assert((!isa<Instruction>(Mem) || cast<Instruction>(Mem)->getFunction() ==
939 TheCall->getFunction()) &&
940 "Input memory not defined in original function");
941 Value *&MemAsI8Ptr = Bitcasts[Mem];
942 if (!MemAsI8Ptr) {
943 if (Mem->getType() == Int8PtrTy)
944 MemAsI8Ptr = Mem;
945 else
946 MemAsI8Ptr =
947 CastInst::CreatePointerCast(Mem, Int8PtrTy, "lt.cast", TheCall);
948 }
949
950 auto Marker = CallInst::Create(MarkerFunc, {NegativeOne, MemAsI8Ptr});
951 if (InsertBefore)
952 Marker->insertBefore(TheCall);
953 else
954 Marker->insertBefore(Term);
955 }
956 };
957
958 if (!LifetimesStart.empty()) {
959 auto StartFn = llvm::Intrinsic::getDeclaration(
960 M, llvm::Intrinsic::lifetime_start, Int8PtrTy);
961 insertMarkers(StartFn, LifetimesStart, /*InsertBefore=*/true);
962 }
963
964 if (!LifetimesEnd.empty()) {
965 auto EndFn = llvm::Intrinsic::getDeclaration(
966 M, llvm::Intrinsic::lifetime_end, Int8PtrTy);
967 insertMarkers(EndFn, LifetimesEnd, /*InsertBefore=*/false);
Vedant Kumar17d9f142019-01-19 02:37:59 +0000968 }
969}
970
Chris Lattner3b2917b2004-05-12 06:01:40 +0000971/// emitCallAndSwitchStatement - This method sets up the caller side by adding
972/// the call instruction, splitting any PHI nodes in the header block as
973/// necessary.
Vedant Kumara1778df2019-01-04 17:43:22 +0000974CallInst *CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,
975 BasicBlock *codeReplacer,
976 ValueSet &inputs,
977 ValueSet &outputs) {
Chris Lattner3b2917b2004-05-12 06:01:40 +0000978 // Emit a call to the new function, passing in: *pointer to struct (if
979 // aggregating parameters), or plan inputs and allocated memory for outputs
Eugene Zelenko286d5892017-10-11 21:41:43 +0000980 std::vector<Value *> params, StructValues, ReloadOutputs, Reloads;
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000981
982 Module *M = newFunction->getParent();
983 LLVMContext &Context = M->getContext();
984 const DataLayout &DL = M->getDataLayout();
Vedant Kumara1778df2019-01-04 17:43:22 +0000985 CallInst *call = nullptr;
Chris Lattnerd8017a32004-03-18 04:12:05 +0000986
Misha Brukman3596f0a2004-04-23 23:54:17 +0000987 // Add inputs as params, or to be filled into the struct
Vedant Kumar1c3694a2019-01-28 19:13:37 +0000988 unsigned ArgNo = 0;
989 SmallVector<unsigned, 1> SwiftErrorArgs;
990 for (Value *input : inputs) {
Misha Brukman3596f0a2004-04-23 23:54:17 +0000991 if (AggregateArgs)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000992 StructValues.push_back(input);
Vedant Kumar1c3694a2019-01-28 19:13:37 +0000993 else {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000994 params.push_back(input);
Vedant Kumar1c3694a2019-01-28 19:13:37 +0000995 if (input->isSwiftError())
996 SwiftErrorArgs.push_back(ArgNo);
997 }
998 ++ArgNo;
999 }
Misha Brukman3596f0a2004-04-23 23:54:17 +00001000
1001 // Create allocas for the outputs
Benjamin Kramer135f7352016-06-26 12:28:59 +00001002 for (Value *output : outputs) {
Misha Brukman3596f0a2004-04-23 23:54:17 +00001003 if (AggregateArgs) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001004 StructValues.push_back(output);
Misha Brukman3596f0a2004-04-23 23:54:17 +00001005 } else {
1006 AllocaInst *alloca =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001007 new AllocaInst(output->getType(), DL.getAllocaAddrSpace(),
1008 nullptr, output->getName() + ".loc",
1009 &codeReplacer->getParent()->front().front());
Misha Brukman3596f0a2004-04-23 23:54:17 +00001010 ReloadOutputs.push_back(alloca);
1011 params.push_back(alloca);
1012 }
1013 }
1014
David Blaikie741c8f82015-03-14 01:53:18 +00001015 StructType *StructArgTy = nullptr;
Craig Topperf40110f2014-04-25 05:29:35 +00001016 AllocaInst *Struct = nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +00001017 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
Eugene Zelenko286d5892017-10-11 21:41:43 +00001018 std::vector<Type *> ArgTypes;
Chandler Carruth0fde0012012-05-04 10:18:49 +00001019 for (ValueSet::iterator v = StructValues.begin(),
Misha Brukman3596f0a2004-04-23 23:54:17 +00001020 ve = StructValues.end(); v != ve; ++v)
1021 ArgTypes.push_back((*v)->getType());
1022
1023 // Allocate a struct at the beginning of this function
David Blaikie741c8f82015-03-14 01:53:18 +00001024 StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001025 Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr,
1026 "structArg",
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001027 &codeReplacer->getParent()->front().front());
Misha Brukman3596f0a2004-04-23 23:54:17 +00001028 params.push_back(Struct);
1029
1030 for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
David Greenec656cbb2007-09-04 15:46:09 +00001031 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +00001032 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
1033 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
David Blaikie741c8f82015-03-14 01:53:18 +00001034 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1035 StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +00001036 codeReplacer->getInstList().push_back(GEP);
1037 StoreInst *SI = new StoreInst(StructValues[i], GEP);
1038 codeReplacer->getInstList().push_back(SI);
1039 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001040 }
Misha Brukman3596f0a2004-04-23 23:54:17 +00001041
1042 // Emit the call to the function
Vedant Kumara1778df2019-01-04 17:43:22 +00001043 call = CallInst::Create(newFunction, params,
1044 NumExitBlocks > 1 ? "targetBlock" : "");
Florian Hahne5089e22017-12-08 21:49:03 +00001045 // Add debug location to the new call, if the original function has debug
1046 // info. In that case, the terminator of the entry block of the extracted
1047 // function contains the first debug location of the extracted function,
1048 // set in extractCodeRegion.
1049 if (codeReplacer->getParent()->getSubprogram()) {
1050 if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc())
1051 call->setDebugLoc(DL);
1052 }
Misha Brukman3596f0a2004-04-23 23:54:17 +00001053 codeReplacer->getInstList().push_back(call);
1054
Vedant Kumar1c3694a2019-01-28 19:13:37 +00001055 // Set swifterror parameter attributes.
1056 for (unsigned SwiftErrArgNo : SwiftErrorArgs) {
1057 call->addParamAttr(SwiftErrArgNo, Attribute::SwiftError);
1058 newFunction->addParamAttr(SwiftErrArgNo, Attribute::SwiftError);
1059 }
1060
Chris Lattner531f9e92005-03-15 04:54:21 +00001061 Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
Misha Brukman3596f0a2004-04-23 23:54:17 +00001062 unsigned FirstOut = inputs.size();
1063 if (!AggregateArgs)
1064 std::advance(OutputArgBegin, inputs.size());
1065
Jakub Kuderskicbe9fae2017-10-06 03:37:06 +00001066 // Reload the outputs passed in by reference.
Misha Brukman3596f0a2004-04-23 23:54:17 +00001067 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +00001068 Value *Output = nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +00001069 if (AggregateArgs) {
David Greenec656cbb2007-09-04 15:46:09 +00001070 Value *Idx[2];
Owen Anderson55f1c092009-08-13 21:58:54 +00001071 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
1072 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
David Blaikie741c8f82015-03-14 01:53:18 +00001073 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1074 StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName());
Misha Brukman3596f0a2004-04-23 23:54:17 +00001075 codeReplacer->getInstList().push_back(GEP);
1076 Output = GEP;
1077 } else {
1078 Output = ReloadOutputs[i];
1079 }
James Y Knight14359ef2019-02-01 20:44:24 +00001080 LoadInst *load = new LoadInst(outputs[i]->getType(), Output,
1081 outputs[i]->getName() + ".reload");
Owen Anderson34e61482009-08-25 00:54:39 +00001082 Reloads.push_back(load);
Chris Lattner37de2572004-03-18 03:49:40 +00001083 codeReplacer->getInstList().push_back(load);
Eugene Zelenko286d5892017-10-11 21:41:43 +00001084 std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end());
Chris Lattner37de2572004-03-18 03:49:40 +00001085 for (unsigned u = 0, e = Users.size(); u != e; ++u) {
1086 Instruction *inst = cast<Instruction>(Users[u]);
Chandler Carruth0fde0012012-05-04 10:18:49 +00001087 if (!Blocks.count(inst->getParent()))
Chris Lattner37de2572004-03-18 03:49:40 +00001088 inst->replaceUsesOfWith(outputs[i], load);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001089 }
1090 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +00001091
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001092 // Now we can emit a switch statement using the call as a value.
Chris Lattnerffc49262004-05-12 04:14:24 +00001093 SwitchInst *TheSwitch =
Owen Anderson55f1c092009-08-13 21:58:54 +00001094 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
Gabor Greife9ecc682008-04-06 20:25:17 +00001095 codeReplacer, 0, codeReplacer);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001096
1097 // Since there may be multiple exits from the original region, make the new
Chris Lattnerb4d8bf32004-03-14 23:05:49 +00001098 // function return an unsigned, switch on that number. This loop iterates
1099 // over all of the blocks in the extracted region, updating any terminator
1100 // instructions in the to-be-extracted region that branch to blocks that are
1101 // not in the region to be extracted.
Eugene Zelenko286d5892017-10-11 21:41:43 +00001102 std::map<BasicBlock *, BasicBlock *> ExitBlockMap;
Chris Lattnerb4d8bf32004-03-14 23:05:49 +00001103
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001104 unsigned switchVal = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001105 for (BasicBlock *Block : Blocks) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001106 Instruction *TI = Block->getTerminator();
Chris Lattnerb4d8bf32004-03-14 23:05:49 +00001107 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +00001108 if (!Blocks.count(TI->getSuccessor(i))) {
Chris Lattnerb4d8bf32004-03-14 23:05:49 +00001109 BasicBlock *OldTarget = TI->getSuccessor(i);
1110 // add a new basic block which returns the appropriate value
1111 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
1112 if (!NewTarget) {
1113 // If we don't already have an exit stub for this non-extracted
1114 // destination, create one now!
Owen Anderson55f1c092009-08-13 21:58:54 +00001115 NewTarget = BasicBlock::Create(Context,
1116 OldTarget->getName() + ".exitStub",
Gabor Greife9ecc682008-04-06 20:25:17 +00001117 newFunction);
Chris Lattnerffc49262004-05-12 04:14:24 +00001118 unsigned SuccNum = switchVal++;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001119
Craig Topperf40110f2014-04-25 05:29:35 +00001120 Value *brVal = nullptr;
Chris Lattnerffc49262004-05-12 04:14:24 +00001121 switch (NumExitBlocks) {
1122 case 0:
1123 case 1: break; // No value needed.
1124 case 2: // Conditional branch, return a bool
Owen Anderson55f1c092009-08-13 21:58:54 +00001125 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +00001126 break;
1127 default:
Owen Anderson55f1c092009-08-13 21:58:54 +00001128 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
Chris Lattnerffc49262004-05-12 04:14:24 +00001129 break;
1130 }
1131
Jakub Kuderskicbe9fae2017-10-06 03:37:06 +00001132 ReturnInst::Create(Context, brVal, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001133
Chris Lattnerb4d8bf32004-03-14 23:05:49 +00001134 // Update the switch instruction.
Owen Anderson55f1c092009-08-13 21:58:54 +00001135 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
1136 SuccNum),
Chris Lattnerffc49262004-05-12 04:14:24 +00001137 OldTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001138 }
Chris Lattnerb4d8bf32004-03-14 23:05:49 +00001139
1140 // rewrite the original branch instruction with this new target
1141 TI->setSuccessor(i, NewTarget);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001142 }
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001143 }
Chris Lattner5b2072e2004-03-14 23:43:24 +00001144
Vedant Kumar0e5dd512019-02-08 20:48:04 +00001145 // Store the arguments right after the definition of output value.
1146 // This should be proceeded after creating exit stubs to be ensure that invoke
1147 // result restore will be placed in the outlined function.
1148 Function::arg_iterator OAI = OutputArgBegin;
1149 for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
1150 auto *OutI = dyn_cast<Instruction>(outputs[i]);
1151 if (!OutI)
1152 continue;
1153
1154 // Find proper insertion point.
1155 BasicBlock::iterator InsertPt;
1156 // In case OutI is an invoke, we insert the store at the beginning in the
1157 // 'normal destination' BB. Otherwise we insert the store right after OutI.
1158 if (auto *InvokeI = dyn_cast<InvokeInst>(OutI))
1159 InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt();
1160 else if (auto *Phi = dyn_cast<PHINode>(OutI))
1161 InsertPt = Phi->getParent()->getFirstInsertionPt();
1162 else
1163 InsertPt = std::next(OutI->getIterator());
1164
1165 Instruction *InsertBefore = &*InsertPt;
1166 assert((InsertBefore->getFunction() == newFunction ||
1167 Blocks.count(InsertBefore->getParent())) &&
1168 "InsertPt should be in new function");
1169 assert(OAI != newFunction->arg_end() &&
1170 "Number of output arguments should match "
1171 "the amount of defined values");
1172 if (AggregateArgs) {
1173 Value *Idx[2];
1174 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
1175 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
1176 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1177 StructArgTy, &*OAI, Idx, "gep_" + outputs[i]->getName(),
1178 InsertBefore);
1179 new StoreInst(outputs[i], GEP, InsertBefore);
1180 // Since there should be only one struct argument aggregating
1181 // all the output values, we shouldn't increment OAI, which always
1182 // points to the struct argument, in this case.
1183 } else {
1184 new StoreInst(outputs[i], &*OAI, InsertBefore);
1185 ++OAI;
1186 }
1187 }
1188
Chris Lattner3d1ca672004-05-12 03:22:33 +00001189 // Now that we've done the deed, simplify the switch instruction.
Chris Lattner229907c2011-07-18 04:54:35 +00001190 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
Chris Lattnerffc49262004-05-12 04:14:24 +00001191 switch (NumExitBlocks) {
1192 case 0:
Chris Lattner7f1c7ed2004-08-12 03:17:02 +00001193 // There are no successors (the block containing the switch itself), which
Misha Brukman3596f0a2004-04-23 23:54:17 +00001194 // means that previously this was the last part of the function, and hence
1195 // this should be rewritten as a `ret'
Misha Brukmanb1c93172005-04-21 23:48:37 +00001196
Misha Brukman3596f0a2004-04-23 23:54:17 +00001197 // Check if the function should return a value
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001198 if (OldFnRetTy->isVoidTy()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001199 ReturnInst::Create(Context, nullptr, TheSwitch); // Return void
Chris Lattner7f1c7ed2004-08-12 03:17:02 +00001200 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
Misha Brukman3596f0a2004-04-23 23:54:17 +00001201 // return what we have
Owen Anderson55f1c092009-08-13 21:58:54 +00001202 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +00001203 } else {
1204 // Otherwise we must have code extracted an unwind or something, just
1205 // return whatever we want.
Fangrui Songf78650a2018-07-30 19:41:25 +00001206 ReturnInst::Create(Context,
Owen Anderson55f1c092009-08-13 21:58:54 +00001207 Constant::getNullValue(OldFnRetTy), TheSwitch);
Chris Lattner7f1c7ed2004-08-12 03:17:02 +00001208 }
Misha Brukman3596f0a2004-04-23 23:54:17 +00001209
Dan Gohman158ff2c2008-06-21 22:08:46 +00001210 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +00001211 break;
1212 case 1:
1213 // Only a single destination, change the switch into an unconditional
1214 // branch.
Gabor Greife9ecc682008-04-06 20:25:17 +00001215 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +00001216 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +00001217 break;
1218 case 2:
Gabor Greife9ecc682008-04-06 20:25:17 +00001219 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
1220 call, TheSwitch);
Dan Gohman158ff2c2008-06-21 22:08:46 +00001221 TheSwitch->eraseFromParent();
Chris Lattnerffc49262004-05-12 04:14:24 +00001222 break;
1223 default:
1224 // Otherwise, make the default destination of the switch instruction be one
1225 // of the other successors.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001226 TheSwitch->setCondition(call);
1227 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001228 // Remove redundant case
Bob Wilsone4077362013-09-09 19:14:35 +00001229 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
Chris Lattnerffc49262004-05-12 04:14:24 +00001230 break;
Chris Lattner5b2072e2004-03-14 23:43:24 +00001231 }
Vedant Kumara1778df2019-01-04 17:43:22 +00001232
Vedant Kumar17d9f142019-01-19 02:37:59 +00001233 // Insert lifetime markers around the reloads of any output values. The
1234 // allocas output values are stored in are only in-use in the codeRepl block.
Vedant Kumar4b0cc9a2019-02-13 19:53:38 +00001235 insertLifetimeMarkersSurroundingCall(M, ReloadOutputs, ReloadOutputs, call);
Vedant Kumar17d9f142019-01-19 02:37:59 +00001236
Vedant Kumara1778df2019-01-04 17:43:22 +00001237 return call;
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001238}
1239
Chris Lattner3b2917b2004-05-12 06:01:40 +00001240void CodeExtractor::moveCodeToFunction(Function *newFunction) {
Chandler Carruth0fde0012012-05-04 10:18:49 +00001241 Function *oldFunc = (*Blocks.begin())->getParent();
Chris Lattner3b2917b2004-05-12 06:01:40 +00001242 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
1243 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
1244
Benjamin Kramer135f7352016-06-26 12:28:59 +00001245 for (BasicBlock *Block : Blocks) {
Chris Lattner3b2917b2004-05-12 06:01:40 +00001246 // Delete the basic block from the old function, and the list of blocks
Benjamin Kramer135f7352016-06-26 12:28:59 +00001247 oldBlocks.remove(Block);
Chris Lattner3b2917b2004-05-12 06:01:40 +00001248
1249 // Insert this basic block into the new function
Benjamin Kramer135f7352016-06-26 12:28:59 +00001250 newBlocks.push_back(Block);
Sergey Dmitriev807960e2019-02-08 06:55:18 +00001251
1252 // Remove @llvm.assume calls that were moved to the new function from the
1253 // old function's assumption cache.
1254 if (AC)
1255 for (auto &I : *Block)
1256 if (match(&I, m_Intrinsic<Intrinsic::assume>()))
1257 AC->unregisterAssumption(cast<CallInst>(&I));
Chris Lattner3b2917b2004-05-12 06:01:40 +00001258 }
1259}
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001260
Sean Silvaf8015752016-08-02 02:15:45 +00001261void CodeExtractor::calculateNewCallTerminatorWeights(
1262 BasicBlock *CodeReplacer,
1263 DenseMap<BasicBlock *, BlockFrequency> &ExitWeights,
1264 BranchProbabilityInfo *BPI) {
Eugene Zelenko286d5892017-10-11 21:41:43 +00001265 using Distribution = BlockFrequencyInfoImplBase::Distribution;
1266 using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
Sean Silvaf8015752016-08-02 02:15:45 +00001267
1268 // Update the branch weights for the exit block.
Chandler Carruthedb12a82018-10-15 10:04:59 +00001269 Instruction *TI = CodeReplacer->getTerminator();
Sean Silvaf8015752016-08-02 02:15:45 +00001270 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0);
1271
1272 // Block Frequency distribution with dummy node.
1273 Distribution BranchDist;
1274
1275 // Add each of the frequencies of the successors.
1276 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) {
1277 BlockNode ExitNode(i);
1278 uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency();
1279 if (ExitFreq != 0)
1280 BranchDist.addExit(ExitNode, ExitFreq);
1281 else
1282 BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero());
1283 }
1284
1285 // Check for no total weight.
1286 if (BranchDist.Total == 0)
1287 return;
1288
1289 // Normalize the distribution so that they can fit in unsigned.
1290 BranchDist.normalize();
1291
1292 // Create normalized branch weights and set the metadata.
1293 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) {
1294 const auto &Weight = BranchDist.Weights[I];
1295
1296 // Get the weight and update the current BFI.
1297 BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
1298 BranchProbability BP(Weight.Amount, BranchDist.Total);
1299 BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP);
1300 }
1301 TI->setMetadata(
1302 LLVMContext::MD_prof,
1303 MDBuilder(TI->getContext()).createBranchWeights(BranchWeights));
1304}
1305
Chandler Carruth0fde0012012-05-04 10:18:49 +00001306Function *CodeExtractor::extractCodeRegion() {
1307 if (!isEligible())
Craig Topperf40110f2014-04-25 05:29:35 +00001308 return nullptr;
Misha Brukman3596f0a2004-04-23 23:54:17 +00001309
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001310 // Assumption: this is a single-entry code region, and the header is the first
Chris Lattner73ab1fa2004-03-15 01:18:23 +00001311 // block in the region.
Chandler Carruth0fde0012012-05-04 10:18:49 +00001312 BasicBlock *header = *Blocks.begin();
Florian Hahn0e9dec62017-11-13 10:35:52 +00001313 Function *oldFunction = header->getParent();
1314
1315 // For functions with varargs, check that varargs handling is only done in the
1316 // outlined function, i.e vastart and vaend are only used in outlined blocks.
1317 if (AllowVarArgs && oldFunction->getFunctionType()->isVarArg()) {
1318 auto containsVarArgIntrinsic = [](Instruction &I) {
1319 if (const CallInst *CI = dyn_cast<CallInst>(&I))
1320 if (const Function *F = CI->getCalledFunction())
1321 return F->getIntrinsicID() == Intrinsic::vastart ||
1322 F->getIntrinsicID() == Intrinsic::vaend;
1323 return false;
1324 };
1325
1326 for (auto &BB : *oldFunction) {
1327 if (Blocks.count(&BB))
1328 continue;
1329 if (llvm::any_of(BB, containsVarArgIntrinsic))
1330 return nullptr;
1331 }
1332 }
1333 ValueSet inputs, outputs, SinkingCands, HoistingCands;
1334 BasicBlock *CommonExit = nullptr;
Chris Lattner3b2917b2004-05-12 06:01:40 +00001335
Sean Silvaf8015752016-08-02 02:15:45 +00001336 // Calculate the entry frequency of the new function before we change the root
1337 // block.
1338 BlockFrequency EntryFreq;
1339 if (BFI) {
1340 assert(BPI && "Both BPI and BFI are required to preserve profile info");
1341 for (BasicBlock *Pred : predecessors(header)) {
1342 if (Blocks.count(Pred))
1343 continue;
1344 EntryFreq +=
1345 BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header);
1346 }
1347 }
1348
Chris Lattner13d2ddf2004-05-12 16:07:41 +00001349 // If we have any return instructions in the region, split those blocks so
1350 // that the return is not in the region.
1351 splitReturnBlocks();
1352
Vedant Kumard1295692018-12-03 22:40:21 +00001353 // Calculate the exit blocks for the extracted region and the total exit
1354 // weights for each of those blocks.
1355 DenseMap<BasicBlock *, BlockFrequency> ExitWeights;
1356 SmallPtrSet<BasicBlock *, 1> ExitBlocks;
1357 for (BasicBlock *Block : Blocks) {
1358 for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE;
1359 ++SI) {
1360 if (!Blocks.count(*SI)) {
1361 // Update the branch weight for this successor.
1362 if (BFI) {
1363 BlockFrequency &BF = ExitWeights[*SI];
1364 BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI);
1365 }
1366 ExitBlocks.insert(*SI);
1367 }
1368 }
1369 }
1370 NumExitBlocks = ExitBlocks.size();
1371
1372 // If we have to split PHI nodes of the entry or exit blocks, do so now.
1373 severSplitPHINodesOfEntry(header);
1374 severSplitPHINodesOfExits(ExitBlocks);
1375
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001376 // This takes place of the original loop
Fangrui Songf78650a2018-07-30 19:41:25 +00001377 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001378 "codeRepl", oldFunction,
Gabor Greif697e94c2008-05-15 10:04:30 +00001379 header);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001380
1381 // The new function needs a root node because other nodes can branch to the
Chris Lattner3b2917b2004-05-12 06:01:40 +00001382 // head of the region, but the entry node of a function cannot have preds.
Fangrui Songf78650a2018-07-30 19:41:25 +00001383 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001384 "newFuncRoot");
Florian Hahne5089e22017-12-08 21:49:03 +00001385 auto *BranchI = BranchInst::Create(header);
1386 // If the original function has debug info, we have to add a debug location
1387 // to the new branch instruction from the artificial entry block.
1388 // We use the debug location of the first instruction in the extracted
1389 // blocks, as there is no other equivalent line in the source code.
1390 if (oldFunction->getSubprogram()) {
1391 any_of(Blocks, [&BranchI](const BasicBlock *BB) {
1392 return any_of(*BB, [&BranchI](const Instruction &I) {
1393 if (!I.getDebugLoc())
1394 return false;
1395 BranchI->setDebugLoc(I.getDebugLoc());
1396 return true;
1397 });
1398 });
1399 }
1400 newFuncRoot->getInstList().push_back(BranchI);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001401
Xinliang David Li7ed6cd32017-06-11 20:46:05 +00001402 findAllocas(SinkingCands, HoistingCands, CommonExit);
1403 assert(HoistingCands.empty() || CommonExit);
Xinliang David Li74480ad2017-05-30 21:22:18 +00001404
Chris Lattner3b2917b2004-05-12 06:01:40 +00001405 // Find inputs to, outputs from the code region.
Xinliang David Li74480ad2017-05-30 21:22:18 +00001406 findInputsOutputs(inputs, outputs, SinkingCands);
1407
1408 // Now sink all instructions which only have non-phi uses inside the region
1409 for (auto *II : SinkingCands)
1410 cast<Instruction>(II)->moveBefore(*newFuncRoot,
1411 newFuncRoot->getFirstInsertionPt());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001412
Xinliang David Li7ed6cd32017-06-11 20:46:05 +00001413 if (!HoistingCands.empty()) {
1414 auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit);
1415 Instruction *TI = HoistToBlock->getTerminator();
1416 for (auto *II : HoistingCands)
1417 cast<Instruction>(II)->moveBefore(TI);
1418 }
1419
Vedant Kumara1778df2019-01-04 17:43:22 +00001420 // Collect objects which are inputs to the extraction region and also
Vedant Kumar5f5cac32019-02-15 18:46:58 +00001421 // referenced by lifetime start markers within it. The effects of these
Vedant Kumara1778df2019-01-04 17:43:22 +00001422 // markers must be replicated in the calling function to prevent the stack
1423 // coloring pass from merging slots which store input objects.
Vedant Kumar5f5cac32019-02-15 18:46:58 +00001424 ValueSet LifetimesStart;
1425 eraseLifetimeMarkersOnInputs(Blocks, SinkingCands, LifetimesStart);
Vedant Kumara1778df2019-01-04 17:43:22 +00001426
Chris Lattner3b2917b2004-05-12 06:01:40 +00001427 // Construct new function based on inputs/outputs & add allocas for all defs.
Vedant Kumara1778df2019-01-04 17:43:22 +00001428 Function *newFunction =
1429 constructFunction(inputs, outputs, header, newFuncRoot, codeReplacer,
1430 oldFunction, oldFunction->getParent());
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001431
Sean Silvaf8015752016-08-02 02:15:45 +00001432 // Update the entry count of the function.
1433 if (BFI) {
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001434 auto Count = BFI->getProfileCountFromFreq(EntryFreq.getFrequency());
1435 if (Count.hasValue())
1436 newFunction->setEntryCount(
1437 ProfileCount(Count.getValue(), Function::PCT_Real)); // FIXME
Sean Silvaf8015752016-08-02 02:15:45 +00001438 BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency());
1439 }
1440
Vedant Kumara1778df2019-01-04 17:43:22 +00001441 CallInst *TheCall =
1442 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001443
Chris Lattner9c431f62004-03-14 22:34:55 +00001444 moveCodeToFunction(newFunction);
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001445
Vedant Kumara1778df2019-01-04 17:43:22 +00001446 // Replicate the effects of any lifetime start/end markers which referenced
1447 // input objects in the extraction region by placing markers around the call.
Vedant Kumar5f5cac32019-02-15 18:46:58 +00001448 insertLifetimeMarkersSurroundingCall(
1449 oldFunction->getParent(), LifetimesStart.getArrayRef(), {}, TheCall);
Vedant Kumara1778df2019-01-04 17:43:22 +00001450
Sergey Dmitriev69c9cd22018-05-11 22:49:49 +00001451 // Propagate personality info to the new function if there is one.
1452 if (oldFunction->hasPersonalityFn())
1453 newFunction->setPersonalityFn(oldFunction->getPersonalityFn());
1454
Sean Silvaf8015752016-08-02 02:15:45 +00001455 // Update the branch weights for the exit block.
1456 if (BFI && NumExitBlocks > 1)
1457 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
1458
Vedant Kumard1295692018-12-03 22:40:21 +00001459 // Loop over all of the PHI nodes in the header and exit blocks, and change
1460 // any references to the old incoming edge to be the new incoming edge.
Reid Spencer66149462004-09-15 17:06:42 +00001461 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
1462 PHINode *PN = cast<PHINode>(I);
Chris Lattner320d59f2004-03-18 05:28:49 +00001463 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chandler Carruth0fde0012012-05-04 10:18:49 +00001464 if (!Blocks.count(PN->getIncomingBlock(i)))
Chris Lattner320d59f2004-03-18 05:28:49 +00001465 PN->setIncomingBlock(i, newFuncRoot);
Reid Spencer66149462004-09-15 17:06:42 +00001466 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001467
Vedant Kumard1295692018-12-03 22:40:21 +00001468 for (BasicBlock *ExitBB : ExitBlocks)
1469 for (PHINode &PN : ExitBB->phis()) {
Vedant Kumarc2990062018-10-24 22:15:41 +00001470 Value *IncomingCodeReplacerVal = nullptr;
Vedant Kumard1295692018-12-03 22:40:21 +00001471 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Vedant Kumarc2990062018-10-24 22:15:41 +00001472 // Ignore incoming values from outside of the extracted region.
Vedant Kumard1295692018-12-03 22:40:21 +00001473 if (!Blocks.count(PN.getIncomingBlock(i)))
Vedant Kumarc2990062018-10-24 22:15:41 +00001474 continue;
1475
1476 // Ensure that there is only one incoming value from codeReplacer.
1477 if (!IncomingCodeReplacerVal) {
Vedant Kumard1295692018-12-03 22:40:21 +00001478 PN.setIncomingBlock(i, codeReplacer);
1479 IncomingCodeReplacerVal = PN.getIncomingValue(i);
1480 } else
1481 assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) &&
Vedant Kumarc2990062018-10-24 22:15:41 +00001482 "PHI has two incompatbile incoming values from codeRepl");
Vedant Kumarc2990062018-10-24 22:15:41 +00001483 }
Chris Lattner56273822004-08-13 03:27:07 +00001484 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001485
Vedant Kumar15718a62018-10-15 19:22:20 +00001486 // Erase debug info intrinsics. Variable updates within the new function are
1487 // invisible to debuggers. This could be improved by defining a DISubprogram
1488 // for the new function.
1489 for (BasicBlock &BB : *newFunction) {
1490 auto BlockIt = BB.begin();
Vedant Kumar09b7aa42018-11-06 19:05:53 +00001491 // Remove debug info intrinsics from the new function.
Vedant Kumar15718a62018-10-15 19:22:20 +00001492 while (BlockIt != BB.end()) {
1493 Instruction *Inst = &*BlockIt;
1494 ++BlockIt;
1495 if (isa<DbgInfoIntrinsic>(Inst))
1496 Inst->eraseFromParent();
1497 }
Vedant Kumar09b7aa42018-11-06 19:05:53 +00001498 // Remove debug info intrinsics which refer to values in the new function
1499 // from the old function.
1500 SmallVector<DbgVariableIntrinsic *, 4> DbgUsers;
1501 for (Instruction &I : BB)
1502 findDbgUsers(DbgUsers, &I);
1503 for (DbgVariableIntrinsic *DVI : DbgUsers)
1504 DVI->eraseFromParent();
Vedant Kumar15718a62018-10-15 19:22:20 +00001505 }
1506
Vedant Kumar09415a82018-12-05 19:35:37 +00001507 // Mark the new function `noreturn` if applicable. Terminators which resume
1508 // exception propagation are treated as returning instructions. This is to
1509 // avoid inserting traps after calls to outlined functions which unwind.
Vedant Kumard6699422018-11-08 17:57:09 +00001510 bool doesNotReturn = none_of(*newFunction, [](const BasicBlock &BB) {
Vedant Kumar09415a82018-12-05 19:35:37 +00001511 const Instruction *Term = BB.getTerminator();
1512 return isa<ReturnInst>(Term) || isa<ResumeInst>(Term);
Vedant Kumard6699422018-11-08 17:57:09 +00001513 });
1514 if (doesNotReturn)
1515 newFunction->setDoesNotReturn();
1516
Vedant Kumarb2a6f8e2018-12-07 03:01:54 +00001517 LLVM_DEBUG(if (verifyFunction(*newFunction, &errs())) {
1518 newFunction->dump();
1519 report_fatal_error("verification of newFunction failed!");
1520 });
Vedant Kumard1295692018-12-03 22:40:21 +00001521 LLVM_DEBUG(if (verifyFunction(*oldFunction))
1522 report_fatal_error("verification of oldFunction failed!"));
Misha Brukmancaa1a5a2004-02-28 03:26:20 +00001523 return newFunction;
1524}