Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1 | //===- CodeExtractor.cpp - Pull code region into a new function -----------===// |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 6 | // |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This file implements the interface to tear out a code region, such as an |
| 10 | // individual loop or a parallel section, into a new function, replacing it with |
| 11 | // a call to the new function. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 15 | #include "llvm/Transforms/Utils/CodeExtractor.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 16 | #include "llvm/ADT/ArrayRef.h" |
| 17 | #include "llvm/ADT/DenseMap.h" |
| 18 | #include "llvm/ADT/Optional.h" |
Jakub Staszak | f23980a | 2013-02-09 01:04:28 +0000 | [diff] [blame] | 19 | #include "llvm/ADT/STLExtras.h" |
Chandler Carruth | 8a8cd2b | 2014-01-07 11:48:04 +0000 | [diff] [blame] | 20 | #include "llvm/ADT/SetVector.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 21 | #include "llvm/ADT/SmallPtrSet.h" |
| 22 | #include "llvm/ADT/SmallVector.h" |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 24 | #include "llvm/Analysis/BlockFrequencyInfoImpl.h" |
| 25 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/LoopInfo.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 27 | #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 Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 32 | #include "llvm/IR/Constants.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 33 | #include "llvm/IR/DataLayout.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 34 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 35 | #include "llvm/IR/Dominators.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 36 | #include "llvm/IR/Function.h" |
| 37 | #include "llvm/IR/GlobalValue.h" |
| 38 | #include "llvm/IR/InstrTypes.h" |
| 39 | #include "llvm/IR/Instruction.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 40 | #include "llvm/IR/Instructions.h" |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 41 | #include "llvm/IR/IntrinsicInst.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 42 | #include "llvm/IR/Intrinsics.h" |
| 43 | #include "llvm/IR/LLVMContext.h" |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 44 | #include "llvm/IR/MDBuilder.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 45 | #include "llvm/IR/Module.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 46 | #include "llvm/IR/Type.h" |
| 47 | #include "llvm/IR/User.h" |
| 48 | #include "llvm/IR/Value.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 49 | #include "llvm/IR/Verifier.h" |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 50 | #include "llvm/Pass.h" |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 51 | #include "llvm/Support/BlockFrequency.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 52 | #include "llvm/Support/BranchProbability.h" |
| 53 | #include "llvm/Support/Casting.h" |
Reid Spencer | 7c16caa | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 54 | #include "llvm/Support/CommandLine.h" |
| 55 | #include "llvm/Support/Debug.h" |
Torok Edwin | ccb29cd | 2009-07-11 13:10:19 +0000 | [diff] [blame] | 56 | #include "llvm/Support/ErrorHandling.h" |
Chris Lattner | b25de3f | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 57 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 58 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Vedant Kumar | 09b7aa4 | 2018-11-06 19:05:53 +0000 | [diff] [blame] | 59 | #include "llvm/Transforms/Utils/Local.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 60 | #include <cassert> |
| 61 | #include <cstdint> |
| 62 | #include <iterator> |
| 63 | #include <map> |
Chris Lattner | 9c431f6 | 2004-03-14 22:34:55 +0000 | [diff] [blame] | 64 | #include <set> |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 65 | #include <utility> |
| 66 | #include <vector> |
| 67 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 68 | using namespace llvm; |
Easwaran Raman | e5b8de2 | 2018-01-17 22:24:23 +0000 | [diff] [blame] | 69 | using ProfileCount = Function::ProfileCount; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 70 | |
Chandler Carruth | e96dd89 | 2014-04-21 22:55:11 +0000 | [diff] [blame] | 71 | #define DEBUG_TYPE "code-extractor" |
| 72 | |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 73 | // Provide a command-line option to aggregate function arguments into a struct |
Misha Brukman | 234b44a | 2008-12-13 05:21:37 +0000 | [diff] [blame] | 74 | // for functions produced by the code extractor. This is useful when converting |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 75 | // extracted functions to pthread-based code, as only one argument (void*) can |
| 76 | // be passed in to pthread_create(). |
| 77 | static cl::opt<bool> |
| 78 | AggregateArgsOpt("aggregate-extracted-args", cl::Hidden, |
| 79 | cl::desc("Aggregate arguments to code-extracted functions")); |
| 80 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 81 | /// Test whether a block is valid for extraction. |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 82 | static bool isBlockValidForExtraction(const BasicBlock &BB, |
| 83 | const SetVector<BasicBlock *> &Result, |
| 84 | bool AllowVarArgs, bool AllowAlloca) { |
Serge Guelton | 7bc405a | 2017-06-27 18:57:53 +0000 | [diff] [blame] | 85 | // 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 Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 112 | |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 113 | // If explicitly requested, allow vastart and alloca. For invoke instructions |
| 114 | // verify that extraction is valid. |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 115 | for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) { |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 116 | 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 Kumar | 1e209e2 | 2018-11-06 19:06:08 +0000 | [diff] [blame] | 170 | 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 Hahn | 0e9dec6 | 2017-11-13 10:35:52 +0000 | [diff] [blame] | 174 | if (AllowVarArgs) |
| 175 | continue; |
| 176 | else |
| 177 | return false; |
| 178 | } |
Vedant Kumar | 1e209e2 | 2018-11-06 19:06:08 +0000 | [diff] [blame] | 179 | |
| 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 Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 186 | } |
| 187 | |
| 188 | return true; |
| 189 | } |
| 190 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 191 | /// Build a set of blocks to extract if the input blocks are viable. |
Davide Italiano | 059574c | 2017-04-21 00:21:09 +0000 | [diff] [blame] | 192 | static SetVector<BasicBlock *> |
Florian Hahn | 0e9dec6 | 2017-11-13 10:35:52 +0000 | [diff] [blame] | 193 | buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 194 | bool AllowVarArgs, bool AllowAlloca) { |
Davide Italiano | fa15de3 | 2017-04-21 04:25:00 +0000 | [diff] [blame] | 195 | assert(!BBs.empty() && "The set of blocks to extract must be non-empty"); |
Davide Italiano | 059574c | 2017-04-21 00:21:09 +0000 | [diff] [blame] | 196 | SetVector<BasicBlock *> Result; |
Chandler Carruth | 2f5d019 | 2012-05-04 10:26:45 +0000 | [diff] [blame] | 197 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 198 | // Loop over the blocks, adding them to our set-vector, and aborting with an |
| 199 | // empty set if we encounter invalid blocks. |
Davide Italiano | fa15de3 | 2017-04-21 04:25:00 +0000 | [diff] [blame] | 200 | for (BasicBlock *BB : BBs) { |
Davide Italiano | fa15de3 | 2017-04-21 04:25:00 +0000 | [diff] [blame] | 201 | // 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 Italiano | fa15de3 | 2017-04-21 04:25:00 +0000 | [diff] [blame] | 207 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 208 | |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 209 | 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 Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 216 | LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n"); |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 217 | 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 Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 226 | LLVM_DEBUG( |
| 227 | dbgs() << "No blocks in this region may have entries from " |
| 228 | "outside the region except for the first block!\n"); |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 229 | return {}; |
| 230 | } |
| 231 | } |
Chandler Carruth | 2f5d019 | 2012-05-04 10:26:45 +0000 | [diff] [blame] | 232 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 233 | return Result; |
| 234 | } |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 235 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 236 | CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 237 | bool AggregateArgs, BlockFrequencyInfo *BFI, |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 238 | BranchProbabilityInfo *BPI, bool AllowVarArgs, |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 239 | bool AllowAlloca, std::string Suffix) |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 240 | : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), |
Florian Hahn | 0e9dec6 | 2017-11-13 10:35:52 +0000 | [diff] [blame] | 241 | BPI(BPI), AllowVarArgs(AllowVarArgs), |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 242 | Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)), |
| 243 | Suffix(Suffix) {} |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 244 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 245 | CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs, |
| 246 | BlockFrequencyInfo *BFI, |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 247 | BranchProbabilityInfo *BPI, std::string Suffix) |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 248 | : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), |
Florian Hahn | 7114755 | 2017-11-13 11:08:47 +0000 | [diff] [blame] | 249 | BPI(BPI), AllowVarArgs(false), |
| 250 | Blocks(buildExtractionBlockSet(L.getBlocks(), &DT, |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 251 | /* AllowVarArgs */ false, |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 252 | /* AllowAlloca */ false)), |
| 253 | Suffix(Suffix) {} |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 254 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 255 | /// definedInRegion - Return true if the specified value is defined in the |
| 256 | /// extracted region. |
| 257 | static 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. |
| 267 | static 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 Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 273 | } |
| 274 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 275 | static 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 | |
| 300 | bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers( |
| 301 | Instruction *Addr) const { |
| 302 | AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets()); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 303 | Function *Func = (*Blocks.begin())->getParent(); |
| 304 | for (BasicBlock &BB : *Func) { |
| 305 | if (Blocks.count(&BB)) |
| 306 | continue; |
| 307 | for (Instruction &II : BB) { |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 308 | 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 Kumar | b264d69 | 2018-12-21 21:49:40 +0000 | [diff] [blame] | 334 | if (IntrInst->isLifetimeStartOrEnd()) |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 335 | 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 | |
| 349 | BasicBlock * |
| 350 | CodeExtractor::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 Hahn | b93c063 | 2017-11-01 09:48:12 +0000 | [diff] [blame] | 391 | for (auto PI = pred_begin(CommonExitBlock), PE = pred_end(CommonExitBlock); |
| 392 | PI != PE;) { |
| 393 | BasicBlock *Pred = *PI++; |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 394 | 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 | |
| 403 | void 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 Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 412 | auto *AI = dyn_cast<AllocaInst>(&II); |
| 413 | if (!AI) |
| 414 | continue; |
| 415 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 416 | // 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 Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 424 | Instruction *LifeStart = nullptr, *LifeEnd = nullptr; |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 425 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 426 | for (User *U : Addr->users()) { |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 427 | IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U); |
| 428 | if (IntrInst) { |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 429 | 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 Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 433 | LifeStart = IntrInst; |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 434 | } |
| 435 | if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) { |
| 436 | if (LifeEnd) |
| 437 | return std::make_pair<Instruction *>(nullptr, nullptr); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 438 | LifeEnd = IntrInst; |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 439 | } |
| 440 | continue; |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 441 | } |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 442 | // Find untracked uses of the address, bail. |
| 443 | if (!definedInRegion(Blocks, U)) |
| 444 | return std::make_pair<Instruction *>(nullptr, nullptr); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 445 | } |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 446 | |
| 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 Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 462 | }; |
| 463 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 464 | 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 Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 470 | SinkCands.insert(AI); |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 471 | if (HoistLifeEnd) |
| 472 | HoistCands.insert(Markers.second); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 473 | continue; |
| 474 | } |
| 475 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 476 | // Follow the bitcast. |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 477 | Instruction *MarkerAddr = nullptr; |
| 478 | for (User *U : AI->users()) { |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 479 | if (U->stripInBoundsConstantOffsets() == AI) { |
| 480 | SinkLifeStart = false; |
| 481 | HoistLifeEnd = false; |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 482 | Instruction *Bitcast = cast<Instruction>(U); |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 483 | Markers = GetLifeTimeMarkers(Bitcast, SinkLifeStart, HoistLifeEnd); |
| 484 | if (Markers.first) { |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 485 | MarkerAddr = Bitcast; |
| 486 | continue; |
| 487 | } |
| 488 | } |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 489 | |
| 490 | // Found unknown use of AI. |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 491 | if (!definedInRegion(Blocks, U)) { |
| 492 | MarkerAddr = nullptr; |
| 493 | break; |
| 494 | } |
| 495 | } |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 496 | |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 497 | if (MarkerAddr) { |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 498 | if (SinkLifeStart) |
| 499 | SinkCands.insert(Markers.first); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 500 | if (!definedInRegion(Blocks, MarkerAddr)) |
| 501 | SinkCands.insert(MarkerAddr); |
| 502 | SinkCands.insert(AI); |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 503 | if (HoistLifeEnd) |
| 504 | HoistCands.insert(Markers.second); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 505 | } |
| 506 | } |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs, |
| 511 | const ValueSet &SinkCands) const { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 512 | for (BasicBlock *BB : Blocks) { |
Chandler Carruth | 14316fc | 2012-05-04 11:20:27 +0000 | [diff] [blame] | 513 | // 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 Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 515 | for (Instruction &II : *BB) { |
| 516 | for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE; |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 517 | ++OI) { |
| 518 | Value *V = *OI; |
| 519 | if (!SinkCands.count(V) && definedInCaller(Blocks, V)) |
| 520 | Inputs.insert(V); |
| 521 | } |
Chandler Carruth | 14316fc | 2012-05-04 11:20:27 +0000 | [diff] [blame] | 522 | |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 523 | for (User *U : II.users()) |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 524 | if (!definedInRegion(Blocks, U)) { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 525 | Outputs.insert(&II); |
Chandler Carruth | 14316fc | 2012-05-04 11:20:27 +0000 | [diff] [blame] | 526 | break; |
| 527 | } |
| 528 | } |
| 529 | } |
| 530 | } |
| 531 | |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 532 | /// 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. |
| 535 | void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) { |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 536 | unsigned NumPredsFromRegion = 0; |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 537 | unsigned NumPredsOutsideRegion = 0; |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 538 | |
Dan Gohman | dcb291f | 2007-03-22 16:38:57 +0000 | [diff] [blame] | 539 | if (Header != &Header->getParent()->getEntryBlock()) { |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 540 | PHINode *PN = dyn_cast<PHINode>(Header->begin()); |
| 541 | if (!PN) return; // No PHI nodes. |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 542 | |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 543 | // 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 Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 547 | if (Blocks.count(PN->getIncomingBlock(i))) |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 548 | ++NumPredsFromRegion; |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 549 | 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 Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 561 | BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 562 | |
| 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 Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 566 | Blocks.remove(OldPred); |
| 567 | Blocks.insert(NewBB); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 568 | Header = NewBB; |
| 569 | |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 570 | // 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 Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 572 | if (NumPredsFromRegion) { |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 573 | 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 Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 577 | if (Blocks.count(PN->getIncomingBlock(i))) { |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 578 | Instruction *TI = PN->getIncomingBlock(i)->getTerminator(); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 579 | TI->replaceUsesOfWith(OldPred, NewBB); |
| 580 | } |
| 581 | |
Chris Lattner | 0ab5e2c | 2011-04-15 05:18:47 +0000 | [diff] [blame] | 582 | // Okay, everything within the region is now branching to the right block, we |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 583 | // just have to update the PHI nodes now, inserting PHI nodes into NewBB. |
Xinliang David Li | 99e3ca1 | 2017-04-20 21:40:22 +0000 | [diff] [blame] | 584 | BasicBlock::iterator AfterPHIs; |
Reid Spencer | 6614946 | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 585 | for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) { |
| 586 | PHINode *PN = cast<PHINode>(AfterPHIs); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 587 | // Create a new PHI node in the new region, which has an incoming value |
| 588 | // from OldPred of PN. |
Jay Foad | 5213134 | 2011-03-30 11:28:46 +0000 | [diff] [blame] | 589 | PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion, |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 590 | PN->getName() + ".ce", &NewBB->front()); |
Xinliang David Li | f12a0fa | 2017-04-25 04:51:19 +0000 | [diff] [blame] | 591 | PN->replaceAllUsesWith(NewPN); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 592 | 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 Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 597 | if (Blocks.count(PN->getIncomingBlock(i))) { |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 598 | NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i)); |
| 599 | PN->removeIncomingValue(i); |
| 600 | --i; |
| 601 | } |
| 602 | } |
| 603 | } |
| 604 | } |
Chris Lattner | 13d2ddf | 2004-05-12 16:07:41 +0000 | [diff] [blame] | 605 | } |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 606 | |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 607 | /// 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. |
| 611 | void 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 Lattner | 13d2ddf | 2004-05-12 16:07:41 +0000 | [diff] [blame] | 657 | void CodeExtractor::splitReturnBlocks() { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 658 | for (BasicBlock *Block : Blocks) |
| 659 | if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) { |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 660 | BasicBlock *New = |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 661 | Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret"); |
Owen Anderson | b4aa5b1 | 2009-08-24 23:32:14 +0000 | [diff] [blame] | 662 | if (DT) { |
Gabor Greif | 2f5f696 | 2010-09-10 22:25:58 +0000 | [diff] [blame] | 663 | // Old dominates New. New node dominates all other nodes dominated |
| 664 | // by Old. |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 665 | DomTreeNode *OldNode = DT->getNode(Block); |
| 666 | SmallVector<DomTreeNode *, 8> Children(OldNode->begin(), |
| 667 | OldNode->end()); |
Owen Anderson | b4aa5b1 | 2009-08-24 23:32:14 +0000 | [diff] [blame] | 668 | |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 669 | DomTreeNode *NewNode = DT->addNewBlock(New, Block); |
Owen Anderson | b4aa5b1 | 2009-08-24 23:32:14 +0000 | [diff] [blame] | 670 | |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 671 | for (DomTreeNode *I : Children) |
| 672 | DT->changeImmediateDominator(I, NewNode); |
Owen Anderson | b4aa5b1 | 2009-08-24 23:32:14 +0000 | [diff] [blame] | 673 | } |
| 674 | } |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 675 | } |
| 676 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 677 | /// constructFunction - make a function based on inputs and outputs, as follows: |
| 678 | /// f(in0, ..., inN, out0, ..., outN) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 679 | Function *CodeExtractor::constructFunction(const ValueSet &inputs, |
| 680 | const ValueSet &outputs, |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 681 | BasicBlock *header, |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 682 | BasicBlock *newRootNode, |
| 683 | BasicBlock *newHeader, |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 684 | Function *oldFunction, |
| 685 | Module *M) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 686 | LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n"); |
| 687 | LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n"); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 688 | |
| 689 | // This function returns unsigned, outputs will go back by reference. |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 690 | switch (NumExitBlocks) { |
| 691 | case 0: |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 692 | 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 Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 695 | } |
| 696 | |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 697 | std::vector<Type *> paramTy; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 698 | |
| 699 | // Add the types of the input values to the function's argument list |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 700 | for (Value *value : inputs) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 701 | LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n"); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 702 | paramTy.push_back(value->getType()); |
| 703 | } |
| 704 | |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 705 | // Add the types of the output values to the function's argument list. |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 706 | for (Value *output : outputs) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 707 | LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n"); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 708 | if (AggregateArgs) |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 709 | paramTy.push_back(output->getType()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 710 | else |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 711 | paramTy.push_back(PointerType::getUnqual(output->getType())); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 712 | } |
| 713 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 714 | LLVM_DEBUG({ |
Benjamin Kramer | 706e4883 | 2016-06-26 13:39:33 +0000 | [diff] [blame] | 715 | dbgs() << "Function type: " << *RetTy << " f("; |
| 716 | for (Type *i : paramTy) |
| 717 | dbgs() << *i << ", "; |
| 718 | dbgs() << ")\n"; |
| 719 | }); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 720 | |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 721 | StructType *StructTy; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 722 | if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 723 | StructTy = StructType::get(M->getContext(), paramTy); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 724 | paramTy.clear(); |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 725 | paramTy.push_back(PointerType::getUnqual(StructTy)); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 726 | } |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 727 | FunctionType *funcType = |
Florian Hahn | 0e9dec6 | 2017-11-13 10:35:52 +0000 | [diff] [blame] | 728 | FunctionType::get(RetTy, paramTy, |
| 729 | AllowVarArgs && oldFunction->isVarArg()); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 730 | |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 731 | std::string SuffixToUse = |
| 732 | Suffix.empty() |
| 733 | ? (header->getName().empty() ? "extracted" : header->getName().str()) |
| 734 | : Suffix; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 735 | // Create the new function |
Alexander Richardson | 6bcf2ba | 2018-08-23 09:25:17 +0000 | [diff] [blame] | 736 | Function *newFunction = Function::Create( |
| 737 | funcType, GlobalValue::InternalLinkage, oldFunction->getAddressSpace(), |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 738 | oldFunction->getName() + "." + SuffixToUse, M); |
Chris Lattner | 4caf5eb | 2008-12-18 05:52:56 +0000 | [diff] [blame] | 739 | // If the old function is no-throw, so is the new one. |
| 740 | if (oldFunction->doesNotThrow()) |
Bill Wendling | f319e99 | 2012-10-10 03:12:49 +0000 | [diff] [blame] | 741 | newFunction->setDoesNotThrow(); |
Sean Silva | a0a802a | 2016-08-01 03:15:32 +0000 | [diff] [blame] | 742 | |
| 743 | // Inherit the uwtable attribute if we need to. |
| 744 | if (oldFunction->hasUWTable()) |
| 745 | newFunction->setHasUWTable(); |
| 746 | |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 747 | // Inherit all of the target dependent attributes and white-listed |
| 748 | // target independent attributes. |
Sean Silva | a0a802a | 2016-08-01 03:15:32 +0000 | [diff] [blame] | 749 | // (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 Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 754 | 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 Morehouse | 236cdaf | 2018-03-22 17:07:51 +0000 | [diff] [blame] | 810 | case Attribute::OptForFuzzing: |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 811 | case Attribute::OptimizeNone: |
| 812 | case Attribute::OptimizeForSize: |
| 813 | case Attribute::SafeStack: |
Vlad Tsyrklevich | d17f61e | 2018-04-03 20:10:40 +0000 | [diff] [blame] | 814 | case Attribute::ShadowCallStack: |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 815 | case Attribute::SanitizeAddress: |
| 816 | case Attribute::SanitizeMemory: |
| 817 | case Attribute::SanitizeThread: |
| 818 | case Attribute::SanitizeHWAddress: |
Chandler Carruth | 664aa86 | 2018-09-04 12:38:00 +0000 | [diff] [blame] | 819 | case Attribute::SpeculativeLoadHardening: |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 820 | case Attribute::StackProtect: |
| 821 | case Attribute::StackProtectReq: |
| 822 | case Attribute::StackProtectStrong: |
| 823 | case Attribute::StrictFP: |
| 824 | case Attribute::UWTable: |
Oren Ben Simhon | fdd72fd | 2018-03-17 13:29:46 +0000 | [diff] [blame] | 825 | case Attribute::NoCfCheck: |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 826 | break; |
| 827 | } |
Sean Silva | a0a802a | 2016-08-01 03:15:32 +0000 | [diff] [blame] | 828 | |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 829 | newFunction->addFnAttr(Attr); |
| 830 | } |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 831 | newFunction->getBasicBlockList().push_back(newRootNode); |
| 832 | |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 833 | // Create an iterator to name all of the arguments we inserted. |
Chris Lattner | 531f9e9 | 2005-03-15 04:54:21 +0000 | [diff] [blame] | 834 | Function::arg_iterator AI = newFunction->arg_begin(); |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 835 | |
| 836 | // Rewrite all users of the inputs in the extracted region to use the |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 837 | // 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 Greene | c656cbb | 2007-09-04 15:46:09 +0000 | [diff] [blame] | 841 | Value *Idx[2]; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 842 | Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext())); |
| 843 | Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i); |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 844 | Instruction *TI = newFunction->begin()->getTerminator(); |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 845 | GetElementPtrInst *GEP = GetElementPtrInst::Create( |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 846 | StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI); |
Daniel Dunbar | 12368685 | 2009-07-24 08:24:36 +0000 | [diff] [blame] | 847 | RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 848 | } else |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 849 | RewriteVal = &*AI++; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 850 | |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 851 | std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end()); |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 852 | for (User *use : Users) |
| 853 | if (Instruction *inst = dyn_cast<Instruction>(use)) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 854 | if (Blocks.count(inst->getParent())) |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 855 | inst->replaceUsesOfWith(inputs[i], RewriteVal); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 856 | } |
| 857 | |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 858 | // Set names for input and output arguments. |
| 859 | if (!AggregateArgs) { |
Chris Lattner | 531f9e9 | 2005-03-15 04:54:21 +0000 | [diff] [blame] | 860 | AI = newFunction->arg_begin(); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 861 | for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI) |
Owen Anderson | 7629b71 | 2008-04-14 17:38:21 +0000 | [diff] [blame] | 862 | AI->setName(inputs[i]->getName()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 863 | for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI) |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 864 | AI->setName(outputs[i]->getName()+".out"); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 865 | } |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 866 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 867 | // 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 Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 870 | std::vector<User *> Users(header->user_begin(), header->user_end()); |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 871 | 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 Carruth | 8b7a812 | 2018-10-18 00:38:54 +0000 | [diff] [blame] | 874 | 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 Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 878 | |
| 879 | return newFunction; |
| 880 | } |
| 881 | |
Vedant Kumar | 17d9f14 | 2019-01-19 02:37:59 +0000 | [diff] [blame] | 882 | /// 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). |
| 888 | static SetVector<Value *> |
| 889 | eraseLifetimeMarkersOnInputs(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. |
| 915 | static 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 Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 947 | /// 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 Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 950 | CallInst *CodeExtractor::emitCallAndSwitchStatement(Function *newFunction, |
| 951 | BasicBlock *codeReplacer, |
| 952 | ValueSet &inputs, |
| 953 | ValueSet &outputs) { |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 954 | // 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 Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 956 | std::vector<Value *> params, StructValues, ReloadOutputs, Reloads; |
Matt Arsenault | 3c1fc76 | 2017-04-10 22:27:50 +0000 | [diff] [blame] | 957 | |
| 958 | Module *M = newFunction->getParent(); |
| 959 | LLVMContext &Context = M->getContext(); |
| 960 | const DataLayout &DL = M->getDataLayout(); |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 961 | CallInst *call = nullptr; |
Chris Lattner | d8017a3 | 2004-03-18 04:12:05 +0000 | [diff] [blame] | 962 | |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 963 | // Add inputs as params, or to be filled into the struct |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 964 | for (Value *input : inputs) |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 965 | if (AggregateArgs) |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 966 | StructValues.push_back(input); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 967 | else |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 968 | params.push_back(input); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 969 | |
| 970 | // Create allocas for the outputs |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 971 | for (Value *output : outputs) { |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 972 | if (AggregateArgs) { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 973 | StructValues.push_back(output); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 974 | } else { |
| 975 | AllocaInst *alloca = |
Matt Arsenault | 3c1fc76 | 2017-04-10 22:27:50 +0000 | [diff] [blame] | 976 | new AllocaInst(output->getType(), DL.getAllocaAddrSpace(), |
| 977 | nullptr, output->getName() + ".loc", |
| 978 | &codeReplacer->getParent()->front().front()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 979 | ReloadOutputs.push_back(alloca); |
| 980 | params.push_back(alloca); |
| 981 | } |
| 982 | } |
| 983 | |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 984 | StructType *StructArgTy = nullptr; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 985 | AllocaInst *Struct = nullptr; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 986 | if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 987 | std::vector<Type *> ArgTypes; |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 988 | for (ValueSet::iterator v = StructValues.begin(), |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 989 | ve = StructValues.end(); v != ve; ++v) |
| 990 | ArgTypes.push_back((*v)->getType()); |
| 991 | |
| 992 | // Allocate a struct at the beginning of this function |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 993 | StructArgTy = StructType::get(newFunction->getContext(), ArgTypes); |
Matt Arsenault | 3c1fc76 | 2017-04-10 22:27:50 +0000 | [diff] [blame] | 994 | Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr, |
| 995 | "structArg", |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 996 | &codeReplacer->getParent()->front().front()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 997 | params.push_back(Struct); |
| 998 | |
| 999 | for (unsigned i = 0, e = inputs.size(); i != e; ++i) { |
David Greene | c656cbb | 2007-09-04 15:46:09 +0000 | [diff] [blame] | 1000 | Value *Idx[2]; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1001 | Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); |
| 1002 | Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i); |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 1003 | GetElementPtrInst *GEP = GetElementPtrInst::Create( |
| 1004 | StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1005 | codeReplacer->getInstList().push_back(GEP); |
| 1006 | StoreInst *SI = new StoreInst(StructValues[i], GEP); |
| 1007 | codeReplacer->getInstList().push_back(SI); |
| 1008 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1009 | } |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1010 | |
| 1011 | // Emit the call to the function |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1012 | call = CallInst::Create(newFunction, params, |
| 1013 | NumExitBlocks > 1 ? "targetBlock" : ""); |
Florian Hahn | e5089e2 | 2017-12-08 21:49:03 +0000 | [diff] [blame] | 1014 | // 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 Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1022 | codeReplacer->getInstList().push_back(call); |
| 1023 | |
Chris Lattner | 531f9e9 | 2005-03-15 04:54:21 +0000 | [diff] [blame] | 1024 | Function::arg_iterator OutputArgBegin = newFunction->arg_begin(); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1025 | unsigned FirstOut = inputs.size(); |
| 1026 | if (!AggregateArgs) |
| 1027 | std::advance(OutputArgBegin, inputs.size()); |
| 1028 | |
Jakub Kuderski | cbe9fae | 2017-10-06 03:37:06 +0000 | [diff] [blame] | 1029 | // Reload the outputs passed in by reference. |
| 1030 | Function::arg_iterator OAI = OutputArgBegin; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1031 | for (unsigned i = 0, e = outputs.size(); i != e; ++i) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1032 | Value *Output = nullptr; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1033 | if (AggregateArgs) { |
David Greene | c656cbb | 2007-09-04 15:46:09 +0000 | [diff] [blame] | 1034 | Value *Idx[2]; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1035 | Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); |
| 1036 | Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i); |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 1037 | GetElementPtrInst *GEP = GetElementPtrInst::Create( |
| 1038 | StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1039 | 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 Anderson | 34e6148 | 2009-08-25 00:54:39 +0000 | [diff] [blame] | 1045 | Reloads.push_back(load); |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 1046 | codeReplacer->getInstList().push_back(load); |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 1047 | std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end()); |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 1048 | for (unsigned u = 0, e = Users.size(); u != e; ++u) { |
| 1049 | Instruction *inst = cast<Instruction>(Users[u]); |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1050 | if (!Blocks.count(inst->getParent())) |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 1051 | inst->replaceUsesOfWith(outputs[i], load); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1052 | } |
Jakub Kuderski | cbe9fae | 2017-10-06 03:37:06 +0000 | [diff] [blame] | 1053 | |
| 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 Hahn | 7cdf52e | 2018-08-21 20:07:46 +0000 | [diff] [blame] | 1058 | |
Jakub Kuderski | cbe9fae | 2017-10-06 03:37:06 +0000 | [diff] [blame] | 1059 | // Find proper insertion point. |
Vedant Kumar | b2a6f8e | 2018-12-07 03:01:54 +0000 | [diff] [blame] | 1060 | BasicBlock::iterator InsertPt; |
Florian Hahn | 7cdf52e | 2018-08-21 20:07:46 +0000 | [diff] [blame] | 1061 | // 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 Kumar | b2a6f8e | 2018-12-07 03:01:54 +0000 | [diff] [blame] | 1064 | InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt(); |
| 1065 | else if (auto *Phi = dyn_cast<PHINode>(OutI)) |
| 1066 | InsertPt = Phi->getParent()->getFirstInsertionPt(); |
Florian Hahn | 7cdf52e | 2018-08-21 20:07:46 +0000 | [diff] [blame] | 1067 | else |
Vedant Kumar | b2a6f8e | 2018-12-07 03:01:54 +0000 | [diff] [blame] | 1068 | InsertPt = std::next(OutI->getIterator()); |
Jakub Kuderski | cbe9fae | 2017-10-06 03:37:06 +0000 | [diff] [blame] | 1069 | |
| 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 Kumar | b2a6f8e | 2018-12-07 03:01:54 +0000 | [diff] [blame] | 1078 | StructArgTy, &*OAI, Idx, "gep_" + outputs[i]->getName(), &*InsertPt); |
| 1079 | new StoreInst(outputs[i], GEP, &*InsertPt); |
Jakub Kuderski | cbe9fae | 2017-10-06 03:37:06 +0000 | [diff] [blame] | 1080 | // 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 Kumar | b2a6f8e | 2018-12-07 03:01:54 +0000 | [diff] [blame] | 1084 | new StoreInst(outputs[i], &*OAI, &*InsertPt); |
Jakub Kuderski | cbe9fae | 2017-10-06 03:37:06 +0000 | [diff] [blame] | 1085 | ++OAI; |
| 1086 | } |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1087 | } |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1088 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1089 | // Now we can emit a switch statement using the call as a value. |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1090 | SwitchInst *TheSwitch = |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1091 | SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)), |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1092 | codeReplacer, 0, codeReplacer); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1093 | |
| 1094 | // Since there may be multiple exits from the original region, make the new |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1095 | // 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 Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 1099 | std::map<BasicBlock *, BasicBlock *> ExitBlockMap; |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1100 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1101 | unsigned switchVal = 0; |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1102 | for (BasicBlock *Block : Blocks) { |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 1103 | Instruction *TI = Block->getTerminator(); |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1104 | for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1105 | if (!Blocks.count(TI->getSuccessor(i))) { |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1106 | 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 Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1112 | NewTarget = BasicBlock::Create(Context, |
| 1113 | OldTarget->getName() + ".exitStub", |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1114 | newFunction); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1115 | unsigned SuccNum = switchVal++; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1116 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1117 | Value *brVal = nullptr; |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1118 | switch (NumExitBlocks) { |
| 1119 | case 0: |
| 1120 | case 1: break; // No value needed. |
| 1121 | case 2: // Conditional branch, return a bool |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1122 | brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1123 | break; |
| 1124 | default: |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1125 | brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1126 | break; |
| 1127 | } |
| 1128 | |
Jakub Kuderski | cbe9fae | 2017-10-06 03:37:06 +0000 | [diff] [blame] | 1129 | ReturnInst::Create(Context, brVal, NewTarget); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1130 | |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1131 | // Update the switch instruction. |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1132 | TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context), |
| 1133 | SuccNum), |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1134 | OldTarget); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1135 | } |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1136 | |
| 1137 | // rewrite the original branch instruction with this new target |
| 1138 | TI->setSuccessor(i, NewTarget); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1139 | } |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1140 | } |
Chris Lattner | 5b2072e | 2004-03-14 23:43:24 +0000 | [diff] [blame] | 1141 | |
Chris Lattner | 3d1ca67 | 2004-05-12 03:22:33 +0000 | [diff] [blame] | 1142 | // Now that we've done the deed, simplify the switch instruction. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1143 | Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType(); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1144 | switch (NumExitBlocks) { |
| 1145 | case 0: |
Chris Lattner | 7f1c7ed | 2004-08-12 03:17:02 +0000 | [diff] [blame] | 1146 | // There are no successors (the block containing the switch itself), which |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1147 | // means that previously this was the last part of the function, and hence |
| 1148 | // this should be rewritten as a `ret' |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1149 | |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1150 | // Check if the function should return a value |
Benjamin Kramer | ccce8ba | 2010-01-05 13:12:22 +0000 | [diff] [blame] | 1151 | if (OldFnRetTy->isVoidTy()) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1152 | ReturnInst::Create(Context, nullptr, TheSwitch); // Return void |
Chris Lattner | 7f1c7ed | 2004-08-12 03:17:02 +0000 | [diff] [blame] | 1153 | } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) { |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1154 | // return what we have |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1155 | ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch); |
Chris Lattner | 7f1c7ed | 2004-08-12 03:17:02 +0000 | [diff] [blame] | 1156 | } else { |
| 1157 | // Otherwise we must have code extracted an unwind or something, just |
| 1158 | // return whatever we want. |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 1159 | ReturnInst::Create(Context, |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1160 | Constant::getNullValue(OldFnRetTy), TheSwitch); |
Chris Lattner | 7f1c7ed | 2004-08-12 03:17:02 +0000 | [diff] [blame] | 1161 | } |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1162 | |
Dan Gohman | 158ff2c | 2008-06-21 22:08:46 +0000 | [diff] [blame] | 1163 | TheSwitch->eraseFromParent(); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1164 | break; |
| 1165 | case 1: |
| 1166 | // Only a single destination, change the switch into an unconditional |
| 1167 | // branch. |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1168 | BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch); |
Dan Gohman | 158ff2c | 2008-06-21 22:08:46 +0000 | [diff] [blame] | 1169 | TheSwitch->eraseFromParent(); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1170 | break; |
| 1171 | case 2: |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1172 | BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2), |
| 1173 | call, TheSwitch); |
Dan Gohman | 158ff2c | 2008-06-21 22:08:46 +0000 | [diff] [blame] | 1174 | TheSwitch->eraseFromParent(); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1175 | break; |
| 1176 | default: |
| 1177 | // Otherwise, make the default destination of the switch instruction be one |
| 1178 | // of the other successors. |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 1179 | TheSwitch->setCondition(call); |
| 1180 | TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks)); |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 1181 | // Remove redundant case |
Bob Wilson | e407736 | 2013-09-09 19:14:35 +0000 | [diff] [blame] | 1182 | TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1)); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1183 | break; |
Chris Lattner | 5b2072e | 2004-03-14 23:43:24 +0000 | [diff] [blame] | 1184 | } |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1185 | |
Vedant Kumar | 17d9f14 | 2019-01-19 02:37:59 +0000 | [diff] [blame] | 1186 | // 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 Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1190 | return call; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1191 | } |
| 1192 | |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1193 | void CodeExtractor::moveCodeToFunction(Function *newFunction) { |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1194 | Function *oldFunc = (*Blocks.begin())->getParent(); |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1195 | Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList(); |
| 1196 | Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList(); |
| 1197 | |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1198 | for (BasicBlock *Block : Blocks) { |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1199 | // Delete the basic block from the old function, and the list of blocks |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1200 | oldBlocks.remove(Block); |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1201 | |
| 1202 | // Insert this basic block into the new function |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1203 | newBlocks.push_back(Block); |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1204 | } |
| 1205 | } |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1206 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1207 | void CodeExtractor::calculateNewCallTerminatorWeights( |
| 1208 | BasicBlock *CodeReplacer, |
| 1209 | DenseMap<BasicBlock *, BlockFrequency> &ExitWeights, |
| 1210 | BranchProbabilityInfo *BPI) { |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 1211 | using Distribution = BlockFrequencyInfoImplBase::Distribution; |
| 1212 | using BlockNode = BlockFrequencyInfoImplBase::BlockNode; |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1213 | |
| 1214 | // Update the branch weights for the exit block. |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 1215 | Instruction *TI = CodeReplacer->getTerminator(); |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1216 | 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 Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1252 | Function *CodeExtractor::extractCodeRegion() { |
| 1253 | if (!isEligible()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1254 | return nullptr; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1255 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1256 | // Assumption: this is a single-entry code region, and the header is the first |
Chris Lattner | 73ab1fa | 2004-03-15 01:18:23 +0000 | [diff] [blame] | 1257 | // block in the region. |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1258 | BasicBlock *header = *Blocks.begin(); |
Florian Hahn | 0e9dec6 | 2017-11-13 10:35:52 +0000 | [diff] [blame] | 1259 | 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 Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1281 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1282 | // 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 Lattner | 13d2ddf | 2004-05-12 16:07:41 +0000 | [diff] [blame] | 1295 | // 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 Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 1299 | // 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 Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1322 | // This takes place of the original loop |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 1323 | BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1324 | "codeRepl", oldFunction, |
Gabor Greif | 697e94c | 2008-05-15 10:04:30 +0000 | [diff] [blame] | 1325 | header); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1326 | |
| 1327 | // The new function needs a root node because other nodes can branch to the |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1328 | // head of the region, but the entry node of a function cannot have preds. |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 1329 | BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1330 | "newFuncRoot"); |
Florian Hahn | e5089e2 | 2017-12-08 21:49:03 +0000 | [diff] [blame] | 1331 | 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 Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1347 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 1348 | findAllocas(SinkingCands, HoistingCands, CommonExit); |
| 1349 | assert(HoistingCands.empty() || CommonExit); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 1350 | |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1351 | // Find inputs to, outputs from the code region. |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 1352 | 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 Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1358 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 1359 | 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 Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1366 | // 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 Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1373 | // Construct new function based on inputs/outputs & add allocas for all defs. |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1374 | Function *newFunction = |
| 1375 | constructFunction(inputs, outputs, header, newFuncRoot, codeReplacer, |
| 1376 | oldFunction, oldFunction->getParent()); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1377 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1378 | // Update the entry count of the function. |
| 1379 | if (BFI) { |
Easwaran Raman | e5b8de2 | 2018-01-17 22:24:23 +0000 | [diff] [blame] | 1380 | auto Count = BFI->getProfileCountFromFreq(EntryFreq.getFrequency()); |
| 1381 | if (Count.hasValue()) |
| 1382 | newFunction->setEntryCount( |
| 1383 | ProfileCount(Count.getValue(), Function::PCT_Real)); // FIXME |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1384 | BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency()); |
| 1385 | } |
| 1386 | |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1387 | CallInst *TheCall = |
| 1388 | emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1389 | |
Chris Lattner | 9c431f6 | 2004-03-14 22:34:55 +0000 | [diff] [blame] | 1390 | moveCodeToFunction(newFunction); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1391 | |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1392 | // 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 Kumar | 17d9f14 | 2019-01-19 02:37:59 +0000 | [diff] [blame] | 1395 | InputObjectsWithLifetime.getArrayRef(), |
| 1396 | TheCall); |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1397 | |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 1398 | // Propagate personality info to the new function if there is one. |
| 1399 | if (oldFunction->hasPersonalityFn()) |
| 1400 | newFunction->setPersonalityFn(oldFunction->getPersonalityFn()); |
| 1401 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1402 | // Update the branch weights for the exit block. |
| 1403 | if (BFI && NumExitBlocks > 1) |
| 1404 | calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI); |
| 1405 | |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 1406 | // 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 Spencer | 6614946 | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 1408 | for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) { |
| 1409 | PHINode *PN = cast<PHINode>(I); |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 1410 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1411 | if (!Blocks.count(PN->getIncomingBlock(i))) |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 1412 | PN->setIncomingBlock(i, newFuncRoot); |
Reid Spencer | 6614946 | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 1413 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1414 | |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 1415 | for (BasicBlock *ExitBB : ExitBlocks) |
| 1416 | for (PHINode &PN : ExitBB->phis()) { |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 1417 | Value *IncomingCodeReplacerVal = nullptr; |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 1418 | for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 1419 | // Ignore incoming values from outside of the extracted region. |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 1420 | if (!Blocks.count(PN.getIncomingBlock(i))) |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 1421 | continue; |
| 1422 | |
| 1423 | // Ensure that there is only one incoming value from codeReplacer. |
| 1424 | if (!IncomingCodeReplacerVal) { |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 1425 | PN.setIncomingBlock(i, codeReplacer); |
| 1426 | IncomingCodeReplacerVal = PN.getIncomingValue(i); |
| 1427 | } else |
| 1428 | assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) && |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 1429 | "PHI has two incompatbile incoming values from codeRepl"); |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 1430 | } |
Chris Lattner | 5627382 | 2004-08-13 03:27:07 +0000 | [diff] [blame] | 1431 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1432 | |
Vedant Kumar | 15718a6 | 2018-10-15 19:22:20 +0000 | [diff] [blame] | 1433 | // 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 Kumar | 09b7aa4 | 2018-11-06 19:05:53 +0000 | [diff] [blame] | 1438 | // Remove debug info intrinsics from the new function. |
Vedant Kumar | 15718a6 | 2018-10-15 19:22:20 +0000 | [diff] [blame] | 1439 | while (BlockIt != BB.end()) { |
| 1440 | Instruction *Inst = &*BlockIt; |
| 1441 | ++BlockIt; |
| 1442 | if (isa<DbgInfoIntrinsic>(Inst)) |
| 1443 | Inst->eraseFromParent(); |
| 1444 | } |
Vedant Kumar | 09b7aa4 | 2018-11-06 19:05:53 +0000 | [diff] [blame] | 1445 | // 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 Kumar | 15718a6 | 2018-10-15 19:22:20 +0000 | [diff] [blame] | 1452 | } |
| 1453 | |
Vedant Kumar | 09415a8 | 2018-12-05 19:35:37 +0000 | [diff] [blame] | 1454 | // 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 Kumar | d669942 | 2018-11-08 17:57:09 +0000 | [diff] [blame] | 1457 | bool doesNotReturn = none_of(*newFunction, [](const BasicBlock &BB) { |
Vedant Kumar | 09415a8 | 2018-12-05 19:35:37 +0000 | [diff] [blame] | 1458 | const Instruction *Term = BB.getTerminator(); |
| 1459 | return isa<ReturnInst>(Term) || isa<ResumeInst>(Term); |
Vedant Kumar | d669942 | 2018-11-08 17:57:09 +0000 | [diff] [blame] | 1460 | }); |
| 1461 | if (doesNotReturn) |
| 1462 | newFunction->setDoesNotReturn(); |
| 1463 | |
Vedant Kumar | b2a6f8e | 2018-12-07 03:01:54 +0000 | [diff] [blame] | 1464 | LLVM_DEBUG(if (verifyFunction(*newFunction, &errs())) { |
| 1465 | newFunction->dump(); |
| 1466 | report_fatal_error("verification of newFunction failed!"); |
| 1467 | }); |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 1468 | LLVM_DEBUG(if (verifyFunction(*oldFunction)) |
| 1469 | report_fatal_error("verification of oldFunction failed!")); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1470 | return newFunction; |
| 1471 | } |