LLVM 24.0.0git
CodeExtractor.h
Go to the documentation of this file.
1//===- Transform/Utils/CodeExtractor.h - Code extraction util ---*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// A utility to support extracting code from one function into its own
10// stand-alone function.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_TRANSFORMS_UTILS_CODEEXTRACTOR_H
15#define LLVM_TRANSFORMS_UTILS_CODEEXTRACTOR_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SetVector.h"
20#include "llvm/IR/BasicBlock.h"
21#include "llvm/IR/DebugLoc.h"
22#include "llvm/IR/IRBuilder.h"
24#include <limits>
25
26namespace llvm {
27
28template <typename PtrType> class SmallPtrSetImpl;
30class AllocaInst;
31class BlockFrequency;
34class AssumptionCache;
35class CallInst;
36class DominatorTree;
37class Function;
38class Instruction;
39class Module;
40class Type;
41class Value;
42class StructType;
43
44/// A cache for the CodeExtractor analysis. The operation \ref
45/// CodeExtractor::extractCodeRegion is guaranteed not to invalidate this
46/// object. This object should conservatively be considered invalid if any
47/// other mutating operations on the IR occur.
48///
49/// Constructing this object is O(n) in the size of the function.
51 /// The allocas in the function.
53
54 /// Base memory addresses of load/store instructions, grouped by block.
56
57 /// Blocks which contain instructions which may have unknown side-effects
58 /// on memory.
59 DenseSet<BasicBlock *> SideEffectingBlocks;
60
61 void findSideEffectInfoForBlock(BasicBlock &BB);
62
63public:
65
66 /// Get the allocas in the function at the time the analysis was created.
67 /// Note that some of these allocas may no longer be present in the function,
68 /// due to \ref CodeExtractor::extractCodeRegion.
69 ArrayRef<AllocaInst *> getAllocas() const { return Allocas; }
70
71 /// Check whether \p BB contains an instruction thought to load from, store
72 /// to, or otherwise clobber the alloca \p Addr.
74 AllocaInst *Addr) const;
75};
76
77/// Utility class for extracting code into a new function.
78///
79/// This utility provides a simple interface for extracting some sequence of
80/// code into its own function, replacing it with a call to that function. It
81/// also provides various methods to query about the nature and result of such a
82/// transformation.
83///
84/// The rough algorithm used is:
85/// 1) Find both the inputs and outputs for the extracted region.
86/// 2) Pass the inputs as arguments, remapping them within the extracted
87/// function to arguments.
88/// 3) Add allocas for any scalar outputs, adding all of the outputs' allocas as
89/// arguments, and inserting stores to the arguments for any scalars.
91 using ValueSet = SetVector<Value *>;
92
93 // Various bits of state computed on construction.
94 DominatorTree *const DT;
95 const bool AggregateArgs;
99
100 /// A block outside of the extraction set where any intermediate allocations
101 /// will be placed inside. If this is null, allocations will be placed in the
102 /// entry block of the function.
103 BasicBlock *AllocationBlock;
104
105 /// A set of blocks outside of the extraction set where deallocations for
106 /// intermediate allocations should be placed. Not used for automatically
107 /// deallocated memory (e.g. `alloca`), which is the default.
108 ///
109 /// If it is empty and needed, the end of the replacement basic block will be
110 /// used to place deallocations.
111 SmallVector<BasicBlock *> DeallocationBlocks;
112
113 /// If true, varargs functions can be extracted.
114 bool AllowVarArgs;
115
116 /// Bits of intermediate state computed at various phases of extraction.
118
119 /// Lists of blocks that are branched from the code region to be extracted,
120 /// also called the exit blocks. Each block is contained at most once. Its
121 /// order defines the return value of the extracted function.
122 ///
123 /// When there is just one (or no) exit block, the return value is irrelevant.
124 ///
125 /// When there are exactly two exit blocks, the extracted function returns a
126 /// boolean. For ExtractedFuncRetVals[0], it returns 'true'. For
127 /// ExtractedFuncRetVals[1] it returns 'false'.
128 /// NOTE: Since a boolean is represented by i1, ExtractedFuncRetVals[0]
129 /// returns 1 and ExtractedFuncRetVals[1] returns 0, which opposite of
130 /// the regular pattern below.
131 ///
132 /// When there are 3 or more exit blocks, leaving the extracted function via
133 /// the first block it returns 0. When leaving via the second entry it returns
134 /// 1, etc.
135 SmallVector<BasicBlock *> ExtractedFuncRetVals;
136
137 /// Suffix to use when creating extracted function (appended to the original
138 /// function name + "."). If empty, the default is to use the entry block
139 /// label, if non-empty, otherwise "extracted".
140 std::string Suffix;
141
142 /// If true, the outlined function has aggregate argument in zero address
143 /// space.
144 bool ArgsInZeroAddressSpace;
145
146 // If true, the outlined function always return void even when there is only
147 // one output.
148 bool VoidReturnWithSingleOutput;
149
150 // If set, the return value of the outline function.
151 Value *FuncRetVal = nullptr;
152
153public:
154 /// Create a code extractor for a sequence of blocks.
155 ///
156 /// Given a sequence of basic blocks where the first block in the sequence
157 /// dominates the rest, prepare a code extractor object for pulling this
158 /// sequence out into its new function. When a DominatorTree is also given,
159 /// extra checking and transformations are enabled. If AllowVarArgs is true,
160 /// vararg functions can be extracted. This is safe, if all vararg handling
161 /// code is extracted, including vastart. If AllowAlloca is true, then
162 /// extraction of blocks containing alloca instructions would be possible,
163 /// however code extractor won't validate whether extraction is legal. Any new
164 /// allocations will be placed in the AllocationBlock, unless it is null, in
165 /// which case it will be placed in the entry block of the function from which
166 /// the code is being extracted. Explicit deallocations for the aforementioned
167 /// allocations will be placed, if needed, in all blocks in DeallocationBlocks
168 /// or the end of the replacement block. If ArgsInZeroAddressSpace param is
169 /// set to true, then the aggregate param pointer of the outlined function is
170 /// declared in zero address space. If VoidReturnWithSingleOutput is set to
171 /// true, then the return type of the outlined function is set void even if
172 /// there is only one output.
174 bool AggregateArgs = false, BlockFrequencyInfo *BFI = nullptr,
175 BranchProbabilityInfo *BPI = nullptr,
176 AssumptionCache *AC = nullptr, bool AllowVarArgs = false,
177 bool AllowAlloca = false, BasicBlock *AllocationBlock = nullptr,
178 ArrayRef<BasicBlock *> DeallocationBlocks = {},
179 std::string Suffix = "", bool ArgsInZeroAddressSpace = false,
180 bool VoidReturnWithSingleOutput = true);
181
182 virtual ~CodeExtractor() = default;
183
184 /// Perform the extraction, returning the new function.
185 ///
186 /// Returns zero when called on a CodeExtractor instance where isEligible
187 /// returns false.
189
190 /// Perform the extraction, returning the new function and providing an
191 /// interface to see what was categorized as inputs and outputs.
192 ///
193 /// \param CEAC - Cache to speed up operations for the CodeExtractor when
194 /// hoisting, and extracting lifetime values and assumes.
195 /// \param Inputs [in/out] - filled with values marked as inputs to the newly
196 /// outlined function.
197 /// \param Outputs [out] - filled with values marked as outputs to the newly
198 /// outlined function.
199 /// \returns zero when called on a CodeExtractor instance where isEligible
200 /// returns false.
202 ValueSet &Inputs, ValueSet &Outputs);
203
204 /// Verify that assumption cache isn't stale after a region is extracted.
205 /// Returns true when verifier finds errors. AssumptionCache is passed as
206 /// parameter to make this function stateless.
207 static bool verifyAssumptionCache(const Function &OldFunc,
208 const Function &NewFunc,
209 AssumptionCache *AC);
210
211 /// Test whether this code extractor is eligible.
212 ///
213 /// Based on the blocks used when constructing the code extractor, determine
214 /// whether it is eligible for extraction.
215 ///
216 /// Checks that varargs handling (with vastart and vaend) is only done in the
217 /// outlined blocks.
218 bool isEligible() const;
219
220 /// Compute the set of input values and output values for the code.
221 ///
222 /// These can be used either when performing the extraction or to evaluate the
223 /// expected size of a call to the extracted function. Note that this work
224 /// cannot be cached between the two as once we decide to extract a code
225 /// sequence, that sequence is modified, including changing these sets, before
226 /// extraction occurs. These modifications won't have any significant impact
227 /// on the cost however.
228 void findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs,
229 const ValueSet &Allocas,
230 bool CollectGlobalInputs = false);
231
232 /// Check if life time marker nodes can be hoisted/sunk into the outline
233 /// region.
234 ///
235 /// Returns true if it is safe to do the code motion.
236 bool
238 Instruction *AllocaAddr) const;
239
240 /// Find the set of allocas whose life ranges are contained within the
241 /// outlined region.
242 ///
243 /// Allocas which have life_time markers contained in the outlined region
244 /// should be pushed to the outlined function. The address bitcasts that are
245 /// used by the lifetime markers are also candidates for shrink-wrapping. The
246 /// instructions that need to be sunk are collected in 'Allocas'.
247 void findAllocas(const CodeExtractorAnalysisCache &CEAC, ValueSet &SinkCands,
248 ValueSet &HoistCands, BasicBlock *&ExitBlock) const;
249
250 /// Find or create a block within the outline region for placing hoisted code.
251 ///
252 /// CommonExitBlock is block outside the outline region. It is the common
253 /// successor of blocks inside the region. If there exists a single block
254 /// inside the region that is the predecessor of CommonExitBlock, that block
255 /// will be returned. Otherwise CommonExitBlock will be split and the original
256 /// block will be added to the outline region.
258
259 /// Exclude a value from aggregate argument passing when extracting a code
260 /// region, passing it instead as a scalar.
262
263protected:
264 /// Allocate an intermediate variable at the specified point.
266 DebugLoc DL, Type *VarType,
267 const Twine &Name = Twine(""),
268 AddrSpaceCastInst **CastedAlloc = nullptr);
269
270 /// Deallocate a previously-allocated intermediate variable at the specified
271 /// point.
273 DebugLoc DL, Value *Var, Type *VarType);
274
275private:
276 struct LifetimeMarkerInfo {
277 bool SinkLifeStart = false;
278 bool HoistLifeEnd = false;
279 Instruction *LifeStart = nullptr;
280 Instruction *LifeEnd = nullptr;
281 };
282
283 ValueSet ExcludeArgsFromAggregate;
284
285 LifetimeMarkerInfo getLifetimeMarkers(const CodeExtractorAnalysisCache &CEAC,
286 Instruction *Addr,
287 BasicBlock *ExitBlock) const;
288
289 /// Updates the list of SwitchCases (corresponding to exit blocks) after
290 /// changes of the control flow or the Blocks list.
291 void computeExtractedFuncRetVals();
292
293 /// Return the type used for the return code of the extracted function to
294 /// indicate which exit block to jump to.
295 Type *getSwitchType();
296
297 void severSplitPHINodesOfEntry(BasicBlock *&Header);
298 void severSplitPHINodesOfExits();
299 void splitReturnBlocks();
300
301 void moveCodeToFunction(Function *newFunction);
302
303 void calculateNewCallTerminatorWeights(
304 BasicBlock *CodeReplacer,
307
308 /// Normalizes the control flow of the extracted regions, such as ensuring
309 /// that the extracted region does not contain a return instruction.
310 void normalizeCFGForExtraction(BasicBlock *&header);
311
312 /// Generates the function declaration for the function containing the
313 /// extracted code.
314 Function *
315 constructFunctionDeclaration(const ValueSet &inputs, const ValueSet &outputs,
316 BlockFrequency EntryFreq, const Twine &Name,
317 ValueSet &StructValues, StructType *&StructTy);
318
319 /// Generates the code for the extracted function. That is: a prolog, the
320 /// moved or copied code from the original function, and epilogs for each
321 /// exit.
322 void emitFunctionBody(const ValueSet &inputs, const ValueSet &outputs,
323 const ValueSet &StructValues, Function *newFunction,
324 StructType *StructArgTy, BasicBlock *header,
325 const ValueSet &SinkingCands,
326 SmallVectorImpl<Value *> &NewValues);
327
328 /// Generates a Basic Block that calls the extracted function.
329 CallInst *emitReplacerCall(const ValueSet &inputs, const ValueSet &outputs,
330 const ValueSet &StructValues,
331 Function *newFunction, StructType *StructArgTy,
332 Function *oldFunction, BasicBlock *ReplIP,
333 BlockFrequency EntryFreq,
334 ArrayRef<Value *> LifetimesStart,
335 std::vector<Value *> &Reloads);
336
337 /// Connects the basic block containing the call to the extracted function
338 /// into the original function's control flow.
339 void
340 insertReplacerCall(Function *oldFunction, BasicBlock *header,
341 CallInst *ReplacerCall, const ValueSet &outputs,
342 ArrayRef<Value *> Reloads,
343 const DenseMap<BasicBlock *, BlockFrequency> &ExitWeights);
344};
345
346} // end namespace llvm
347
348#endif // LLVM_TRANSFORMS_UTILS_CODEEXTRACTOR_H
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define LLVM_ABI
Definition Compiler.h:215
This file defines the DenseMap class.
#define F(x, y, z)
Definition MD5.cpp:54
This file implements a set that has insertion order iteration characteristics.
This class represents a conversion between pointers from one address space to another.
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis providing branch probability information.
This class represents a function call, abstracting a target machine's calling convention.
A cache for the CodeExtractor analysis.
ArrayRef< AllocaInst * > getAllocas() const
Get the allocas in the function at the time the analysis was created.
LLVM_ABI CodeExtractorAnalysisCache(Function &F)
LLVM_ABI bool doesBlockContainClobberOfAddr(BasicBlock &BB, AllocaInst *Addr) const
Check whether BB contains an instruction thought to load from, store to, or otherwise clobber the all...
BasicBlock * findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock)
Find or create a block within the outline region for placing hoisted code.
void findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs, const ValueSet &Allocas, bool CollectGlobalInputs=false)
Compute the set of input values and output values for the code.
void findAllocas(const CodeExtractorAnalysisCache &CEAC, ValueSet &SinkCands, ValueSet &HoistCands, BasicBlock *&ExitBlock) const
Find the set of allocas whose life ranges are contained within the outlined region.
CodeExtractor(ArrayRef< BasicBlock * > BBs, DominatorTree *DT=nullptr, bool AggregateArgs=false, BlockFrequencyInfo *BFI=nullptr, BranchProbabilityInfo *BPI=nullptr, AssumptionCache *AC=nullptr, bool AllowVarArgs=false, bool AllowAlloca=false, BasicBlock *AllocationBlock=nullptr, ArrayRef< BasicBlock * > DeallocationBlocks={}, std::string Suffix="", bool ArgsInZeroAddressSpace=false, bool VoidReturnWithSingleOutput=true)
Create a code extractor for a sequence of blocks.
Function * extractCodeRegion(const CodeExtractorAnalysisCache &CEAC)
Perform the extraction, returning the new function.
static bool verifyAssumptionCache(const Function &OldFunc, const Function &NewFunc, AssumptionCache *AC)
Verify that assumption cache isn't stale after a region is extracted.
virtual ~CodeExtractor()=default
virtual Instruction * allocateVar(IRBuilder<>::InsertPoint AllocaIP, DebugLoc DL, Type *VarType, const Twine &Name=Twine(""), AddrSpaceCastInst **CastedAlloc=nullptr)
Allocate an intermediate variable at the specified point.
bool isEligible() const
Test whether this code extractor is eligible.
void excludeArgFromAggregate(Value *Arg)
Exclude a value from aggregate argument passing when extracting a code region, passing it instead as ...
bool isLegalToShrinkwrapLifetimeMarkers(const CodeExtractorAnalysisCache &CEAC, Instruction *AllocaAddr) const
Check if life time marker nodes can be hoisted/sunk into the outline region.
virtual Instruction * deallocateVar(IRBuilder<>::InsertPoint DeallocIP, DebugLoc DL, Value *Var, Type *VarType)
Deallocate a previously-allocated intermediate variable at the specified point.
A debug info location.
Definition DebugLoc.h:126
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
InsertPoint - A saved insertion point.
Definition IRBuilder.h:246
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A vector that has set insertion semantics.
Definition SetVector.h:57
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Class to represent struct types.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
This is an optimization pass for GlobalISel generic memory operations.