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" |
Sergey Dmitriev | 807960e | 2019-02-08 06:55:18 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/AssumptionCache.h" |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 25 | #include "llvm/Analysis/BlockFrequencyInfoImpl.h" |
| 26 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/LoopInfo.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 28 | #include "llvm/IR/Argument.h" |
| 29 | #include "llvm/IR/Attributes.h" |
| 30 | #include "llvm/IR/BasicBlock.h" |
| 31 | #include "llvm/IR/CFG.h" |
| 32 | #include "llvm/IR/Constant.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 33 | #include "llvm/IR/Constants.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 34 | #include "llvm/IR/DataLayout.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 35 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 36 | #include "llvm/IR/Dominators.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 37 | #include "llvm/IR/Function.h" |
| 38 | #include "llvm/IR/GlobalValue.h" |
| 39 | #include "llvm/IR/InstrTypes.h" |
| 40 | #include "llvm/IR/Instruction.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 41 | #include "llvm/IR/Instructions.h" |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 42 | #include "llvm/IR/IntrinsicInst.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 43 | #include "llvm/IR/Intrinsics.h" |
| 44 | #include "llvm/IR/LLVMContext.h" |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 45 | #include "llvm/IR/MDBuilder.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 46 | #include "llvm/IR/Module.h" |
Sergey Dmitriev | 807960e | 2019-02-08 06:55:18 +0000 | [diff] [blame] | 47 | #include "llvm/IR/PatternMatch.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 48 | #include "llvm/IR/Type.h" |
| 49 | #include "llvm/IR/User.h" |
| 50 | #include "llvm/IR/Value.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 51 | #include "llvm/IR/Verifier.h" |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 52 | #include "llvm/Pass.h" |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 53 | #include "llvm/Support/BlockFrequency.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 54 | #include "llvm/Support/BranchProbability.h" |
| 55 | #include "llvm/Support/Casting.h" |
Reid Spencer | 7c16caa | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 56 | #include "llvm/Support/CommandLine.h" |
| 57 | #include "llvm/Support/Debug.h" |
Torok Edwin | ccb29cd | 2009-07-11 13:10:19 +0000 | [diff] [blame] | 58 | #include "llvm/Support/ErrorHandling.h" |
Chris Lattner | b25de3f | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 59 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 60 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Vedant Kumar | 09b7aa4 | 2018-11-06 19:05:53 +0000 | [diff] [blame] | 61 | #include "llvm/Transforms/Utils/Local.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 62 | #include <cassert> |
| 63 | #include <cstdint> |
| 64 | #include <iterator> |
| 65 | #include <map> |
Chris Lattner | 9c431f6 | 2004-03-14 22:34:55 +0000 | [diff] [blame] | 66 | #include <set> |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 67 | #include <utility> |
| 68 | #include <vector> |
| 69 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 70 | using namespace llvm; |
Sergey Dmitriev | 807960e | 2019-02-08 06:55:18 +0000 | [diff] [blame] | 71 | using namespace llvm::PatternMatch; |
Easwaran Raman | e5b8de2 | 2018-01-17 22:24:23 +0000 | [diff] [blame] | 72 | using ProfileCount = Function::ProfileCount; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 73 | |
Chandler Carruth | e96dd89 | 2014-04-21 22:55:11 +0000 | [diff] [blame] | 74 | #define DEBUG_TYPE "code-extractor" |
| 75 | |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 76 | // Provide a command-line option to aggregate function arguments into a struct |
Misha Brukman | 234b44a | 2008-12-13 05:21:37 +0000 | [diff] [blame] | 77 | // for functions produced by the code extractor. This is useful when converting |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 78 | // extracted functions to pthread-based code, as only one argument (void*) can |
| 79 | // be passed in to pthread_create(). |
| 80 | static cl::opt<bool> |
| 81 | AggregateArgsOpt("aggregate-extracted-args", cl::Hidden, |
| 82 | cl::desc("Aggregate arguments to code-extracted functions")); |
| 83 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 84 | /// Test whether a block is valid for extraction. |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 85 | static bool isBlockValidForExtraction(const BasicBlock &BB, |
| 86 | const SetVector<BasicBlock *> &Result, |
| 87 | bool AllowVarArgs, bool AllowAlloca) { |
Serge Guelton | 7bc405a | 2017-06-27 18:57:53 +0000 | [diff] [blame] | 88 | // taking the address of a basic block moved to another function is illegal |
| 89 | if (BB.hasAddressTaken()) |
| 90 | return false; |
| 91 | |
| 92 | // don't hoist code that uses another basicblock address, as it's likely to |
| 93 | // lead to unexpected behavior, like cross-function jumps |
| 94 | SmallPtrSet<User const *, 16> Visited; |
| 95 | SmallVector<User const *, 16> ToVisit; |
| 96 | |
| 97 | for (Instruction const &Inst : BB) |
| 98 | ToVisit.push_back(&Inst); |
| 99 | |
| 100 | while (!ToVisit.empty()) { |
| 101 | User const *Curr = ToVisit.pop_back_val(); |
| 102 | if (!Visited.insert(Curr).second) |
| 103 | continue; |
| 104 | if (isa<BlockAddress const>(Curr)) |
| 105 | return false; // even a reference to self is likely to be not compatible |
| 106 | |
| 107 | if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB) |
| 108 | continue; |
| 109 | |
| 110 | for (auto const &U : Curr->operands()) { |
| 111 | if (auto *UU = dyn_cast<User>(U)) |
| 112 | ToVisit.push_back(UU); |
| 113 | } |
| 114 | } |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 115 | |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 116 | // If explicitly requested, allow vastart and alloca. For invoke instructions |
| 117 | // verify that extraction is valid. |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 118 | 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] | 119 | if (isa<AllocaInst>(I)) { |
| 120 | if (!AllowAlloca) |
| 121 | return false; |
| 122 | continue; |
| 123 | } |
| 124 | |
| 125 | if (const auto *II = dyn_cast<InvokeInst>(I)) { |
| 126 | // Unwind destination (either a landingpad, catchswitch, or cleanuppad) |
| 127 | // must be a part of the subgraph which is being extracted. |
| 128 | if (auto *UBB = II->getUnwindDest()) |
| 129 | if (!Result.count(UBB)) |
| 130 | return false; |
| 131 | continue; |
| 132 | } |
| 133 | |
| 134 | // All catch handlers of a catchswitch instruction as well as the unwind |
| 135 | // destination must be in the subgraph. |
| 136 | if (const auto *CSI = dyn_cast<CatchSwitchInst>(I)) { |
| 137 | if (auto *UBB = CSI->getUnwindDest()) |
| 138 | if (!Result.count(UBB)) |
| 139 | return false; |
| 140 | for (auto *HBB : CSI->handlers()) |
| 141 | if (!Result.count(const_cast<BasicBlock*>(HBB))) |
| 142 | return false; |
| 143 | continue; |
| 144 | } |
| 145 | |
| 146 | // Make sure that entire catch handler is within subgraph. It is sufficient |
| 147 | // to check that catch return's block is in the list. |
| 148 | if (const auto *CPI = dyn_cast<CatchPadInst>(I)) { |
| 149 | for (const auto *U : CPI->users()) |
| 150 | if (const auto *CRI = dyn_cast<CatchReturnInst>(U)) |
| 151 | if (!Result.count(const_cast<BasicBlock*>(CRI->getParent()))) |
| 152 | return false; |
| 153 | continue; |
| 154 | } |
| 155 | |
| 156 | // And do similar checks for cleanup handler - the entire handler must be |
| 157 | // in subgraph which is going to be extracted. For cleanup return should |
| 158 | // additionally check that the unwind destination is also in the subgraph. |
| 159 | if (const auto *CPI = dyn_cast<CleanupPadInst>(I)) { |
| 160 | for (const auto *U : CPI->users()) |
| 161 | if (const auto *CRI = dyn_cast<CleanupReturnInst>(U)) |
| 162 | if (!Result.count(const_cast<BasicBlock*>(CRI->getParent()))) |
| 163 | return false; |
| 164 | continue; |
| 165 | } |
| 166 | if (const auto *CRI = dyn_cast<CleanupReturnInst>(I)) { |
| 167 | if (auto *UBB = CRI->getUnwindDest()) |
| 168 | if (!Result.count(UBB)) |
| 169 | return false; |
| 170 | continue; |
| 171 | } |
| 172 | |
Vedant Kumar | 1e209e2 | 2018-11-06 19:06:08 +0000 | [diff] [blame] | 173 | if (const CallInst *CI = dyn_cast<CallInst>(I)) { |
| 174 | if (const Function *F = CI->getCalledFunction()) { |
| 175 | auto IID = F->getIntrinsicID(); |
| 176 | if (IID == Intrinsic::vastart) { |
Florian Hahn | 0e9dec6 | 2017-11-13 10:35:52 +0000 | [diff] [blame] | 177 | if (AllowVarArgs) |
| 178 | continue; |
| 179 | else |
| 180 | return false; |
| 181 | } |
Vedant Kumar | 1e209e2 | 2018-11-06 19:06:08 +0000 | [diff] [blame] | 182 | |
| 183 | // Currently, we miscompile outlined copies of eh_typid_for. There are |
| 184 | // proposals for fixing this in llvm.org/PR39545. |
| 185 | if (IID == Intrinsic::eh_typeid_for) |
| 186 | return false; |
| 187 | } |
| 188 | } |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 189 | } |
| 190 | |
| 191 | return true; |
| 192 | } |
| 193 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 194 | /// 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] | 195 | static SetVector<BasicBlock *> |
Florian Hahn | 0e9dec6 | 2017-11-13 10:35:52 +0000 | [diff] [blame] | 196 | buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 197 | bool AllowVarArgs, bool AllowAlloca) { |
Davide Italiano | fa15de3 | 2017-04-21 04:25:00 +0000 | [diff] [blame] | 198 | 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] | 199 | SetVector<BasicBlock *> Result; |
Chandler Carruth | 2f5d019 | 2012-05-04 10:26:45 +0000 | [diff] [blame] | 200 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 201 | // Loop over the blocks, adding them to our set-vector, and aborting with an |
| 202 | // empty set if we encounter invalid blocks. |
Davide Italiano | fa15de3 | 2017-04-21 04:25:00 +0000 | [diff] [blame] | 203 | for (BasicBlock *BB : BBs) { |
Davide Italiano | fa15de3 | 2017-04-21 04:25:00 +0000 | [diff] [blame] | 204 | // If this block is dead, don't process it. |
| 205 | if (DT && !DT->isReachableFromEntry(BB)) |
| 206 | continue; |
| 207 | |
| 208 | if (!Result.insert(BB)) |
| 209 | llvm_unreachable("Repeated basic blocks in extraction input"); |
Davide Italiano | fa15de3 | 2017-04-21 04:25:00 +0000 | [diff] [blame] | 210 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 211 | |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 212 | for (auto *BB : Result) { |
| 213 | if (!isBlockValidForExtraction(*BB, Result, AllowVarArgs, AllowAlloca)) |
| 214 | return {}; |
| 215 | |
| 216 | // Make sure that the first block is not a landing pad. |
| 217 | if (BB == Result.front()) { |
| 218 | if (BB->isEHPad()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 219 | LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n"); |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 220 | return {}; |
| 221 | } |
| 222 | continue; |
| 223 | } |
| 224 | |
| 225 | // All blocks other than the first must not have predecessors outside of |
| 226 | // the subgraph which is being extracted. |
| 227 | for (auto *PBB : predecessors(BB)) |
| 228 | if (!Result.count(PBB)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 229 | LLVM_DEBUG( |
| 230 | dbgs() << "No blocks in this region may have entries from " |
| 231 | "outside the region except for the first block!\n"); |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 232 | return {}; |
| 233 | } |
| 234 | } |
Chandler Carruth | 2f5d019 | 2012-05-04 10:26:45 +0000 | [diff] [blame] | 235 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 236 | return Result; |
| 237 | } |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 238 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 239 | CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 240 | bool AggregateArgs, BlockFrequencyInfo *BFI, |
Sergey Dmitriev | 807960e | 2019-02-08 06:55:18 +0000 | [diff] [blame] | 241 | BranchProbabilityInfo *BPI, AssumptionCache *AC, |
| 242 | bool AllowVarArgs, bool AllowAlloca, |
| 243 | std::string Suffix) |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 244 | : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), |
Sergey Dmitriev | 807960e | 2019-02-08 06:55:18 +0000 | [diff] [blame] | 245 | BPI(BPI), AC(AC), AllowVarArgs(AllowVarArgs), |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 246 | Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)), |
| 247 | Suffix(Suffix) {} |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 248 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 249 | CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs, |
| 250 | BlockFrequencyInfo *BFI, |
Sergey Dmitriev | 807960e | 2019-02-08 06:55:18 +0000 | [diff] [blame] | 251 | BranchProbabilityInfo *BPI, AssumptionCache *AC, |
| 252 | std::string Suffix) |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 253 | : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), |
Sergey Dmitriev | 807960e | 2019-02-08 06:55:18 +0000 | [diff] [blame] | 254 | BPI(BPI), AC(AC), AllowVarArgs(false), |
Florian Hahn | 7114755 | 2017-11-13 11:08:47 +0000 | [diff] [blame] | 255 | Blocks(buildExtractionBlockSet(L.getBlocks(), &DT, |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 256 | /* AllowVarArgs */ false, |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 257 | /* AllowAlloca */ false)), |
| 258 | Suffix(Suffix) {} |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 259 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 260 | /// definedInRegion - Return true if the specified value is defined in the |
| 261 | /// extracted region. |
| 262 | static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) { |
| 263 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 264 | if (Blocks.count(I->getParent())) |
| 265 | return true; |
| 266 | return false; |
| 267 | } |
| 268 | |
| 269 | /// definedInCaller - Return true if the specified value is defined in the |
| 270 | /// function being code extracted, but not in the region being extracted. |
| 271 | /// These values must be passed in as live-ins to the function. |
| 272 | static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) { |
| 273 | if (isa<Argument>(V)) return true; |
| 274 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 275 | if (!Blocks.count(I->getParent())) |
| 276 | return true; |
| 277 | return false; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 278 | } |
| 279 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 280 | static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) { |
| 281 | BasicBlock *CommonExitBlock = nullptr; |
| 282 | auto hasNonCommonExitSucc = [&](BasicBlock *Block) { |
| 283 | for (auto *Succ : successors(Block)) { |
| 284 | // Internal edges, ok. |
| 285 | if (Blocks.count(Succ)) |
| 286 | continue; |
| 287 | if (!CommonExitBlock) { |
| 288 | CommonExitBlock = Succ; |
| 289 | continue; |
| 290 | } |
| 291 | if (CommonExitBlock == Succ) |
| 292 | continue; |
| 293 | |
| 294 | return true; |
| 295 | } |
| 296 | return false; |
| 297 | }; |
| 298 | |
| 299 | if (any_of(Blocks, hasNonCommonExitSucc)) |
| 300 | return nullptr; |
| 301 | |
| 302 | return CommonExitBlock; |
| 303 | } |
| 304 | |
| 305 | bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers( |
| 306 | Instruction *Addr) const { |
| 307 | AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets()); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 308 | Function *Func = (*Blocks.begin())->getParent(); |
| 309 | for (BasicBlock &BB : *Func) { |
| 310 | if (Blocks.count(&BB)) |
| 311 | continue; |
| 312 | for (Instruction &II : BB) { |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 313 | if (isa<DbgInfoIntrinsic>(II)) |
| 314 | continue; |
| 315 | |
| 316 | unsigned Opcode = II.getOpcode(); |
| 317 | Value *MemAddr = nullptr; |
| 318 | switch (Opcode) { |
| 319 | case Instruction::Store: |
| 320 | case Instruction::Load: { |
| 321 | if (Opcode == Instruction::Store) { |
| 322 | StoreInst *SI = cast<StoreInst>(&II); |
| 323 | MemAddr = SI->getPointerOperand(); |
| 324 | } else { |
| 325 | LoadInst *LI = cast<LoadInst>(&II); |
| 326 | MemAddr = LI->getPointerOperand(); |
| 327 | } |
| 328 | // Global variable can not be aliased with locals. |
| 329 | if (dyn_cast<Constant>(MemAddr)) |
| 330 | break; |
| 331 | Value *Base = MemAddr->stripInBoundsConstantOffsets(); |
| 332 | if (!dyn_cast<AllocaInst>(Base) || Base == AI) |
| 333 | return false; |
| 334 | break; |
| 335 | } |
| 336 | default: { |
| 337 | IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II); |
| 338 | if (IntrInst) { |
Vedant Kumar | b264d69 | 2018-12-21 21:49:40 +0000 | [diff] [blame] | 339 | if (IntrInst->isLifetimeStartOrEnd()) |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 340 | break; |
| 341 | return false; |
| 342 | } |
| 343 | // Treat all the other cases conservatively if it has side effects. |
| 344 | if (II.mayHaveSideEffects()) |
| 345 | return false; |
| 346 | } |
| 347 | } |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | return true; |
| 352 | } |
| 353 | |
| 354 | BasicBlock * |
| 355 | CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) { |
| 356 | BasicBlock *SinglePredFromOutlineRegion = nullptr; |
| 357 | assert(!Blocks.count(CommonExitBlock) && |
| 358 | "Expect a block outside the region!"); |
| 359 | for (auto *Pred : predecessors(CommonExitBlock)) { |
| 360 | if (!Blocks.count(Pred)) |
| 361 | continue; |
| 362 | if (!SinglePredFromOutlineRegion) { |
| 363 | SinglePredFromOutlineRegion = Pred; |
| 364 | } else if (SinglePredFromOutlineRegion != Pred) { |
| 365 | SinglePredFromOutlineRegion = nullptr; |
| 366 | break; |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | if (SinglePredFromOutlineRegion) |
| 371 | return SinglePredFromOutlineRegion; |
| 372 | |
| 373 | #ifndef NDEBUG |
| 374 | auto getFirstPHI = [](BasicBlock *BB) { |
| 375 | BasicBlock::iterator I = BB->begin(); |
| 376 | PHINode *FirstPhi = nullptr; |
| 377 | while (I != BB->end()) { |
| 378 | PHINode *Phi = dyn_cast<PHINode>(I); |
| 379 | if (!Phi) |
| 380 | break; |
| 381 | if (!FirstPhi) { |
| 382 | FirstPhi = Phi; |
| 383 | break; |
| 384 | } |
| 385 | } |
| 386 | return FirstPhi; |
| 387 | }; |
| 388 | // If there are any phi nodes, the single pred either exists or has already |
| 389 | // be created before code extraction. |
| 390 | assert(!getFirstPHI(CommonExitBlock) && "Phi not expected"); |
| 391 | #endif |
| 392 | |
| 393 | BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock( |
| 394 | CommonExitBlock->getFirstNonPHI()->getIterator()); |
| 395 | |
Florian Hahn | b93c063 | 2017-11-01 09:48:12 +0000 | [diff] [blame] | 396 | for (auto PI = pred_begin(CommonExitBlock), PE = pred_end(CommonExitBlock); |
| 397 | PI != PE;) { |
| 398 | BasicBlock *Pred = *PI++; |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 399 | if (Blocks.count(Pred)) |
| 400 | continue; |
| 401 | Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock); |
| 402 | } |
| 403 | // Now add the old exit block to the outline region. |
| 404 | Blocks.insert(CommonExitBlock); |
| 405 | return CommonExitBlock; |
| 406 | } |
| 407 | |
| 408 | void CodeExtractor::findAllocas(ValueSet &SinkCands, ValueSet &HoistCands, |
| 409 | BasicBlock *&ExitBlock) const { |
| 410 | Function *Func = (*Blocks.begin())->getParent(); |
| 411 | ExitBlock = getCommonExitBlock(Blocks); |
| 412 | |
| 413 | for (BasicBlock &BB : *Func) { |
| 414 | if (Blocks.count(&BB)) |
| 415 | continue; |
| 416 | for (Instruction &II : BB) { |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 417 | auto *AI = dyn_cast<AllocaInst>(&II); |
| 418 | if (!AI) |
| 419 | continue; |
| 420 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 421 | // Find the pair of life time markers for address 'Addr' that are either |
| 422 | // defined inside the outline region or can legally be shrinkwrapped into |
| 423 | // the outline region. If there are not other untracked uses of the |
| 424 | // address, return the pair of markers if found; otherwise return a pair |
| 425 | // of nullptr. |
| 426 | auto GetLifeTimeMarkers = |
| 427 | [&](Instruction *Addr, bool &SinkLifeStart, |
| 428 | bool &HoistLifeEnd) -> std::pair<Instruction *, Instruction *> { |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 429 | Instruction *LifeStart = nullptr, *LifeEnd = nullptr; |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 430 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 431 | for (User *U : Addr->users()) { |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 432 | IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U); |
| 433 | if (IntrInst) { |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 434 | if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) { |
| 435 | // Do not handle the case where AI has multiple start markers. |
| 436 | if (LifeStart) |
| 437 | return std::make_pair<Instruction *>(nullptr, nullptr); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 438 | LifeStart = IntrInst; |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 439 | } |
| 440 | if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) { |
| 441 | if (LifeEnd) |
| 442 | return std::make_pair<Instruction *>(nullptr, nullptr); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 443 | LifeEnd = IntrInst; |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 444 | } |
| 445 | continue; |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 446 | } |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 447 | // Find untracked uses of the address, bail. |
| 448 | if (!definedInRegion(Blocks, U)) |
| 449 | return std::make_pair<Instruction *>(nullptr, nullptr); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 450 | } |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 451 | |
| 452 | if (!LifeStart || !LifeEnd) |
| 453 | return std::make_pair<Instruction *>(nullptr, nullptr); |
| 454 | |
| 455 | SinkLifeStart = !definedInRegion(Blocks, LifeStart); |
| 456 | HoistLifeEnd = !definedInRegion(Blocks, LifeEnd); |
| 457 | // Do legality Check. |
| 458 | if ((SinkLifeStart || HoistLifeEnd) && |
| 459 | !isLegalToShrinkwrapLifetimeMarkers(Addr)) |
| 460 | return std::make_pair<Instruction *>(nullptr, nullptr); |
| 461 | |
| 462 | // Check to see if we have a place to do hoisting, if not, bail. |
| 463 | if (HoistLifeEnd && !ExitBlock) |
| 464 | return std::make_pair<Instruction *>(nullptr, nullptr); |
| 465 | |
| 466 | return std::make_pair(LifeStart, LifeEnd); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 467 | }; |
| 468 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 469 | bool SinkLifeStart = false, HoistLifeEnd = false; |
| 470 | auto Markers = GetLifeTimeMarkers(AI, SinkLifeStart, HoistLifeEnd); |
| 471 | |
| 472 | if (Markers.first) { |
| 473 | if (SinkLifeStart) |
| 474 | SinkCands.insert(Markers.first); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 475 | SinkCands.insert(AI); |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 476 | if (HoistLifeEnd) |
| 477 | HoistCands.insert(Markers.second); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 478 | continue; |
| 479 | } |
| 480 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 481 | // Follow the bitcast. |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 482 | Instruction *MarkerAddr = nullptr; |
| 483 | for (User *U : AI->users()) { |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 484 | if (U->stripInBoundsConstantOffsets() == AI) { |
| 485 | SinkLifeStart = false; |
| 486 | HoistLifeEnd = false; |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 487 | Instruction *Bitcast = cast<Instruction>(U); |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 488 | Markers = GetLifeTimeMarkers(Bitcast, SinkLifeStart, HoistLifeEnd); |
| 489 | if (Markers.first) { |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 490 | MarkerAddr = Bitcast; |
| 491 | continue; |
| 492 | } |
| 493 | } |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 494 | |
| 495 | // Found unknown use of AI. |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 496 | if (!definedInRegion(Blocks, U)) { |
| 497 | MarkerAddr = nullptr; |
| 498 | break; |
| 499 | } |
| 500 | } |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 501 | |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 502 | if (MarkerAddr) { |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 503 | if (SinkLifeStart) |
| 504 | SinkCands.insert(Markers.first); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 505 | if (!definedInRegion(Blocks, MarkerAddr)) |
| 506 | SinkCands.insert(MarkerAddr); |
| 507 | SinkCands.insert(AI); |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 508 | if (HoistLifeEnd) |
| 509 | HoistCands.insert(Markers.second); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 510 | } |
| 511 | } |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs, |
| 516 | const ValueSet &SinkCands) const { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 517 | for (BasicBlock *BB : Blocks) { |
Chandler Carruth | 14316fc | 2012-05-04 11:20:27 +0000 | [diff] [blame] | 518 | // If a used value is defined outside the region, it's an input. If an |
| 519 | // instruction is used outside the region, it's an output. |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 520 | for (Instruction &II : *BB) { |
| 521 | 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] | 522 | ++OI) { |
| 523 | Value *V = *OI; |
| 524 | if (!SinkCands.count(V) && definedInCaller(Blocks, V)) |
| 525 | Inputs.insert(V); |
| 526 | } |
Chandler Carruth | 14316fc | 2012-05-04 11:20:27 +0000 | [diff] [blame] | 527 | |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 528 | for (User *U : II.users()) |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 529 | if (!definedInRegion(Blocks, U)) { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 530 | Outputs.insert(&II); |
Chandler Carruth | 14316fc | 2012-05-04 11:20:27 +0000 | [diff] [blame] | 531 | break; |
| 532 | } |
| 533 | } |
| 534 | } |
| 535 | } |
| 536 | |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 537 | /// severSplitPHINodesOfEntry - If a PHI node has multiple inputs from outside |
| 538 | /// of the region, we need to split the entry block of the region so that the |
| 539 | /// PHI node is easier to deal with. |
| 540 | void CodeExtractor::severSplitPHINodesOfEntry(BasicBlock *&Header) { |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 541 | unsigned NumPredsFromRegion = 0; |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 542 | unsigned NumPredsOutsideRegion = 0; |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 543 | |
Dan Gohman | dcb291f | 2007-03-22 16:38:57 +0000 | [diff] [blame] | 544 | if (Header != &Header->getParent()->getEntryBlock()) { |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 545 | PHINode *PN = dyn_cast<PHINode>(Header->begin()); |
| 546 | if (!PN) return; // No PHI nodes. |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 547 | |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 548 | // If the header node contains any PHI nodes, check to see if there is more |
| 549 | // than one entry from outside the region. If so, we need to sever the |
| 550 | // header block into two. |
| 551 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 552 | if (Blocks.count(PN->getIncomingBlock(i))) |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 553 | ++NumPredsFromRegion; |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 554 | else |
| 555 | ++NumPredsOutsideRegion; |
| 556 | |
| 557 | // If there is one (or fewer) predecessor from outside the region, we don't |
| 558 | // need to do anything special. |
| 559 | if (NumPredsOutsideRegion <= 1) return; |
| 560 | } |
| 561 | |
| 562 | // Otherwise, we need to split the header block into two pieces: one |
| 563 | // containing PHI nodes merging values from outside of the region, and a |
| 564 | // second that contains all of the code for the block and merges back any |
| 565 | // incoming values from inside of the region. |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 566 | BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 567 | |
| 568 | // We only want to code extract the second block now, and it becomes the new |
| 569 | // header of the region. |
| 570 | BasicBlock *OldPred = Header; |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 571 | Blocks.remove(OldPred); |
| 572 | Blocks.insert(NewBB); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 573 | Header = NewBB; |
| 574 | |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 575 | // Okay, now we need to adjust the PHI nodes and any branches from within the |
| 576 | // region to go to the new header block instead of the old header block. |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 577 | if (NumPredsFromRegion) { |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 578 | PHINode *PN = cast<PHINode>(OldPred->begin()); |
| 579 | // Loop over all of the predecessors of OldPred that are in the region, |
| 580 | // changing them to branch to NewBB instead. |
| 581 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 582 | if (Blocks.count(PN->getIncomingBlock(i))) { |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 583 | Instruction *TI = PN->getIncomingBlock(i)->getTerminator(); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 584 | TI->replaceUsesOfWith(OldPred, NewBB); |
| 585 | } |
| 586 | |
Chris Lattner | 0ab5e2c | 2011-04-15 05:18:47 +0000 | [diff] [blame] | 587 | // 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] | 588 | // 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] | 589 | BasicBlock::iterator AfterPHIs; |
Reid Spencer | 6614946 | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 590 | for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) { |
| 591 | PHINode *PN = cast<PHINode>(AfterPHIs); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 592 | // Create a new PHI node in the new region, which has an incoming value |
| 593 | // from OldPred of PN. |
Jay Foad | 5213134 | 2011-03-30 11:28:46 +0000 | [diff] [blame] | 594 | PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion, |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 595 | PN->getName() + ".ce", &NewBB->front()); |
Xinliang David Li | f12a0fa | 2017-04-25 04:51:19 +0000 | [diff] [blame] | 596 | PN->replaceAllUsesWith(NewPN); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 597 | NewPN->addIncoming(PN, OldPred); |
| 598 | |
| 599 | // Loop over all of the incoming value in PN, moving them to NewPN if they |
| 600 | // are from the extracted region. |
| 601 | for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) { |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 602 | if (Blocks.count(PN->getIncomingBlock(i))) { |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 603 | NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i)); |
| 604 | PN->removeIncomingValue(i); |
| 605 | --i; |
| 606 | } |
| 607 | } |
| 608 | } |
| 609 | } |
Chris Lattner | 13d2ddf | 2004-05-12 16:07:41 +0000 | [diff] [blame] | 610 | } |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 611 | |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 612 | /// severSplitPHINodesOfExits - if PHI nodes in exit blocks have inputs from |
| 613 | /// outlined region, we split these PHIs on two: one with inputs from region |
| 614 | /// and other with remaining incoming blocks; then first PHIs are placed in |
| 615 | /// outlined region. |
| 616 | void CodeExtractor::severSplitPHINodesOfExits( |
| 617 | const SmallPtrSetImpl<BasicBlock *> &Exits) { |
| 618 | for (BasicBlock *ExitBB : Exits) { |
| 619 | BasicBlock *NewBB = nullptr; |
| 620 | |
| 621 | for (PHINode &PN : ExitBB->phis()) { |
| 622 | // Find all incoming values from the outlining region. |
| 623 | SmallVector<unsigned, 2> IncomingVals; |
| 624 | for (unsigned i = 0; i < PN.getNumIncomingValues(); ++i) |
| 625 | if (Blocks.count(PN.getIncomingBlock(i))) |
| 626 | IncomingVals.push_back(i); |
| 627 | |
| 628 | // Do not process PHI if there is one (or fewer) predecessor from region. |
| 629 | // If PHI has exactly one predecessor from region, only this one incoming |
| 630 | // will be replaced on codeRepl block, so it should be safe to skip PHI. |
| 631 | if (IncomingVals.size() <= 1) |
| 632 | continue; |
| 633 | |
| 634 | // Create block for new PHIs and add it to the list of outlined if it |
| 635 | // wasn't done before. |
| 636 | if (!NewBB) { |
| 637 | NewBB = BasicBlock::Create(ExitBB->getContext(), |
| 638 | ExitBB->getName() + ".split", |
| 639 | ExitBB->getParent(), ExitBB); |
| 640 | SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBB), |
| 641 | pred_end(ExitBB)); |
| 642 | for (BasicBlock *PredBB : Preds) |
| 643 | if (Blocks.count(PredBB)) |
| 644 | PredBB->getTerminator()->replaceUsesOfWith(ExitBB, NewBB); |
| 645 | BranchInst::Create(ExitBB, NewBB); |
| 646 | Blocks.insert(NewBB); |
| 647 | } |
| 648 | |
| 649 | // Split this PHI. |
| 650 | PHINode *NewPN = |
| 651 | PHINode::Create(PN.getType(), IncomingVals.size(), |
| 652 | PN.getName() + ".ce", NewBB->getFirstNonPHI()); |
| 653 | for (unsigned i : IncomingVals) |
| 654 | NewPN->addIncoming(PN.getIncomingValue(i), PN.getIncomingBlock(i)); |
| 655 | for (unsigned i : reverse(IncomingVals)) |
| 656 | PN.removeIncomingValue(i, false); |
| 657 | PN.addIncoming(NewPN, NewBB); |
| 658 | } |
| 659 | } |
| 660 | } |
| 661 | |
Chris Lattner | 13d2ddf | 2004-05-12 16:07:41 +0000 | [diff] [blame] | 662 | void CodeExtractor::splitReturnBlocks() { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 663 | for (BasicBlock *Block : Blocks) |
| 664 | if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) { |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 665 | BasicBlock *New = |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 666 | Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret"); |
Owen Anderson | b4aa5b1 | 2009-08-24 23:32:14 +0000 | [diff] [blame] | 667 | if (DT) { |
Gabor Greif | 2f5f696 | 2010-09-10 22:25:58 +0000 | [diff] [blame] | 668 | // Old dominates New. New node dominates all other nodes dominated |
| 669 | // by Old. |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 670 | DomTreeNode *OldNode = DT->getNode(Block); |
| 671 | SmallVector<DomTreeNode *, 8> Children(OldNode->begin(), |
| 672 | OldNode->end()); |
Owen Anderson | b4aa5b1 | 2009-08-24 23:32:14 +0000 | [diff] [blame] | 673 | |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 674 | DomTreeNode *NewNode = DT->addNewBlock(New, Block); |
Owen Anderson | b4aa5b1 | 2009-08-24 23:32:14 +0000 | [diff] [blame] | 675 | |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 676 | for (DomTreeNode *I : Children) |
| 677 | DT->changeImmediateDominator(I, NewNode); |
Owen Anderson | b4aa5b1 | 2009-08-24 23:32:14 +0000 | [diff] [blame] | 678 | } |
| 679 | } |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 680 | } |
| 681 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 682 | /// constructFunction - make a function based on inputs and outputs, as follows: |
| 683 | /// f(in0, ..., inN, out0, ..., outN) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 684 | Function *CodeExtractor::constructFunction(const ValueSet &inputs, |
| 685 | const ValueSet &outputs, |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 686 | BasicBlock *header, |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 687 | BasicBlock *newRootNode, |
| 688 | BasicBlock *newHeader, |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 689 | Function *oldFunction, |
| 690 | Module *M) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 691 | LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n"); |
| 692 | LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n"); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 693 | |
| 694 | // This function returns unsigned, outputs will go back by reference. |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 695 | switch (NumExitBlocks) { |
| 696 | case 0: |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 697 | case 1: RetTy = Type::getVoidTy(header->getContext()); break; |
| 698 | case 2: RetTy = Type::getInt1Ty(header->getContext()); break; |
| 699 | default: RetTy = Type::getInt16Ty(header->getContext()); break; |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 700 | } |
| 701 | |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 702 | std::vector<Type *> paramTy; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 703 | |
| 704 | // 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] | 705 | for (Value *value : inputs) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 706 | LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n"); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 707 | paramTy.push_back(value->getType()); |
| 708 | } |
| 709 | |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 710 | // 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] | 711 | for (Value *output : outputs) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 712 | LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n"); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 713 | if (AggregateArgs) |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 714 | paramTy.push_back(output->getType()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 715 | else |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 716 | paramTy.push_back(PointerType::getUnqual(output->getType())); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 717 | } |
| 718 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 719 | LLVM_DEBUG({ |
Benjamin Kramer | 706e4883 | 2016-06-26 13:39:33 +0000 | [diff] [blame] | 720 | dbgs() << "Function type: " << *RetTy << " f("; |
| 721 | for (Type *i : paramTy) |
| 722 | dbgs() << *i << ", "; |
| 723 | dbgs() << ")\n"; |
| 724 | }); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 725 | |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 726 | StructType *StructTy; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 727 | if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 728 | StructTy = StructType::get(M->getContext(), paramTy); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 729 | paramTy.clear(); |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 730 | paramTy.push_back(PointerType::getUnqual(StructTy)); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 731 | } |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 732 | FunctionType *funcType = |
Florian Hahn | 0e9dec6 | 2017-11-13 10:35:52 +0000 | [diff] [blame] | 733 | FunctionType::get(RetTy, paramTy, |
| 734 | AllowVarArgs && oldFunction->isVarArg()); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 735 | |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 736 | std::string SuffixToUse = |
| 737 | Suffix.empty() |
| 738 | ? (header->getName().empty() ? "extracted" : header->getName().str()) |
| 739 | : Suffix; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 740 | // Create the new function |
Alexander Richardson | 6bcf2ba | 2018-08-23 09:25:17 +0000 | [diff] [blame] | 741 | Function *newFunction = Function::Create( |
| 742 | funcType, GlobalValue::InternalLinkage, oldFunction->getAddressSpace(), |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 743 | oldFunction->getName() + "." + SuffixToUse, M); |
Chris Lattner | 4caf5eb | 2008-12-18 05:52:56 +0000 | [diff] [blame] | 744 | // If the old function is no-throw, so is the new one. |
| 745 | if (oldFunction->doesNotThrow()) |
Bill Wendling | f319e99 | 2012-10-10 03:12:49 +0000 | [diff] [blame] | 746 | newFunction->setDoesNotThrow(); |
Sean Silva | a0a802a | 2016-08-01 03:15:32 +0000 | [diff] [blame] | 747 | |
| 748 | // Inherit the uwtable attribute if we need to. |
| 749 | if (oldFunction->hasUWTable()) |
| 750 | newFunction->setHasUWTable(); |
| 751 | |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 752 | // Inherit all of the target dependent attributes and white-listed |
| 753 | // target independent attributes. |
Sean Silva | a0a802a | 2016-08-01 03:15:32 +0000 | [diff] [blame] | 754 | // (e.g. If the extracted region contains a call to an x86.sse |
| 755 | // instruction we need to make sure that the extracted region has the |
| 756 | // "target-features" attribute allowing it to be lowered. |
| 757 | // FIXME: This should be changed to check to see if a specific |
| 758 | // attribute can not be inherited. |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 759 | for (const auto &Attr : oldFunction->getAttributes().getFnAttributes()) { |
| 760 | if (Attr.isStringAttribute()) { |
| 761 | if (Attr.getKindAsString() == "thunk") |
| 762 | continue; |
| 763 | } else |
| 764 | switch (Attr.getKindAsEnum()) { |
| 765 | // Those attributes cannot be propagated safely. Explicitly list them |
| 766 | // here so we get a warning if new attributes are added. This list also |
| 767 | // includes non-function attributes. |
| 768 | case Attribute::Alignment: |
| 769 | case Attribute::AllocSize: |
| 770 | case Attribute::ArgMemOnly: |
| 771 | case Attribute::Builtin: |
| 772 | case Attribute::ByVal: |
| 773 | case Attribute::Convergent: |
| 774 | case Attribute::Dereferenceable: |
| 775 | case Attribute::DereferenceableOrNull: |
| 776 | case Attribute::InAlloca: |
| 777 | case Attribute::InReg: |
| 778 | case Attribute::InaccessibleMemOnly: |
| 779 | case Attribute::InaccessibleMemOrArgMemOnly: |
| 780 | case Attribute::JumpTable: |
| 781 | case Attribute::Naked: |
| 782 | case Attribute::Nest: |
| 783 | case Attribute::NoAlias: |
| 784 | case Attribute::NoBuiltin: |
| 785 | case Attribute::NoCapture: |
| 786 | case Attribute::NoReturn: |
| 787 | case Attribute::None: |
| 788 | case Attribute::NonNull: |
| 789 | case Attribute::ReadNone: |
| 790 | case Attribute::ReadOnly: |
| 791 | case Attribute::Returned: |
| 792 | case Attribute::ReturnsTwice: |
| 793 | case Attribute::SExt: |
| 794 | case Attribute::Speculatable: |
| 795 | case Attribute::StackAlignment: |
| 796 | case Attribute::StructRet: |
| 797 | case Attribute::SwiftError: |
| 798 | case Attribute::SwiftSelf: |
| 799 | case Attribute::WriteOnly: |
| 800 | case Attribute::ZExt: |
Matt Arsenault | caf1316 | 2019-03-12 21:02:54 +0000 | [diff] [blame] | 801 | case Attribute::ImmArg: |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 802 | case Attribute::EndAttrKinds: |
| 803 | continue; |
| 804 | // Those attributes should be safe to propagate to the extracted function. |
| 805 | case Attribute::AlwaysInline: |
| 806 | case Attribute::Cold: |
| 807 | case Attribute::NoRecurse: |
| 808 | case Attribute::InlineHint: |
| 809 | case Attribute::MinSize: |
| 810 | case Attribute::NoDuplicate: |
| 811 | case Attribute::NoImplicitFloat: |
| 812 | case Attribute::NoInline: |
| 813 | case Attribute::NonLazyBind: |
| 814 | case Attribute::NoRedZone: |
| 815 | case Attribute::NoUnwind: |
Matt Morehouse | 236cdaf | 2018-03-22 17:07:51 +0000 | [diff] [blame] | 816 | case Attribute::OptForFuzzing: |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 817 | case Attribute::OptimizeNone: |
| 818 | case Attribute::OptimizeForSize: |
| 819 | case Attribute::SafeStack: |
Vlad Tsyrklevich | d17f61e | 2018-04-03 20:10:40 +0000 | [diff] [blame] | 820 | case Attribute::ShadowCallStack: |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 821 | case Attribute::SanitizeAddress: |
| 822 | case Attribute::SanitizeMemory: |
| 823 | case Attribute::SanitizeThread: |
| 824 | case Attribute::SanitizeHWAddress: |
Chandler Carruth | 664aa86 | 2018-09-04 12:38:00 +0000 | [diff] [blame] | 825 | case Attribute::SpeculativeLoadHardening: |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 826 | case Attribute::StackProtect: |
| 827 | case Attribute::StackProtectReq: |
| 828 | case Attribute::StackProtectStrong: |
| 829 | case Attribute::StrictFP: |
| 830 | case Attribute::UWTable: |
Oren Ben Simhon | fdd72fd | 2018-03-17 13:29:46 +0000 | [diff] [blame] | 831 | case Attribute::NoCfCheck: |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 832 | break; |
| 833 | } |
Sean Silva | a0a802a | 2016-08-01 03:15:32 +0000 | [diff] [blame] | 834 | |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 835 | newFunction->addFnAttr(Attr); |
| 836 | } |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 837 | newFunction->getBasicBlockList().push_back(newRootNode); |
| 838 | |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 839 | // Create an iterator to name all of the arguments we inserted. |
Chris Lattner | 531f9e9 | 2005-03-15 04:54:21 +0000 | [diff] [blame] | 840 | Function::arg_iterator AI = newFunction->arg_begin(); |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 841 | |
| 842 | // 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] | 843 | // arguments (or appropriate addressing into struct) instead. |
| 844 | for (unsigned i = 0, e = inputs.size(); i != e; ++i) { |
| 845 | Value *RewriteVal; |
| 846 | if (AggregateArgs) { |
David Greene | c656cbb | 2007-09-04 15:46:09 +0000 | [diff] [blame] | 847 | Value *Idx[2]; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 848 | Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext())); |
| 849 | Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i); |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 850 | Instruction *TI = newFunction->begin()->getTerminator(); |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 851 | GetElementPtrInst *GEP = GetElementPtrInst::Create( |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 852 | StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI); |
James Y Knight | 14359ef | 2019-02-01 20:44:24 +0000 | [diff] [blame] | 853 | RewriteVal = new LoadInst(StructTy->getElementType(i), GEP, |
| 854 | "loadgep_" + inputs[i]->getName(), TI); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 855 | } else |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 856 | RewriteVal = &*AI++; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 857 | |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 858 | std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end()); |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 859 | for (User *use : Users) |
| 860 | if (Instruction *inst = dyn_cast<Instruction>(use)) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 861 | if (Blocks.count(inst->getParent())) |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 862 | inst->replaceUsesOfWith(inputs[i], RewriteVal); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 863 | } |
| 864 | |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 865 | // Set names for input and output arguments. |
| 866 | if (!AggregateArgs) { |
Chris Lattner | 531f9e9 | 2005-03-15 04:54:21 +0000 | [diff] [blame] | 867 | AI = newFunction->arg_begin(); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 868 | for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI) |
Owen Anderson | 7629b71 | 2008-04-14 17:38:21 +0000 | [diff] [blame] | 869 | AI->setName(inputs[i]->getName()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 870 | for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI) |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 871 | AI->setName(outputs[i]->getName()+".out"); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 872 | } |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 873 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 874 | // Rewrite branches to basic blocks outside of the loop to new dummy blocks |
| 875 | // within the new function. This must be done before we lose track of which |
| 876 | // blocks were originally in the code region. |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 877 | std::vector<User *> Users(header->user_begin(), header->user_end()); |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 878 | for (unsigned i = 0, e = Users.size(); i != e; ++i) |
| 879 | // The BasicBlock which contains the branch is not in the region |
| 880 | // modify the branch target to a new block |
Chandler Carruth | 8b7a812 | 2018-10-18 00:38:54 +0000 | [diff] [blame] | 881 | if (Instruction *I = dyn_cast<Instruction>(Users[i])) |
| 882 | if (I->isTerminator() && !Blocks.count(I->getParent()) && |
| 883 | I->getParent()->getParent() == oldFunction) |
| 884 | I->replaceUsesOfWith(header, newHeader); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 885 | |
| 886 | return newFunction; |
| 887 | } |
| 888 | |
Vedant Kumar | 4b0cc9a | 2019-02-13 19:53:38 +0000 | [diff] [blame] | 889 | /// Erase lifetime.start markers which reference inputs to the extraction |
Vedant Kumar | 5f5cac3 | 2019-02-15 18:46:58 +0000 | [diff] [blame] | 890 | /// region, and insert the referenced memory into \p LifetimesStart. |
Vedant Kumar | 17d9f14 | 2019-01-19 02:37:59 +0000 | [diff] [blame] | 891 | /// |
| 892 | /// The extraction region is defined by a set of blocks (\p Blocks), and a set |
| 893 | /// of allocas which will be moved from the caller function into the extracted |
| 894 | /// function (\p SunkAllocas). |
Vedant Kumar | 4b0cc9a | 2019-02-13 19:53:38 +0000 | [diff] [blame] | 895 | static void eraseLifetimeMarkersOnInputs(const SetVector<BasicBlock *> &Blocks, |
| 896 | const SetVector<Value *> &SunkAllocas, |
Vedant Kumar | 5f5cac3 | 2019-02-15 18:46:58 +0000 | [diff] [blame] | 897 | SetVector<Value *> &LifetimesStart) { |
Vedant Kumar | 17d9f14 | 2019-01-19 02:37:59 +0000 | [diff] [blame] | 898 | for (BasicBlock *BB : Blocks) { |
| 899 | for (auto It = BB->begin(), End = BB->end(); It != End;) { |
| 900 | auto *II = dyn_cast<IntrinsicInst>(&*It); |
| 901 | ++It; |
| 902 | if (!II || !II->isLifetimeStartOrEnd()) |
| 903 | continue; |
| 904 | |
| 905 | // Get the memory operand of the lifetime marker. If the underlying |
| 906 | // object is a sunk alloca, or is otherwise defined in the extraction |
| 907 | // region, the lifetime marker must not be erased. |
| 908 | Value *Mem = II->getOperand(1)->stripInBoundsOffsets(); |
| 909 | if (SunkAllocas.count(Mem) || definedInRegion(Blocks, Mem)) |
| 910 | continue; |
| 911 | |
Vedant Kumar | 4b0cc9a | 2019-02-13 19:53:38 +0000 | [diff] [blame] | 912 | if (II->getIntrinsicID() == Intrinsic::lifetime_start) |
| 913 | LifetimesStart.insert(Mem); |
Vedant Kumar | 17d9f14 | 2019-01-19 02:37:59 +0000 | [diff] [blame] | 914 | II->eraseFromParent(); |
| 915 | } |
| 916 | } |
Vedant Kumar | 17d9f14 | 2019-01-19 02:37:59 +0000 | [diff] [blame] | 917 | } |
| 918 | |
| 919 | /// Insert lifetime start/end markers surrounding the call to the new function |
| 920 | /// for objects defined in the caller. |
Vedant Kumar | 4b0cc9a | 2019-02-13 19:53:38 +0000 | [diff] [blame] | 921 | static void insertLifetimeMarkersSurroundingCall( |
| 922 | Module *M, ArrayRef<Value *> LifetimesStart, ArrayRef<Value *> LifetimesEnd, |
| 923 | CallInst *TheCall) { |
Vedant Kumar | 17d9f14 | 2019-01-19 02:37:59 +0000 | [diff] [blame] | 924 | LLVMContext &Ctx = M->getContext(); |
| 925 | auto Int8PtrTy = Type::getInt8PtrTy(Ctx); |
| 926 | auto NegativeOne = ConstantInt::getSigned(Type::getInt64Ty(Ctx), -1); |
Vedant Kumar | 17d9f14 | 2019-01-19 02:37:59 +0000 | [diff] [blame] | 927 | Instruction *Term = TheCall->getParent()->getTerminator(); |
Vedant Kumar | 17d9f14 | 2019-01-19 02:37:59 +0000 | [diff] [blame] | 928 | |
Vedant Kumar | 4b0cc9a | 2019-02-13 19:53:38 +0000 | [diff] [blame] | 929 | // The memory argument to a lifetime marker must be a i8*. Cache any bitcasts |
| 930 | // needed to satisfy this requirement so they may be reused. |
| 931 | DenseMap<Value *, Value *> Bitcasts; |
| 932 | |
| 933 | // Emit lifetime markers for the pointers given in \p Objects. Insert the |
| 934 | // markers before the call if \p InsertBefore, and after the call otherwise. |
| 935 | auto insertMarkers = [&](Function *MarkerFunc, ArrayRef<Value *> Objects, |
| 936 | bool InsertBefore) { |
| 937 | for (Value *Mem : Objects) { |
| 938 | assert((!isa<Instruction>(Mem) || cast<Instruction>(Mem)->getFunction() == |
| 939 | TheCall->getFunction()) && |
| 940 | "Input memory not defined in original function"); |
| 941 | Value *&MemAsI8Ptr = Bitcasts[Mem]; |
| 942 | if (!MemAsI8Ptr) { |
| 943 | if (Mem->getType() == Int8PtrTy) |
| 944 | MemAsI8Ptr = Mem; |
| 945 | else |
| 946 | MemAsI8Ptr = |
| 947 | CastInst::CreatePointerCast(Mem, Int8PtrTy, "lt.cast", TheCall); |
| 948 | } |
| 949 | |
| 950 | auto Marker = CallInst::Create(MarkerFunc, {NegativeOne, MemAsI8Ptr}); |
| 951 | if (InsertBefore) |
| 952 | Marker->insertBefore(TheCall); |
| 953 | else |
| 954 | Marker->insertBefore(Term); |
| 955 | } |
| 956 | }; |
| 957 | |
| 958 | if (!LifetimesStart.empty()) { |
| 959 | auto StartFn = llvm::Intrinsic::getDeclaration( |
| 960 | M, llvm::Intrinsic::lifetime_start, Int8PtrTy); |
| 961 | insertMarkers(StartFn, LifetimesStart, /*InsertBefore=*/true); |
| 962 | } |
| 963 | |
| 964 | if (!LifetimesEnd.empty()) { |
| 965 | auto EndFn = llvm::Intrinsic::getDeclaration( |
| 966 | M, llvm::Intrinsic::lifetime_end, Int8PtrTy); |
| 967 | insertMarkers(EndFn, LifetimesEnd, /*InsertBefore=*/false); |
Vedant Kumar | 17d9f14 | 2019-01-19 02:37:59 +0000 | [diff] [blame] | 968 | } |
| 969 | } |
| 970 | |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 971 | /// emitCallAndSwitchStatement - This method sets up the caller side by adding |
| 972 | /// the call instruction, splitting any PHI nodes in the header block as |
| 973 | /// necessary. |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 974 | CallInst *CodeExtractor::emitCallAndSwitchStatement(Function *newFunction, |
| 975 | BasicBlock *codeReplacer, |
| 976 | ValueSet &inputs, |
| 977 | ValueSet &outputs) { |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 978 | // Emit a call to the new function, passing in: *pointer to struct (if |
| 979 | // aggregating parameters), or plan inputs and allocated memory for outputs |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 980 | std::vector<Value *> params, StructValues, ReloadOutputs, Reloads; |
Matt Arsenault | 3c1fc76 | 2017-04-10 22:27:50 +0000 | [diff] [blame] | 981 | |
| 982 | Module *M = newFunction->getParent(); |
| 983 | LLVMContext &Context = M->getContext(); |
| 984 | const DataLayout &DL = M->getDataLayout(); |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 985 | CallInst *call = nullptr; |
Chris Lattner | d8017a3 | 2004-03-18 04:12:05 +0000 | [diff] [blame] | 986 | |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 987 | // Add inputs as params, or to be filled into the struct |
Vedant Kumar | 1c3694a | 2019-01-28 19:13:37 +0000 | [diff] [blame] | 988 | unsigned ArgNo = 0; |
| 989 | SmallVector<unsigned, 1> SwiftErrorArgs; |
| 990 | for (Value *input : inputs) { |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 991 | if (AggregateArgs) |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 992 | StructValues.push_back(input); |
Vedant Kumar | 1c3694a | 2019-01-28 19:13:37 +0000 | [diff] [blame] | 993 | else { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 994 | params.push_back(input); |
Vedant Kumar | 1c3694a | 2019-01-28 19:13:37 +0000 | [diff] [blame] | 995 | if (input->isSwiftError()) |
| 996 | SwiftErrorArgs.push_back(ArgNo); |
| 997 | } |
| 998 | ++ArgNo; |
| 999 | } |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1000 | |
| 1001 | // Create allocas for the outputs |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1002 | for (Value *output : outputs) { |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1003 | if (AggregateArgs) { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1004 | StructValues.push_back(output); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1005 | } else { |
| 1006 | AllocaInst *alloca = |
Matt Arsenault | 3c1fc76 | 2017-04-10 22:27:50 +0000 | [diff] [blame] | 1007 | new AllocaInst(output->getType(), DL.getAllocaAddrSpace(), |
| 1008 | nullptr, output->getName() + ".loc", |
| 1009 | &codeReplacer->getParent()->front().front()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1010 | ReloadOutputs.push_back(alloca); |
| 1011 | params.push_back(alloca); |
| 1012 | } |
| 1013 | } |
| 1014 | |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 1015 | StructType *StructArgTy = nullptr; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1016 | AllocaInst *Struct = nullptr; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1017 | if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 1018 | std::vector<Type *> ArgTypes; |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1019 | for (ValueSet::iterator v = StructValues.begin(), |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1020 | ve = StructValues.end(); v != ve; ++v) |
| 1021 | ArgTypes.push_back((*v)->getType()); |
| 1022 | |
| 1023 | // Allocate a struct at the beginning of this function |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 1024 | StructArgTy = StructType::get(newFunction->getContext(), ArgTypes); |
Matt Arsenault | 3c1fc76 | 2017-04-10 22:27:50 +0000 | [diff] [blame] | 1025 | Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr, |
| 1026 | "structArg", |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1027 | &codeReplacer->getParent()->front().front()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1028 | params.push_back(Struct); |
| 1029 | |
| 1030 | for (unsigned i = 0, e = inputs.size(); i != e; ++i) { |
David Greene | c656cbb | 2007-09-04 15:46:09 +0000 | [diff] [blame] | 1031 | Value *Idx[2]; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1032 | Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); |
| 1033 | Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i); |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 1034 | GetElementPtrInst *GEP = GetElementPtrInst::Create( |
| 1035 | StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1036 | codeReplacer->getInstList().push_back(GEP); |
| 1037 | StoreInst *SI = new StoreInst(StructValues[i], GEP); |
| 1038 | codeReplacer->getInstList().push_back(SI); |
| 1039 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1040 | } |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1041 | |
| 1042 | // Emit the call to the function |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1043 | call = CallInst::Create(newFunction, params, |
| 1044 | NumExitBlocks > 1 ? "targetBlock" : ""); |
Florian Hahn | e5089e2 | 2017-12-08 21:49:03 +0000 | [diff] [blame] | 1045 | // Add debug location to the new call, if the original function has debug |
| 1046 | // info. In that case, the terminator of the entry block of the extracted |
| 1047 | // function contains the first debug location of the extracted function, |
| 1048 | // set in extractCodeRegion. |
| 1049 | if (codeReplacer->getParent()->getSubprogram()) { |
| 1050 | if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc()) |
| 1051 | call->setDebugLoc(DL); |
| 1052 | } |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1053 | codeReplacer->getInstList().push_back(call); |
| 1054 | |
Vedant Kumar | 1c3694a | 2019-01-28 19:13:37 +0000 | [diff] [blame] | 1055 | // Set swifterror parameter attributes. |
| 1056 | for (unsigned SwiftErrArgNo : SwiftErrorArgs) { |
| 1057 | call->addParamAttr(SwiftErrArgNo, Attribute::SwiftError); |
| 1058 | newFunction->addParamAttr(SwiftErrArgNo, Attribute::SwiftError); |
| 1059 | } |
| 1060 | |
Chris Lattner | 531f9e9 | 2005-03-15 04:54:21 +0000 | [diff] [blame] | 1061 | Function::arg_iterator OutputArgBegin = newFunction->arg_begin(); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1062 | unsigned FirstOut = inputs.size(); |
| 1063 | if (!AggregateArgs) |
| 1064 | std::advance(OutputArgBegin, inputs.size()); |
| 1065 | |
Jakub Kuderski | cbe9fae | 2017-10-06 03:37:06 +0000 | [diff] [blame] | 1066 | // Reload the outputs passed in by reference. |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1067 | for (unsigned i = 0, e = outputs.size(); i != e; ++i) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1068 | Value *Output = nullptr; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1069 | if (AggregateArgs) { |
David Greene | c656cbb | 2007-09-04 15:46:09 +0000 | [diff] [blame] | 1070 | Value *Idx[2]; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1071 | Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); |
| 1072 | Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i); |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 1073 | GetElementPtrInst *GEP = GetElementPtrInst::Create( |
| 1074 | StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1075 | codeReplacer->getInstList().push_back(GEP); |
| 1076 | Output = GEP; |
| 1077 | } else { |
| 1078 | Output = ReloadOutputs[i]; |
| 1079 | } |
James Y Knight | 14359ef | 2019-02-01 20:44:24 +0000 | [diff] [blame] | 1080 | LoadInst *load = new LoadInst(outputs[i]->getType(), Output, |
| 1081 | outputs[i]->getName() + ".reload"); |
Owen Anderson | 34e6148 | 2009-08-25 00:54:39 +0000 | [diff] [blame] | 1082 | Reloads.push_back(load); |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 1083 | codeReplacer->getInstList().push_back(load); |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 1084 | std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end()); |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 1085 | for (unsigned u = 0, e = Users.size(); u != e; ++u) { |
| 1086 | Instruction *inst = cast<Instruction>(Users[u]); |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1087 | if (!Blocks.count(inst->getParent())) |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 1088 | inst->replaceUsesOfWith(outputs[i], load); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1089 | } |
| 1090 | } |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1091 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1092 | // 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] | 1093 | SwitchInst *TheSwitch = |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1094 | SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)), |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1095 | codeReplacer, 0, codeReplacer); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1096 | |
| 1097 | // 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] | 1098 | // function return an unsigned, switch on that number. This loop iterates |
| 1099 | // over all of the blocks in the extracted region, updating any terminator |
| 1100 | // instructions in the to-be-extracted region that branch to blocks that are |
| 1101 | // not in the region to be extracted. |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 1102 | std::map<BasicBlock *, BasicBlock *> ExitBlockMap; |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1103 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1104 | unsigned switchVal = 0; |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1105 | for (BasicBlock *Block : Blocks) { |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 1106 | Instruction *TI = Block->getTerminator(); |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1107 | for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1108 | if (!Blocks.count(TI->getSuccessor(i))) { |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1109 | BasicBlock *OldTarget = TI->getSuccessor(i); |
| 1110 | // add a new basic block which returns the appropriate value |
| 1111 | BasicBlock *&NewTarget = ExitBlockMap[OldTarget]; |
| 1112 | if (!NewTarget) { |
| 1113 | // If we don't already have an exit stub for this non-extracted |
| 1114 | // destination, create one now! |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1115 | NewTarget = BasicBlock::Create(Context, |
| 1116 | OldTarget->getName() + ".exitStub", |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1117 | newFunction); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1118 | unsigned SuccNum = switchVal++; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1119 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1120 | Value *brVal = nullptr; |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1121 | switch (NumExitBlocks) { |
| 1122 | case 0: |
| 1123 | case 1: break; // No value needed. |
| 1124 | case 2: // Conditional branch, return a bool |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1125 | brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1126 | break; |
| 1127 | default: |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1128 | brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1129 | break; |
| 1130 | } |
| 1131 | |
Jakub Kuderski | cbe9fae | 2017-10-06 03:37:06 +0000 | [diff] [blame] | 1132 | ReturnInst::Create(Context, brVal, NewTarget); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1133 | |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1134 | // Update the switch instruction. |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1135 | TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context), |
| 1136 | SuccNum), |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1137 | OldTarget); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1138 | } |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1139 | |
| 1140 | // rewrite the original branch instruction with this new target |
| 1141 | TI->setSuccessor(i, NewTarget); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1142 | } |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1143 | } |
Chris Lattner | 5b2072e | 2004-03-14 23:43:24 +0000 | [diff] [blame] | 1144 | |
Vedant Kumar | 0e5dd51 | 2019-02-08 20:48:04 +0000 | [diff] [blame] | 1145 | // Store the arguments right after the definition of output value. |
| 1146 | // This should be proceeded after creating exit stubs to be ensure that invoke |
| 1147 | // result restore will be placed in the outlined function. |
| 1148 | Function::arg_iterator OAI = OutputArgBegin; |
| 1149 | for (unsigned i = 0, e = outputs.size(); i != e; ++i) { |
| 1150 | auto *OutI = dyn_cast<Instruction>(outputs[i]); |
| 1151 | if (!OutI) |
| 1152 | continue; |
| 1153 | |
| 1154 | // Find proper insertion point. |
| 1155 | BasicBlock::iterator InsertPt; |
| 1156 | // In case OutI is an invoke, we insert the store at the beginning in the |
| 1157 | // 'normal destination' BB. Otherwise we insert the store right after OutI. |
| 1158 | if (auto *InvokeI = dyn_cast<InvokeInst>(OutI)) |
| 1159 | InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt(); |
| 1160 | else if (auto *Phi = dyn_cast<PHINode>(OutI)) |
| 1161 | InsertPt = Phi->getParent()->getFirstInsertionPt(); |
| 1162 | else |
| 1163 | InsertPt = std::next(OutI->getIterator()); |
| 1164 | |
| 1165 | Instruction *InsertBefore = &*InsertPt; |
| 1166 | assert((InsertBefore->getFunction() == newFunction || |
| 1167 | Blocks.count(InsertBefore->getParent())) && |
| 1168 | "InsertPt should be in new function"); |
| 1169 | assert(OAI != newFunction->arg_end() && |
| 1170 | "Number of output arguments should match " |
| 1171 | "the amount of defined values"); |
| 1172 | if (AggregateArgs) { |
| 1173 | Value *Idx[2]; |
| 1174 | Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); |
| 1175 | Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i); |
| 1176 | GetElementPtrInst *GEP = GetElementPtrInst::Create( |
| 1177 | StructArgTy, &*OAI, Idx, "gep_" + outputs[i]->getName(), |
| 1178 | InsertBefore); |
| 1179 | new StoreInst(outputs[i], GEP, InsertBefore); |
| 1180 | // Since there should be only one struct argument aggregating |
| 1181 | // all the output values, we shouldn't increment OAI, which always |
| 1182 | // points to the struct argument, in this case. |
| 1183 | } else { |
| 1184 | new StoreInst(outputs[i], &*OAI, InsertBefore); |
| 1185 | ++OAI; |
| 1186 | } |
| 1187 | } |
| 1188 | |
Chris Lattner | 3d1ca67 | 2004-05-12 03:22:33 +0000 | [diff] [blame] | 1189 | // Now that we've done the deed, simplify the switch instruction. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1190 | Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType(); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1191 | switch (NumExitBlocks) { |
| 1192 | case 0: |
Chris Lattner | 7f1c7ed | 2004-08-12 03:17:02 +0000 | [diff] [blame] | 1193 | // There are no successors (the block containing the switch itself), which |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1194 | // means that previously this was the last part of the function, and hence |
| 1195 | // this should be rewritten as a `ret' |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1196 | |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1197 | // Check if the function should return a value |
Benjamin Kramer | ccce8ba | 2010-01-05 13:12:22 +0000 | [diff] [blame] | 1198 | if (OldFnRetTy->isVoidTy()) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1199 | ReturnInst::Create(Context, nullptr, TheSwitch); // Return void |
Chris Lattner | 7f1c7ed | 2004-08-12 03:17:02 +0000 | [diff] [blame] | 1200 | } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) { |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1201 | // return what we have |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1202 | ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch); |
Chris Lattner | 7f1c7ed | 2004-08-12 03:17:02 +0000 | [diff] [blame] | 1203 | } else { |
| 1204 | // Otherwise we must have code extracted an unwind or something, just |
| 1205 | // return whatever we want. |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 1206 | ReturnInst::Create(Context, |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1207 | Constant::getNullValue(OldFnRetTy), TheSwitch); |
Chris Lattner | 7f1c7ed | 2004-08-12 03:17:02 +0000 | [diff] [blame] | 1208 | } |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1209 | |
Dan Gohman | 158ff2c | 2008-06-21 22:08:46 +0000 | [diff] [blame] | 1210 | TheSwitch->eraseFromParent(); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1211 | break; |
| 1212 | case 1: |
| 1213 | // Only a single destination, change the switch into an unconditional |
| 1214 | // branch. |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1215 | BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch); |
Dan Gohman | 158ff2c | 2008-06-21 22:08:46 +0000 | [diff] [blame] | 1216 | TheSwitch->eraseFromParent(); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1217 | break; |
| 1218 | case 2: |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1219 | BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2), |
| 1220 | call, TheSwitch); |
Dan Gohman | 158ff2c | 2008-06-21 22:08:46 +0000 | [diff] [blame] | 1221 | TheSwitch->eraseFromParent(); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1222 | break; |
| 1223 | default: |
| 1224 | // Otherwise, make the default destination of the switch instruction be one |
| 1225 | // of the other successors. |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 1226 | TheSwitch->setCondition(call); |
| 1227 | TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks)); |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 1228 | // Remove redundant case |
Bob Wilson | e407736 | 2013-09-09 19:14:35 +0000 | [diff] [blame] | 1229 | TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1)); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1230 | break; |
Chris Lattner | 5b2072e | 2004-03-14 23:43:24 +0000 | [diff] [blame] | 1231 | } |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1232 | |
Vedant Kumar | 17d9f14 | 2019-01-19 02:37:59 +0000 | [diff] [blame] | 1233 | // Insert lifetime markers around the reloads of any output values. The |
| 1234 | // allocas output values are stored in are only in-use in the codeRepl block. |
Vedant Kumar | 4b0cc9a | 2019-02-13 19:53:38 +0000 | [diff] [blame] | 1235 | insertLifetimeMarkersSurroundingCall(M, ReloadOutputs, ReloadOutputs, call); |
Vedant Kumar | 17d9f14 | 2019-01-19 02:37:59 +0000 | [diff] [blame] | 1236 | |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1237 | return call; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1238 | } |
| 1239 | |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1240 | void CodeExtractor::moveCodeToFunction(Function *newFunction) { |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1241 | Function *oldFunc = (*Blocks.begin())->getParent(); |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1242 | Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList(); |
| 1243 | Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList(); |
| 1244 | |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1245 | for (BasicBlock *Block : Blocks) { |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1246 | // 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] | 1247 | oldBlocks.remove(Block); |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1248 | |
| 1249 | // Insert this basic block into the new function |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1250 | newBlocks.push_back(Block); |
Sergey Dmitriev | 807960e | 2019-02-08 06:55:18 +0000 | [diff] [blame] | 1251 | |
| 1252 | // Remove @llvm.assume calls that were moved to the new function from the |
| 1253 | // old function's assumption cache. |
| 1254 | if (AC) |
| 1255 | for (auto &I : *Block) |
| 1256 | if (match(&I, m_Intrinsic<Intrinsic::assume>())) |
| 1257 | AC->unregisterAssumption(cast<CallInst>(&I)); |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1258 | } |
| 1259 | } |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1260 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1261 | void CodeExtractor::calculateNewCallTerminatorWeights( |
| 1262 | BasicBlock *CodeReplacer, |
| 1263 | DenseMap<BasicBlock *, BlockFrequency> &ExitWeights, |
| 1264 | BranchProbabilityInfo *BPI) { |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 1265 | using Distribution = BlockFrequencyInfoImplBase::Distribution; |
| 1266 | using BlockNode = BlockFrequencyInfoImplBase::BlockNode; |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1267 | |
| 1268 | // Update the branch weights for the exit block. |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 1269 | Instruction *TI = CodeReplacer->getTerminator(); |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1270 | SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0); |
| 1271 | |
| 1272 | // Block Frequency distribution with dummy node. |
| 1273 | Distribution BranchDist; |
| 1274 | |
| 1275 | // Add each of the frequencies of the successors. |
| 1276 | for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) { |
| 1277 | BlockNode ExitNode(i); |
| 1278 | uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency(); |
| 1279 | if (ExitFreq != 0) |
| 1280 | BranchDist.addExit(ExitNode, ExitFreq); |
| 1281 | else |
| 1282 | BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero()); |
| 1283 | } |
| 1284 | |
| 1285 | // Check for no total weight. |
| 1286 | if (BranchDist.Total == 0) |
| 1287 | return; |
| 1288 | |
| 1289 | // Normalize the distribution so that they can fit in unsigned. |
| 1290 | BranchDist.normalize(); |
| 1291 | |
| 1292 | // Create normalized branch weights and set the metadata. |
| 1293 | for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) { |
| 1294 | const auto &Weight = BranchDist.Weights[I]; |
| 1295 | |
| 1296 | // Get the weight and update the current BFI. |
| 1297 | BranchWeights[Weight.TargetNode.Index] = Weight.Amount; |
| 1298 | BranchProbability BP(Weight.Amount, BranchDist.Total); |
| 1299 | BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP); |
| 1300 | } |
| 1301 | TI->setMetadata( |
| 1302 | LLVMContext::MD_prof, |
| 1303 | MDBuilder(TI->getContext()).createBranchWeights(BranchWeights)); |
| 1304 | } |
| 1305 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1306 | Function *CodeExtractor::extractCodeRegion() { |
| 1307 | if (!isEligible()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1308 | return nullptr; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1309 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1310 | // 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] | 1311 | // block in the region. |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1312 | BasicBlock *header = *Blocks.begin(); |
Florian Hahn | 0e9dec6 | 2017-11-13 10:35:52 +0000 | [diff] [blame] | 1313 | Function *oldFunction = header->getParent(); |
| 1314 | |
| 1315 | // For functions with varargs, check that varargs handling is only done in the |
| 1316 | // outlined function, i.e vastart and vaend are only used in outlined blocks. |
| 1317 | if (AllowVarArgs && oldFunction->getFunctionType()->isVarArg()) { |
| 1318 | auto containsVarArgIntrinsic = [](Instruction &I) { |
| 1319 | if (const CallInst *CI = dyn_cast<CallInst>(&I)) |
| 1320 | if (const Function *F = CI->getCalledFunction()) |
| 1321 | return F->getIntrinsicID() == Intrinsic::vastart || |
| 1322 | F->getIntrinsicID() == Intrinsic::vaend; |
| 1323 | return false; |
| 1324 | }; |
| 1325 | |
| 1326 | for (auto &BB : *oldFunction) { |
| 1327 | if (Blocks.count(&BB)) |
| 1328 | continue; |
| 1329 | if (llvm::any_of(BB, containsVarArgIntrinsic)) |
| 1330 | return nullptr; |
| 1331 | } |
| 1332 | } |
| 1333 | ValueSet inputs, outputs, SinkingCands, HoistingCands; |
| 1334 | BasicBlock *CommonExit = nullptr; |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1335 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1336 | // Calculate the entry frequency of the new function before we change the root |
| 1337 | // block. |
| 1338 | BlockFrequency EntryFreq; |
| 1339 | if (BFI) { |
| 1340 | assert(BPI && "Both BPI and BFI are required to preserve profile info"); |
| 1341 | for (BasicBlock *Pred : predecessors(header)) { |
| 1342 | if (Blocks.count(Pred)) |
| 1343 | continue; |
| 1344 | EntryFreq += |
| 1345 | BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header); |
| 1346 | } |
| 1347 | } |
| 1348 | |
Chris Lattner | 13d2ddf | 2004-05-12 16:07:41 +0000 | [diff] [blame] | 1349 | // If we have any return instructions in the region, split those blocks so |
| 1350 | // that the return is not in the region. |
| 1351 | splitReturnBlocks(); |
| 1352 | |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 1353 | // Calculate the exit blocks for the extracted region and the total exit |
| 1354 | // weights for each of those blocks. |
| 1355 | DenseMap<BasicBlock *, BlockFrequency> ExitWeights; |
| 1356 | SmallPtrSet<BasicBlock *, 1> ExitBlocks; |
| 1357 | for (BasicBlock *Block : Blocks) { |
| 1358 | for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE; |
| 1359 | ++SI) { |
| 1360 | if (!Blocks.count(*SI)) { |
| 1361 | // Update the branch weight for this successor. |
| 1362 | if (BFI) { |
| 1363 | BlockFrequency &BF = ExitWeights[*SI]; |
| 1364 | BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI); |
| 1365 | } |
| 1366 | ExitBlocks.insert(*SI); |
| 1367 | } |
| 1368 | } |
| 1369 | } |
| 1370 | NumExitBlocks = ExitBlocks.size(); |
| 1371 | |
| 1372 | // If we have to split PHI nodes of the entry or exit blocks, do so now. |
| 1373 | severSplitPHINodesOfEntry(header); |
| 1374 | severSplitPHINodesOfExits(ExitBlocks); |
| 1375 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1376 | // This takes place of the original loop |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 1377 | BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1378 | "codeRepl", oldFunction, |
Gabor Greif | 697e94c | 2008-05-15 10:04:30 +0000 | [diff] [blame] | 1379 | header); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1380 | |
| 1381 | // 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] | 1382 | // 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] | 1383 | BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1384 | "newFuncRoot"); |
Florian Hahn | e5089e2 | 2017-12-08 21:49:03 +0000 | [diff] [blame] | 1385 | auto *BranchI = BranchInst::Create(header); |
| 1386 | // If the original function has debug info, we have to add a debug location |
| 1387 | // to the new branch instruction from the artificial entry block. |
| 1388 | // We use the debug location of the first instruction in the extracted |
| 1389 | // blocks, as there is no other equivalent line in the source code. |
| 1390 | if (oldFunction->getSubprogram()) { |
| 1391 | any_of(Blocks, [&BranchI](const BasicBlock *BB) { |
| 1392 | return any_of(*BB, [&BranchI](const Instruction &I) { |
| 1393 | if (!I.getDebugLoc()) |
| 1394 | return false; |
| 1395 | BranchI->setDebugLoc(I.getDebugLoc()); |
| 1396 | return true; |
| 1397 | }); |
| 1398 | }); |
| 1399 | } |
| 1400 | newFuncRoot->getInstList().push_back(BranchI); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1401 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 1402 | findAllocas(SinkingCands, HoistingCands, CommonExit); |
| 1403 | assert(HoistingCands.empty() || CommonExit); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 1404 | |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1405 | // Find inputs to, outputs from the code region. |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 1406 | findInputsOutputs(inputs, outputs, SinkingCands); |
| 1407 | |
| 1408 | // Now sink all instructions which only have non-phi uses inside the region |
| 1409 | for (auto *II : SinkingCands) |
| 1410 | cast<Instruction>(II)->moveBefore(*newFuncRoot, |
| 1411 | newFuncRoot->getFirstInsertionPt()); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1412 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 1413 | if (!HoistingCands.empty()) { |
| 1414 | auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit); |
| 1415 | Instruction *TI = HoistToBlock->getTerminator(); |
| 1416 | for (auto *II : HoistingCands) |
| 1417 | cast<Instruction>(II)->moveBefore(TI); |
| 1418 | } |
| 1419 | |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1420 | // Collect objects which are inputs to the extraction region and also |
Vedant Kumar | 5f5cac3 | 2019-02-15 18:46:58 +0000 | [diff] [blame] | 1421 | // referenced by lifetime start markers within it. The effects of these |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1422 | // markers must be replicated in the calling function to prevent the stack |
| 1423 | // coloring pass from merging slots which store input objects. |
Vedant Kumar | 5f5cac3 | 2019-02-15 18:46:58 +0000 | [diff] [blame] | 1424 | ValueSet LifetimesStart; |
| 1425 | eraseLifetimeMarkersOnInputs(Blocks, SinkingCands, LifetimesStart); |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1426 | |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1427 | // Construct new function based on inputs/outputs & add allocas for all defs. |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1428 | Function *newFunction = |
| 1429 | constructFunction(inputs, outputs, header, newFuncRoot, codeReplacer, |
| 1430 | oldFunction, oldFunction->getParent()); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1431 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1432 | // Update the entry count of the function. |
| 1433 | if (BFI) { |
Easwaran Raman | e5b8de2 | 2018-01-17 22:24:23 +0000 | [diff] [blame] | 1434 | auto Count = BFI->getProfileCountFromFreq(EntryFreq.getFrequency()); |
| 1435 | if (Count.hasValue()) |
| 1436 | newFunction->setEntryCount( |
| 1437 | ProfileCount(Count.getValue(), Function::PCT_Real)); // FIXME |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1438 | BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency()); |
| 1439 | } |
| 1440 | |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1441 | CallInst *TheCall = |
| 1442 | emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1443 | |
Chris Lattner | 9c431f6 | 2004-03-14 22:34:55 +0000 | [diff] [blame] | 1444 | moveCodeToFunction(newFunction); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1445 | |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1446 | // Replicate the effects of any lifetime start/end markers which referenced |
| 1447 | // input objects in the extraction region by placing markers around the call. |
Vedant Kumar | 5f5cac3 | 2019-02-15 18:46:58 +0000 | [diff] [blame] | 1448 | insertLifetimeMarkersSurroundingCall( |
| 1449 | oldFunction->getParent(), LifetimesStart.getArrayRef(), {}, TheCall); |
Vedant Kumar | a1778df | 2019-01-04 17:43:22 +0000 | [diff] [blame] | 1450 | |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 1451 | // Propagate personality info to the new function if there is one. |
| 1452 | if (oldFunction->hasPersonalityFn()) |
| 1453 | newFunction->setPersonalityFn(oldFunction->getPersonalityFn()); |
| 1454 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1455 | // Update the branch weights for the exit block. |
| 1456 | if (BFI && NumExitBlocks > 1) |
| 1457 | calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI); |
| 1458 | |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 1459 | // Loop over all of the PHI nodes in the header and exit blocks, and change |
| 1460 | // any references to the old incoming edge to be the new incoming edge. |
Reid Spencer | 6614946 | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 1461 | for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) { |
| 1462 | PHINode *PN = cast<PHINode>(I); |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 1463 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1464 | if (!Blocks.count(PN->getIncomingBlock(i))) |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 1465 | PN->setIncomingBlock(i, newFuncRoot); |
Reid Spencer | 6614946 | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 1466 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1467 | |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 1468 | for (BasicBlock *ExitBB : ExitBlocks) |
| 1469 | for (PHINode &PN : ExitBB->phis()) { |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 1470 | Value *IncomingCodeReplacerVal = nullptr; |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 1471 | for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 1472 | // Ignore incoming values from outside of the extracted region. |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 1473 | if (!Blocks.count(PN.getIncomingBlock(i))) |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 1474 | continue; |
| 1475 | |
| 1476 | // Ensure that there is only one incoming value from codeReplacer. |
| 1477 | if (!IncomingCodeReplacerVal) { |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 1478 | PN.setIncomingBlock(i, codeReplacer); |
| 1479 | IncomingCodeReplacerVal = PN.getIncomingValue(i); |
| 1480 | } else |
| 1481 | assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) && |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 1482 | "PHI has two incompatbile incoming values from codeRepl"); |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 1483 | } |
Chris Lattner | 5627382 | 2004-08-13 03:27:07 +0000 | [diff] [blame] | 1484 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1485 | |
Vedant Kumar | 15718a6 | 2018-10-15 19:22:20 +0000 | [diff] [blame] | 1486 | // Erase debug info intrinsics. Variable updates within the new function are |
| 1487 | // invisible to debuggers. This could be improved by defining a DISubprogram |
| 1488 | // for the new function. |
| 1489 | for (BasicBlock &BB : *newFunction) { |
| 1490 | auto BlockIt = BB.begin(); |
Vedant Kumar | 09b7aa4 | 2018-11-06 19:05:53 +0000 | [diff] [blame] | 1491 | // Remove debug info intrinsics from the new function. |
Vedant Kumar | 15718a6 | 2018-10-15 19:22:20 +0000 | [diff] [blame] | 1492 | while (BlockIt != BB.end()) { |
| 1493 | Instruction *Inst = &*BlockIt; |
| 1494 | ++BlockIt; |
| 1495 | if (isa<DbgInfoIntrinsic>(Inst)) |
| 1496 | Inst->eraseFromParent(); |
| 1497 | } |
Vedant Kumar | 09b7aa4 | 2018-11-06 19:05:53 +0000 | [diff] [blame] | 1498 | // Remove debug info intrinsics which refer to values in the new function |
| 1499 | // from the old function. |
| 1500 | SmallVector<DbgVariableIntrinsic *, 4> DbgUsers; |
| 1501 | for (Instruction &I : BB) |
| 1502 | findDbgUsers(DbgUsers, &I); |
| 1503 | for (DbgVariableIntrinsic *DVI : DbgUsers) |
| 1504 | DVI->eraseFromParent(); |
Vedant Kumar | 15718a6 | 2018-10-15 19:22:20 +0000 | [diff] [blame] | 1505 | } |
| 1506 | |
Vedant Kumar | 09415a8 | 2018-12-05 19:35:37 +0000 | [diff] [blame] | 1507 | // Mark the new function `noreturn` if applicable. Terminators which resume |
| 1508 | // exception propagation are treated as returning instructions. This is to |
| 1509 | // avoid inserting traps after calls to outlined functions which unwind. |
Vedant Kumar | d669942 | 2018-11-08 17:57:09 +0000 | [diff] [blame] | 1510 | bool doesNotReturn = none_of(*newFunction, [](const BasicBlock &BB) { |
Vedant Kumar | 09415a8 | 2018-12-05 19:35:37 +0000 | [diff] [blame] | 1511 | const Instruction *Term = BB.getTerminator(); |
| 1512 | return isa<ReturnInst>(Term) || isa<ResumeInst>(Term); |
Vedant Kumar | d669942 | 2018-11-08 17:57:09 +0000 | [diff] [blame] | 1513 | }); |
| 1514 | if (doesNotReturn) |
| 1515 | newFunction->setDoesNotReturn(); |
| 1516 | |
Vedant Kumar | b2a6f8e | 2018-12-07 03:01:54 +0000 | [diff] [blame] | 1517 | LLVM_DEBUG(if (verifyFunction(*newFunction, &errs())) { |
| 1518 | newFunction->dump(); |
| 1519 | report_fatal_error("verification of newFunction failed!"); |
| 1520 | }); |
Vedant Kumar | d129569 | 2018-12-03 22:40:21 +0000 | [diff] [blame] | 1521 | LLVM_DEBUG(if (verifyFunction(*oldFunction)) |
| 1522 | report_fatal_error("verification of oldFunction failed!")); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1523 | return newFunction; |
| 1524 | } |