File: | build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/CodeGen/CodeGenPrepare.cpp |
Warning: | line 2354, column 10 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===// | ||||
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 | // This pass munges the code in the input function to better prepare it for | ||||
10 | // SelectionDAG-based code generation. This works around limitations in it's | ||||
11 | // basic-block-at-a-time approach. It should eventually be removed. | ||||
12 | // | ||||
13 | //===----------------------------------------------------------------------===// | ||||
14 | |||||
15 | #include "llvm/ADT/APInt.h" | ||||
16 | #include "llvm/ADT/ArrayRef.h" | ||||
17 | #include "llvm/ADT/DenseMap.h" | ||||
18 | #include "llvm/ADT/MapVector.h" | ||||
19 | #include "llvm/ADT/PointerIntPair.h" | ||||
20 | #include "llvm/ADT/STLExtras.h" | ||||
21 | #include "llvm/ADT/SmallPtrSet.h" | ||||
22 | #include "llvm/ADT/SmallVector.h" | ||||
23 | #include "llvm/ADT/Statistic.h" | ||||
24 | #include "llvm/Analysis/BlockFrequencyInfo.h" | ||||
25 | #include "llvm/Analysis/BranchProbabilityInfo.h" | ||||
26 | #include "llvm/Analysis/InstructionSimplify.h" | ||||
27 | #include "llvm/Analysis/LoopInfo.h" | ||||
28 | #include "llvm/Analysis/ProfileSummaryInfo.h" | ||||
29 | #include "llvm/Analysis/TargetLibraryInfo.h" | ||||
30 | #include "llvm/Analysis/TargetTransformInfo.h" | ||||
31 | #include "llvm/Analysis/ValueTracking.h" | ||||
32 | #include "llvm/Analysis/VectorUtils.h" | ||||
33 | #include "llvm/CodeGen/Analysis.h" | ||||
34 | #include "llvm/CodeGen/ISDOpcodes.h" | ||||
35 | #include "llvm/CodeGen/SelectionDAGNodes.h" | ||||
36 | #include "llvm/CodeGen/TargetLowering.h" | ||||
37 | #include "llvm/CodeGen/TargetPassConfig.h" | ||||
38 | #include "llvm/CodeGen/TargetSubtargetInfo.h" | ||||
39 | #include "llvm/CodeGen/ValueTypes.h" | ||||
40 | #include "llvm/Config/llvm-config.h" | ||||
41 | #include "llvm/IR/Argument.h" | ||||
42 | #include "llvm/IR/Attributes.h" | ||||
43 | #include "llvm/IR/BasicBlock.h" | ||||
44 | #include "llvm/IR/Constant.h" | ||||
45 | #include "llvm/IR/Constants.h" | ||||
46 | #include "llvm/IR/DataLayout.h" | ||||
47 | #include "llvm/IR/DebugInfo.h" | ||||
48 | #include "llvm/IR/DerivedTypes.h" | ||||
49 | #include "llvm/IR/Dominators.h" | ||||
50 | #include "llvm/IR/Function.h" | ||||
51 | #include "llvm/IR/GetElementPtrTypeIterator.h" | ||||
52 | #include "llvm/IR/GlobalValue.h" | ||||
53 | #include "llvm/IR/GlobalVariable.h" | ||||
54 | #include "llvm/IR/IRBuilder.h" | ||||
55 | #include "llvm/IR/InlineAsm.h" | ||||
56 | #include "llvm/IR/InstrTypes.h" | ||||
57 | #include "llvm/IR/Instruction.h" | ||||
58 | #include "llvm/IR/Instructions.h" | ||||
59 | #include "llvm/IR/IntrinsicInst.h" | ||||
60 | #include "llvm/IR/Intrinsics.h" | ||||
61 | #include "llvm/IR/IntrinsicsAArch64.h" | ||||
62 | #include "llvm/IR/LLVMContext.h" | ||||
63 | #include "llvm/IR/MDBuilder.h" | ||||
64 | #include "llvm/IR/Module.h" | ||||
65 | #include "llvm/IR/Operator.h" | ||||
66 | #include "llvm/IR/PatternMatch.h" | ||||
67 | #include "llvm/IR/Statepoint.h" | ||||
68 | #include "llvm/IR/Type.h" | ||||
69 | #include "llvm/IR/Use.h" | ||||
70 | #include "llvm/IR/User.h" | ||||
71 | #include "llvm/IR/Value.h" | ||||
72 | #include "llvm/IR/ValueHandle.h" | ||||
73 | #include "llvm/IR/ValueMap.h" | ||||
74 | #include "llvm/InitializePasses.h" | ||||
75 | #include "llvm/Pass.h" | ||||
76 | #include "llvm/Support/BlockFrequency.h" | ||||
77 | #include "llvm/Support/BranchProbability.h" | ||||
78 | #include "llvm/Support/Casting.h" | ||||
79 | #include "llvm/Support/CommandLine.h" | ||||
80 | #include "llvm/Support/Compiler.h" | ||||
81 | #include "llvm/Support/Debug.h" | ||||
82 | #include "llvm/Support/ErrorHandling.h" | ||||
83 | #include "llvm/Support/MachineValueType.h" | ||||
84 | #include "llvm/Support/MathExtras.h" | ||||
85 | #include "llvm/Support/raw_ostream.h" | ||||
86 | #include "llvm/Target/TargetMachine.h" | ||||
87 | #include "llvm/Target/TargetOptions.h" | ||||
88 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" | ||||
89 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" | ||||
90 | #include "llvm/Transforms/Utils/Local.h" | ||||
91 | #include "llvm/Transforms/Utils/SimplifyLibCalls.h" | ||||
92 | #include "llvm/Transforms/Utils/SizeOpts.h" | ||||
93 | #include <algorithm> | ||||
94 | #include <cassert> | ||||
95 | #include <cstdint> | ||||
96 | #include <iterator> | ||||
97 | #include <limits> | ||||
98 | #include <memory> | ||||
99 | #include <utility> | ||||
100 | #include <vector> | ||||
101 | |||||
102 | using namespace llvm; | ||||
103 | using namespace llvm::PatternMatch; | ||||
104 | |||||
105 | #define DEBUG_TYPE"codegenprepare" "codegenprepare" | ||||
106 | |||||
107 | STATISTIC(NumBlocksElim, "Number of blocks eliminated")static llvm::Statistic NumBlocksElim = {"codegenprepare", "NumBlocksElim" , "Number of blocks eliminated"}; | ||||
108 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated")static llvm::Statistic NumPHIsElim = {"codegenprepare", "NumPHIsElim" , "Number of trivial PHIs eliminated"}; | ||||
109 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts")static llvm::Statistic NumGEPsElim = {"codegenprepare", "NumGEPsElim" , "Number of GEPs converted to casts"}; | ||||
110 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "static llvm::Statistic NumCmpUses = {"codegenprepare", "NumCmpUses" , "Number of uses of Cmp expressions replaced with uses of " "sunken Cmps" } | ||||
111 | "sunken Cmps")static llvm::Statistic NumCmpUses = {"codegenprepare", "NumCmpUses" , "Number of uses of Cmp expressions replaced with uses of " "sunken Cmps" }; | ||||
112 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "static llvm::Statistic NumCastUses = {"codegenprepare", "NumCastUses" , "Number of uses of Cast expressions replaced with uses " "of sunken Casts" } | ||||
113 | "of sunken Casts")static llvm::Statistic NumCastUses = {"codegenprepare", "NumCastUses" , "Number of uses of Cast expressions replaced with uses " "of sunken Casts" }; | ||||
114 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "static llvm::Statistic NumMemoryInsts = {"codegenprepare", "NumMemoryInsts" , "Number of memory instructions whose address " "computations were sunk" } | ||||
115 | "computations were sunk")static llvm::Statistic NumMemoryInsts = {"codegenprepare", "NumMemoryInsts" , "Number of memory instructions whose address " "computations were sunk" }; | ||||
116 | STATISTIC(NumMemoryInstsPhiCreated,static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare" , "NumMemoryInstsPhiCreated", "Number of phis created when address " "computations were sunk to memory instructions"} | ||||
117 | "Number of phis created when address "static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare" , "NumMemoryInstsPhiCreated", "Number of phis created when address " "computations were sunk to memory instructions"} | ||||
118 | "computations were sunk to memory instructions")static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare" , "NumMemoryInstsPhiCreated", "Number of phis created when address " "computations were sunk to memory instructions"}; | ||||
119 | STATISTIC(NumMemoryInstsSelectCreated,static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare" , "NumMemoryInstsSelectCreated", "Number of select created when address " "computations were sunk to memory instructions"} | ||||
120 | "Number of select created when address "static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare" , "NumMemoryInstsSelectCreated", "Number of select created when address " "computations were sunk to memory instructions"} | ||||
121 | "computations were sunk to memory instructions")static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare" , "NumMemoryInstsSelectCreated", "Number of select created when address " "computations were sunk to memory instructions"}; | ||||
122 | STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads")static llvm::Statistic NumExtsMoved = {"codegenprepare", "NumExtsMoved" , "Number of [s|z]ext instructions combined with loads"}; | ||||
123 | STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized")static llvm::Statistic NumExtUses = {"codegenprepare", "NumExtUses" , "Number of uses of [s|z]ext instructions optimized"}; | ||||
124 | STATISTIC(NumAndsAdded,static llvm::Statistic NumAndsAdded = {"codegenprepare", "NumAndsAdded" , "Number of and mask instructions added to form ext loads"} | ||||
125 | "Number of and mask instructions added to form ext loads")static llvm::Statistic NumAndsAdded = {"codegenprepare", "NumAndsAdded" , "Number of and mask instructions added to form ext loads"}; | ||||
126 | STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized")static llvm::Statistic NumAndUses = {"codegenprepare", "NumAndUses" , "Number of uses of and mask instructions optimized"}; | ||||
127 | STATISTIC(NumRetsDup, "Number of return instructions duplicated")static llvm::Statistic NumRetsDup = {"codegenprepare", "NumRetsDup" , "Number of return instructions duplicated"}; | ||||
128 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved")static llvm::Statistic NumDbgValueMoved = {"codegenprepare", "NumDbgValueMoved" , "Number of debug value instructions moved"}; | ||||
129 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches")static llvm::Statistic NumSelectsExpanded = {"codegenprepare" , "NumSelectsExpanded", "Number of selects turned into branches" }; | ||||
130 | STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed")static llvm::Statistic NumStoreExtractExposed = {"codegenprepare" , "NumStoreExtractExposed", "Number of store(extractelement) exposed" }; | ||||
131 | |||||
132 | static cl::opt<bool> DisableBranchOpts( | ||||
133 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), | ||||
134 | cl::desc("Disable branch optimizations in CodeGenPrepare")); | ||||
135 | |||||
136 | static cl::opt<bool> | ||||
137 | DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), | ||||
138 | cl::desc("Disable GC optimizations in CodeGenPrepare")); | ||||
139 | |||||
140 | static cl::opt<bool> DisableSelectToBranch( | ||||
141 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), | ||||
142 | cl::desc("Disable select to branch conversion.")); | ||||
143 | |||||
144 | static cl::opt<bool> AddrSinkUsingGEPs( | ||||
145 | "addr-sink-using-gep", cl::Hidden, cl::init(true), | ||||
146 | cl::desc("Address sinking in CGP using GEPs.")); | ||||
147 | |||||
148 | static cl::opt<bool> EnableAndCmpSinking( | ||||
149 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), | ||||
150 | cl::desc("Enable sinkinig and/cmp into branches.")); | ||||
151 | |||||
152 | static cl::opt<bool> DisableStoreExtract( | ||||
153 | "disable-cgp-store-extract", cl::Hidden, cl::init(false), | ||||
154 | cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); | ||||
155 | |||||
156 | static cl::opt<bool> StressStoreExtract( | ||||
157 | "stress-cgp-store-extract", cl::Hidden, cl::init(false), | ||||
158 | cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); | ||||
159 | |||||
160 | static cl::opt<bool> DisableExtLdPromotion( | ||||
161 | "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), | ||||
162 | cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " | ||||
163 | "CodeGenPrepare")); | ||||
164 | |||||
165 | static cl::opt<bool> StressExtLdPromotion( | ||||
166 | "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), | ||||
167 | cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " | ||||
168 | "optimization in CodeGenPrepare")); | ||||
169 | |||||
170 | static cl::opt<bool> DisablePreheaderProtect( | ||||
171 | "disable-preheader-prot", cl::Hidden, cl::init(false), | ||||
172 | cl::desc("Disable protection against removing loop preheaders")); | ||||
173 | |||||
174 | static cl::opt<bool> ProfileGuidedSectionPrefix( | ||||
175 | "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore, | ||||
176 | cl::desc("Use profile info to add section prefix for hot/cold functions")); | ||||
177 | |||||
178 | static cl::opt<bool> ProfileUnknownInSpecialSection( | ||||
179 | "profile-unknown-in-special-section", cl::Hidden, cl::init(false), | ||||
180 | cl::ZeroOrMore, | ||||
181 | cl::desc("In profiling mode like sampleFDO, if a function doesn't have " | ||||
182 | "profile, we cannot tell the function is cold for sure because " | ||||
183 | "it may be a function newly added without ever being sampled. " | ||||
184 | "With the flag enabled, compiler can put such profile unknown " | ||||
185 | "functions into a special section, so runtime system can choose " | ||||
186 | "to handle it in a different way than .text section, to save " | ||||
187 | "RAM for example. ")); | ||||
188 | |||||
189 | static cl::opt<unsigned> FreqRatioToSkipMerge( | ||||
190 | "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2), | ||||
191 | cl::desc("Skip merging empty blocks if (frequency of empty block) / " | ||||
192 | "(frequency of destination block) is greater than this ratio")); | ||||
193 | |||||
194 | static cl::opt<bool> ForceSplitStore( | ||||
195 | "force-split-store", cl::Hidden, cl::init(false), | ||||
196 | cl::desc("Force store splitting no matter what the target query says.")); | ||||
197 | |||||
198 | static cl::opt<bool> | ||||
199 | EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden, | ||||
200 | cl::desc("Enable merging of redundant sexts when one is dominating" | ||||
201 | " the other."), cl::init(true)); | ||||
202 | |||||
203 | static cl::opt<bool> DisableComplexAddrModes( | ||||
204 | "disable-complex-addr-modes", cl::Hidden, cl::init(false), | ||||
205 | cl::desc("Disables combining addressing modes with different parts " | ||||
206 | "in optimizeMemoryInst.")); | ||||
207 | |||||
208 | static cl::opt<bool> | ||||
209 | AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false), | ||||
210 | cl::desc("Allow creation of Phis in Address sinking.")); | ||||
211 | |||||
212 | static cl::opt<bool> | ||||
213 | AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true), | ||||
214 | cl::desc("Allow creation of selects in Address sinking.")); | ||||
215 | |||||
216 | static cl::opt<bool> AddrSinkCombineBaseReg( | ||||
217 | "addr-sink-combine-base-reg", cl::Hidden, cl::init(true), | ||||
218 | cl::desc("Allow combining of BaseReg field in Address sinking.")); | ||||
219 | |||||
220 | static cl::opt<bool> AddrSinkCombineBaseGV( | ||||
221 | "addr-sink-combine-base-gv", cl::Hidden, cl::init(true), | ||||
222 | cl::desc("Allow combining of BaseGV field in Address sinking.")); | ||||
223 | |||||
224 | static cl::opt<bool> AddrSinkCombineBaseOffs( | ||||
225 | "addr-sink-combine-base-offs", cl::Hidden, cl::init(true), | ||||
226 | cl::desc("Allow combining of BaseOffs field in Address sinking.")); | ||||
227 | |||||
228 | static cl::opt<bool> AddrSinkCombineScaledReg( | ||||
229 | "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true), | ||||
230 | cl::desc("Allow combining of ScaledReg field in Address sinking.")); | ||||
231 | |||||
232 | static cl::opt<bool> | ||||
233 | EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden, | ||||
234 | cl::init(true), | ||||
235 | cl::desc("Enable splitting large offset of GEP.")); | ||||
236 | |||||
237 | static cl::opt<bool> EnableICMP_EQToICMP_ST( | ||||
238 | "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false), | ||||
239 | cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion.")); | ||||
240 | |||||
241 | static cl::opt<bool> | ||||
242 | VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false), | ||||
243 | cl::desc("Enable BFI update verification for " | ||||
244 | "CodeGenPrepare.")); | ||||
245 | |||||
246 | static cl::opt<bool> OptimizePhiTypes( | ||||
247 | "cgp-optimize-phi-types", cl::Hidden, cl::init(false), | ||||
248 | cl::desc("Enable converting phi types in CodeGenPrepare")); | ||||
249 | |||||
250 | namespace { | ||||
251 | |||||
252 | enum ExtType { | ||||
253 | ZeroExtension, // Zero extension has been seen. | ||||
254 | SignExtension, // Sign extension has been seen. | ||||
255 | BothExtension // This extension type is used if we saw sext after | ||||
256 | // ZeroExtension had been set, or if we saw zext after | ||||
257 | // SignExtension had been set. It makes the type | ||||
258 | // information of a promoted instruction invalid. | ||||
259 | }; | ||||
260 | |||||
261 | using SetOfInstrs = SmallPtrSet<Instruction *, 16>; | ||||
262 | using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>; | ||||
263 | using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>; | ||||
264 | using SExts = SmallVector<Instruction *, 16>; | ||||
265 | using ValueToSExts = DenseMap<Value *, SExts>; | ||||
266 | |||||
267 | class TypePromotionTransaction; | ||||
268 | |||||
269 | class CodeGenPrepare : public FunctionPass { | ||||
270 | const TargetMachine *TM = nullptr; | ||||
271 | const TargetSubtargetInfo *SubtargetInfo; | ||||
272 | const TargetLowering *TLI = nullptr; | ||||
273 | const TargetRegisterInfo *TRI; | ||||
274 | const TargetTransformInfo *TTI = nullptr; | ||||
275 | const TargetLibraryInfo *TLInfo; | ||||
276 | const LoopInfo *LI; | ||||
277 | std::unique_ptr<BlockFrequencyInfo> BFI; | ||||
278 | std::unique_ptr<BranchProbabilityInfo> BPI; | ||||
279 | ProfileSummaryInfo *PSI; | ||||
280 | |||||
281 | /// As we scan instructions optimizing them, this is the next instruction | ||||
282 | /// to optimize. Transforms that can invalidate this should update it. | ||||
283 | BasicBlock::iterator CurInstIterator; | ||||
284 | |||||
285 | /// Keeps track of non-local addresses that have been sunk into a block. | ||||
286 | /// This allows us to avoid inserting duplicate code for blocks with | ||||
287 | /// multiple load/stores of the same address. The usage of WeakTrackingVH | ||||
288 | /// enables SunkAddrs to be treated as a cache whose entries can be | ||||
289 | /// invalidated if a sunken address computation has been erased. | ||||
290 | ValueMap<Value*, WeakTrackingVH> SunkAddrs; | ||||
291 | |||||
292 | /// Keeps track of all instructions inserted for the current function. | ||||
293 | SetOfInstrs InsertedInsts; | ||||
294 | |||||
295 | /// Keeps track of the type of the related instruction before their | ||||
296 | /// promotion for the current function. | ||||
297 | InstrToOrigTy PromotedInsts; | ||||
298 | |||||
299 | /// Keep track of instructions removed during promotion. | ||||
300 | SetOfInstrs RemovedInsts; | ||||
301 | |||||
302 | /// Keep track of sext chains based on their initial value. | ||||
303 | DenseMap<Value *, Instruction *> SeenChainsForSExt; | ||||
304 | |||||
305 | /// Keep track of GEPs accessing the same data structures such as structs or | ||||
306 | /// arrays that are candidates to be split later because of their large | ||||
307 | /// size. | ||||
308 | MapVector< | ||||
309 | AssertingVH<Value>, | ||||
310 | SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>> | ||||
311 | LargeOffsetGEPMap; | ||||
312 | |||||
313 | /// Keep track of new GEP base after splitting the GEPs having large offset. | ||||
314 | SmallSet<AssertingVH<Value>, 2> NewGEPBases; | ||||
315 | |||||
316 | /// Map serial numbers to Large offset GEPs. | ||||
317 | DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID; | ||||
318 | |||||
319 | /// Keep track of SExt promoted. | ||||
320 | ValueToSExts ValToSExtendedUses; | ||||
321 | |||||
322 | /// True if the function has the OptSize attribute. | ||||
323 | bool OptSize; | ||||
324 | |||||
325 | /// DataLayout for the Function being processed. | ||||
326 | const DataLayout *DL = nullptr; | ||||
327 | |||||
328 | /// Building the dominator tree can be expensive, so we only build it | ||||
329 | /// lazily and update it when required. | ||||
330 | std::unique_ptr<DominatorTree> DT; | ||||
331 | |||||
332 | public: | ||||
333 | static char ID; // Pass identification, replacement for typeid | ||||
334 | |||||
335 | CodeGenPrepare() : FunctionPass(ID) { | ||||
336 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); | ||||
337 | } | ||||
338 | |||||
339 | bool runOnFunction(Function &F) override; | ||||
340 | |||||
341 | StringRef getPassName() const override { return "CodeGen Prepare"; } | ||||
342 | |||||
343 | void getAnalysisUsage(AnalysisUsage &AU) const override { | ||||
344 | // FIXME: When we can selectively preserve passes, preserve the domtree. | ||||
345 | AU.addRequired<ProfileSummaryInfoWrapperPass>(); | ||||
346 | AU.addRequired<TargetLibraryInfoWrapperPass>(); | ||||
347 | AU.addRequired<TargetPassConfig>(); | ||||
348 | AU.addRequired<TargetTransformInfoWrapperPass>(); | ||||
349 | AU.addRequired<LoopInfoWrapperPass>(); | ||||
350 | } | ||||
351 | |||||
352 | private: | ||||
353 | template <typename F> | ||||
354 | void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) { | ||||
355 | // Substituting can cause recursive simplifications, which can invalidate | ||||
356 | // our iterator. Use a WeakTrackingVH to hold onto it in case this | ||||
357 | // happens. | ||||
358 | Value *CurValue = &*CurInstIterator; | ||||
359 | WeakTrackingVH IterHandle(CurValue); | ||||
360 | |||||
361 | f(); | ||||
362 | |||||
363 | // If the iterator instruction was recursively deleted, start over at the | ||||
364 | // start of the block. | ||||
365 | if (IterHandle != CurValue) { | ||||
366 | CurInstIterator = BB->begin(); | ||||
367 | SunkAddrs.clear(); | ||||
368 | } | ||||
369 | } | ||||
370 | |||||
371 | // Get the DominatorTree, building if necessary. | ||||
372 | DominatorTree &getDT(Function &F) { | ||||
373 | if (!DT) | ||||
374 | DT = std::make_unique<DominatorTree>(F); | ||||
375 | return *DT; | ||||
376 | } | ||||
377 | |||||
378 | void removeAllAssertingVHReferences(Value *V); | ||||
379 | bool eliminateAssumptions(Function &F); | ||||
380 | bool eliminateFallThrough(Function &F); | ||||
381 | bool eliminateMostlyEmptyBlocks(Function &F); | ||||
382 | BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB); | ||||
383 | bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; | ||||
384 | void eliminateMostlyEmptyBlock(BasicBlock *BB); | ||||
385 | bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB, | ||||
386 | bool isPreheader); | ||||
387 | bool makeBitReverse(Instruction &I); | ||||
388 | bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT); | ||||
389 | bool optimizeInst(Instruction *I, bool &ModifiedDT); | ||||
390 | bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, | ||||
391 | Type *AccessTy, unsigned AddrSpace); | ||||
392 | bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr); | ||||
393 | bool optimizeInlineAsmInst(CallInst *CS); | ||||
394 | bool optimizeCallInst(CallInst *CI, bool &ModifiedDT); | ||||
395 | bool optimizeExt(Instruction *&I); | ||||
396 | bool optimizeExtUses(Instruction *I); | ||||
397 | bool optimizeLoadExt(LoadInst *Load); | ||||
398 | bool optimizeShiftInst(BinaryOperator *BO); | ||||
399 | bool optimizeFunnelShift(IntrinsicInst *Fsh); | ||||
400 | bool optimizeSelectInst(SelectInst *SI); | ||||
401 | bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI); | ||||
402 | bool optimizeSwitchInst(SwitchInst *SI); | ||||
403 | bool optimizeExtractElementInst(Instruction *Inst); | ||||
404 | bool dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT); | ||||
405 | bool fixupDbgValue(Instruction *I); | ||||
406 | bool placeDbgValues(Function &F); | ||||
407 | bool placePseudoProbes(Function &F); | ||||
408 | bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts, | ||||
409 | LoadInst *&LI, Instruction *&Inst, bool HasPromoted); | ||||
410 | bool tryToPromoteExts(TypePromotionTransaction &TPT, | ||||
411 | const SmallVectorImpl<Instruction *> &Exts, | ||||
412 | SmallVectorImpl<Instruction *> &ProfitablyMovedExts, | ||||
413 | unsigned CreatedInstsCost = 0); | ||||
414 | bool mergeSExts(Function &F); | ||||
415 | bool splitLargeGEPOffsets(); | ||||
416 | bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited, | ||||
417 | SmallPtrSetImpl<Instruction *> &DeletedInstrs); | ||||
418 | bool optimizePhiTypes(Function &F); | ||||
419 | bool performAddressTypePromotion( | ||||
420 | Instruction *&Inst, | ||||
421 | bool AllowPromotionWithoutCommonHeader, | ||||
422 | bool HasPromoted, TypePromotionTransaction &TPT, | ||||
423 | SmallVectorImpl<Instruction *> &SpeculativelyMovedExts); | ||||
424 | bool splitBranchCondition(Function &F, bool &ModifiedDT); | ||||
425 | bool simplifyOffsetableRelocate(GCStatepointInst &I); | ||||
426 | |||||
427 | bool tryToSinkFreeOperands(Instruction *I); | ||||
428 | bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0, | ||||
429 | Value *Arg1, CmpInst *Cmp, | ||||
430 | Intrinsic::ID IID); | ||||
431 | bool optimizeCmp(CmpInst *Cmp, bool &ModifiedDT); | ||||
432 | bool combineToUSubWithOverflow(CmpInst *Cmp, bool &ModifiedDT); | ||||
433 | bool combineToUAddWithOverflow(CmpInst *Cmp, bool &ModifiedDT); | ||||
434 | void verifyBFIUpdates(Function &F); | ||||
435 | }; | ||||
436 | |||||
437 | } // end anonymous namespace | ||||
438 | |||||
439 | char CodeGenPrepare::ID = 0; | ||||
440 | |||||
441 | INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,static void *initializeCodeGenPreparePassOnce(PassRegistry & Registry) { | ||||
442 | "Optimize for code generation", false, false)static void *initializeCodeGenPreparePassOnce(PassRegistry & Registry) { | ||||
443 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)initializeLoopInfoWrapperPassPass(Registry); | ||||
444 | INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)initializeProfileSummaryInfoWrapperPassPass(Registry); | ||||
445 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry); | ||||
446 | INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)initializeTargetPassConfigPass(Registry); | ||||
447 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry); | ||||
448 | INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,PassInfo *PI = new PassInfo( "Optimize for code generation", "codegenprepare" , &CodeGenPrepare::ID, PassInfo::NormalCtor_t(callDefaultCtor <CodeGenPrepare>), false, false); Registry.registerPass (*PI, true); return PI; } static llvm::once_flag InitializeCodeGenPreparePassFlag ; void llvm::initializeCodeGenPreparePass(PassRegistry &Registry ) { llvm::call_once(InitializeCodeGenPreparePassFlag, initializeCodeGenPreparePassOnce , std::ref(Registry)); } | ||||
449 | "Optimize for code generation", false, false)PassInfo *PI = new PassInfo( "Optimize for code generation", "codegenprepare" , &CodeGenPrepare::ID, PassInfo::NormalCtor_t(callDefaultCtor <CodeGenPrepare>), false, false); Registry.registerPass (*PI, true); return PI; } static llvm::once_flag InitializeCodeGenPreparePassFlag ; void llvm::initializeCodeGenPreparePass(PassRegistry &Registry ) { llvm::call_once(InitializeCodeGenPreparePassFlag, initializeCodeGenPreparePassOnce , std::ref(Registry)); } | ||||
450 | |||||
451 | FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); } | ||||
452 | |||||
453 | bool CodeGenPrepare::runOnFunction(Function &F) { | ||||
454 | if (skipFunction(F)) | ||||
455 | return false; | ||||
456 | |||||
457 | DL = &F.getParent()->getDataLayout(); | ||||
458 | |||||
459 | bool EverMadeChange = false; | ||||
460 | // Clear per function information. | ||||
461 | InsertedInsts.clear(); | ||||
462 | PromotedInsts.clear(); | ||||
463 | |||||
464 | TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>(); | ||||
465 | SubtargetInfo = TM->getSubtargetImpl(F); | ||||
466 | TLI = SubtargetInfo->getTargetLowering(); | ||||
467 | TRI = SubtargetInfo->getRegisterInfo(); | ||||
468 | TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); | ||||
469 | TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); | ||||
470 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); | ||||
471 | BPI.reset(new BranchProbabilityInfo(F, *LI)); | ||||
472 | BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI)); | ||||
473 | PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); | ||||
474 | OptSize = F.hasOptSize(); | ||||
475 | if (ProfileGuidedSectionPrefix) { | ||||
476 | // The hot attribute overwrites profile count based hotness while profile | ||||
477 | // counts based hotness overwrite the cold attribute. | ||||
478 | // This is a conservative behabvior. | ||||
479 | if (F.hasFnAttribute(Attribute::Hot) || | ||||
480 | PSI->isFunctionHotInCallGraph(&F, *BFI)) | ||||
481 | F.setSectionPrefix("hot"); | ||||
482 | // If PSI shows this function is not hot, we will placed the function | ||||
483 | // into unlikely section if (1) PSI shows this is a cold function, or | ||||
484 | // (2) the function has a attribute of cold. | ||||
485 | else if (PSI->isFunctionColdInCallGraph(&F, *BFI) || | ||||
486 | F.hasFnAttribute(Attribute::Cold)) | ||||
487 | F.setSectionPrefix("unlikely"); | ||||
488 | else if (ProfileUnknownInSpecialSection && PSI->hasPartialSampleProfile() && | ||||
489 | PSI->isFunctionHotnessUnknown(F)) | ||||
490 | F.setSectionPrefix("unknown"); | ||||
491 | } | ||||
492 | |||||
493 | /// This optimization identifies DIV instructions that can be | ||||
494 | /// profitably bypassed and carried out with a shorter, faster divide. | ||||
495 | if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) { | ||||
496 | const DenseMap<unsigned int, unsigned int> &BypassWidths = | ||||
497 | TLI->getBypassSlowDivWidths(); | ||||
498 | BasicBlock* BB = &*F.begin(); | ||||
499 | while (BB != nullptr) { | ||||
500 | // bypassSlowDivision may create new BBs, but we don't want to reapply the | ||||
501 | // optimization to those blocks. | ||||
502 | BasicBlock* Next = BB->getNextNode(); | ||||
503 | // F.hasOptSize is already checked in the outer if statement. | ||||
504 | if (!llvm::shouldOptimizeForSize(BB, PSI, BFI.get())) | ||||
505 | EverMadeChange |= bypassSlowDivision(BB, BypassWidths); | ||||
506 | BB = Next; | ||||
507 | } | ||||
508 | } | ||||
509 | |||||
510 | // Get rid of @llvm.assume builtins before attempting to eliminate empty | ||||
511 | // blocks, since there might be blocks that only contain @llvm.assume calls | ||||
512 | // (plus arguments that we can get rid of). | ||||
513 | EverMadeChange |= eliminateAssumptions(F); | ||||
514 | |||||
515 | // Eliminate blocks that contain only PHI nodes and an | ||||
516 | // unconditional branch. | ||||
517 | EverMadeChange |= eliminateMostlyEmptyBlocks(F); | ||||
518 | |||||
519 | bool ModifiedDT = false; | ||||
520 | if (!DisableBranchOpts) | ||||
521 | EverMadeChange |= splitBranchCondition(F, ModifiedDT); | ||||
522 | |||||
523 | // Split some critical edges where one of the sources is an indirect branch, | ||||
524 | // to help generate sane code for PHIs involving such edges. | ||||
525 | EverMadeChange |= | ||||
526 | SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true); | ||||
527 | |||||
528 | bool MadeChange = true; | ||||
529 | while (MadeChange) { | ||||
530 | MadeChange = false; | ||||
531 | DT.reset(); | ||||
532 | for (BasicBlock &BB : llvm::make_early_inc_range(F)) { | ||||
533 | bool ModifiedDTOnIteration = false; | ||||
534 | MadeChange |= optimizeBlock(BB, ModifiedDTOnIteration); | ||||
535 | |||||
536 | // Restart BB iteration if the dominator tree of the Function was changed | ||||
537 | if (ModifiedDTOnIteration) | ||||
538 | break; | ||||
539 | } | ||||
540 | if (EnableTypePromotionMerge && !ValToSExtendedUses.empty()) | ||||
541 | MadeChange |= mergeSExts(F); | ||||
542 | if (!LargeOffsetGEPMap.empty()) | ||||
543 | MadeChange |= splitLargeGEPOffsets(); | ||||
544 | MadeChange |= optimizePhiTypes(F); | ||||
545 | |||||
546 | if (MadeChange) | ||||
547 | eliminateFallThrough(F); | ||||
548 | |||||
549 | // Really free removed instructions during promotion. | ||||
550 | for (Instruction *I : RemovedInsts) | ||||
551 | I->deleteValue(); | ||||
552 | |||||
553 | EverMadeChange |= MadeChange; | ||||
554 | SeenChainsForSExt.clear(); | ||||
555 | ValToSExtendedUses.clear(); | ||||
556 | RemovedInsts.clear(); | ||||
557 | LargeOffsetGEPMap.clear(); | ||||
558 | LargeOffsetGEPID.clear(); | ||||
559 | } | ||||
560 | |||||
561 | NewGEPBases.clear(); | ||||
562 | SunkAddrs.clear(); | ||||
563 | |||||
564 | if (!DisableBranchOpts) { | ||||
565 | MadeChange = false; | ||||
566 | // Use a set vector to get deterministic iteration order. The order the | ||||
567 | // blocks are removed may affect whether or not PHI nodes in successors | ||||
568 | // are removed. | ||||
569 | SmallSetVector<BasicBlock*, 8> WorkList; | ||||
570 | for (BasicBlock &BB : F) { | ||||
571 | SmallVector<BasicBlock *, 2> Successors(successors(&BB)); | ||||
572 | MadeChange |= ConstantFoldTerminator(&BB, true); | ||||
573 | if (!MadeChange) continue; | ||||
574 | |||||
575 | for (BasicBlock *Succ : Successors) | ||||
576 | if (pred_empty(Succ)) | ||||
577 | WorkList.insert(Succ); | ||||
578 | } | ||||
579 | |||||
580 | // Delete the dead blocks and any of their dead successors. | ||||
581 | MadeChange |= !WorkList.empty(); | ||||
582 | while (!WorkList.empty()) { | ||||
583 | BasicBlock *BB = WorkList.pop_back_val(); | ||||
584 | SmallVector<BasicBlock*, 2> Successors(successors(BB)); | ||||
585 | |||||
586 | DeleteDeadBlock(BB); | ||||
587 | |||||
588 | for (BasicBlock *Succ : Successors) | ||||
589 | if (pred_empty(Succ)) | ||||
590 | WorkList.insert(Succ); | ||||
591 | } | ||||
592 | |||||
593 | // Merge pairs of basic blocks with unconditional branches, connected by | ||||
594 | // a single edge. | ||||
595 | if (EverMadeChange || MadeChange) | ||||
596 | MadeChange |= eliminateFallThrough(F); | ||||
597 | |||||
598 | EverMadeChange |= MadeChange; | ||||
599 | } | ||||
600 | |||||
601 | if (!DisableGCOpts) { | ||||
602 | SmallVector<GCStatepointInst *, 2> Statepoints; | ||||
603 | for (BasicBlock &BB : F) | ||||
604 | for (Instruction &I : BB) | ||||
605 | if (auto *SP = dyn_cast<GCStatepointInst>(&I)) | ||||
606 | Statepoints.push_back(SP); | ||||
607 | for (auto &I : Statepoints) | ||||
608 | EverMadeChange |= simplifyOffsetableRelocate(*I); | ||||
609 | } | ||||
610 | |||||
611 | // Do this last to clean up use-before-def scenarios introduced by other | ||||
612 | // preparatory transforms. | ||||
613 | EverMadeChange |= placeDbgValues(F); | ||||
614 | EverMadeChange |= placePseudoProbes(F); | ||||
615 | |||||
616 | #ifndef NDEBUG | ||||
617 | if (VerifyBFIUpdates) | ||||
618 | verifyBFIUpdates(F); | ||||
619 | #endif | ||||
620 | |||||
621 | return EverMadeChange; | ||||
622 | } | ||||
623 | |||||
624 | bool CodeGenPrepare::eliminateAssumptions(Function &F) { | ||||
625 | bool MadeChange = false; | ||||
626 | for (BasicBlock &BB : F) { | ||||
627 | CurInstIterator = BB.begin(); | ||||
628 | while (CurInstIterator != BB.end()) { | ||||
629 | Instruction *I = &*(CurInstIterator++); | ||||
630 | if (auto *Assume = dyn_cast<AssumeInst>(I)) { | ||||
631 | MadeChange = true; | ||||
632 | Value *Operand = Assume->getOperand(0); | ||||
633 | Assume->eraseFromParent(); | ||||
634 | |||||
635 | resetIteratorIfInvalidatedWhileCalling(&BB, [&]() { | ||||
636 | RecursivelyDeleteTriviallyDeadInstructions(Operand, TLInfo, nullptr); | ||||
637 | }); | ||||
638 | } | ||||
639 | } | ||||
640 | } | ||||
641 | return MadeChange; | ||||
642 | } | ||||
643 | |||||
644 | /// An instruction is about to be deleted, so remove all references to it in our | ||||
645 | /// GEP-tracking data strcutures. | ||||
646 | void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) { | ||||
647 | LargeOffsetGEPMap.erase(V); | ||||
648 | NewGEPBases.erase(V); | ||||
649 | |||||
650 | auto GEP = dyn_cast<GetElementPtrInst>(V); | ||||
651 | if (!GEP) | ||||
652 | return; | ||||
653 | |||||
654 | LargeOffsetGEPID.erase(GEP); | ||||
655 | |||||
656 | auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand()); | ||||
657 | if (VecI == LargeOffsetGEPMap.end()) | ||||
658 | return; | ||||
659 | |||||
660 | auto &GEPVector = VecI->second; | ||||
661 | llvm::erase_if(GEPVector, [=](auto &Elt) { return Elt.first == GEP; }); | ||||
662 | |||||
663 | if (GEPVector.empty()) | ||||
664 | LargeOffsetGEPMap.erase(VecI); | ||||
665 | } | ||||
666 | |||||
667 | // Verify BFI has been updated correctly by recomputing BFI and comparing them. | ||||
668 | void LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__)) CodeGenPrepare::verifyBFIUpdates(Function &F) { | ||||
669 | DominatorTree NewDT(F); | ||||
670 | LoopInfo NewLI(NewDT); | ||||
671 | BranchProbabilityInfo NewBPI(F, NewLI, TLInfo); | ||||
672 | BlockFrequencyInfo NewBFI(F, NewBPI, NewLI); | ||||
673 | NewBFI.verifyMatch(*BFI); | ||||
674 | } | ||||
675 | |||||
676 | /// Merge basic blocks which are connected by a single edge, where one of the | ||||
677 | /// basic blocks has a single successor pointing to the other basic block, | ||||
678 | /// which has a single predecessor. | ||||
679 | bool CodeGenPrepare::eliminateFallThrough(Function &F) { | ||||
680 | bool Changed = false; | ||||
681 | // Scan all of the blocks in the function, except for the entry block. | ||||
682 | // Use a temporary array to avoid iterator being invalidated when | ||||
683 | // deleting blocks. | ||||
684 | SmallVector<WeakTrackingVH, 16> Blocks; | ||||
685 | for (auto &Block : llvm::drop_begin(F)) | ||||
686 | Blocks.push_back(&Block); | ||||
687 | |||||
688 | SmallSet<WeakTrackingVH, 16> Preds; | ||||
689 | for (auto &Block : Blocks) { | ||||
690 | auto *BB = cast_or_null<BasicBlock>(Block); | ||||
691 | if (!BB) | ||||
692 | continue; | ||||
693 | // If the destination block has a single pred, then this is a trivial | ||||
694 | // edge, just collapse it. | ||||
695 | BasicBlock *SinglePred = BB->getSinglePredecessor(); | ||||
696 | |||||
697 | // Don't merge if BB's address is taken. | ||||
698 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; | ||||
699 | |||||
700 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); | ||||
701 | if (Term && !Term->isConditional()) { | ||||
702 | Changed = true; | ||||
703 | LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "To merge:\n" << * BB << "\n\n\n"; } } while (false); | ||||
704 | |||||
705 | // Merge BB into SinglePred and delete it. | ||||
706 | MergeBlockIntoPredecessor(BB); | ||||
707 | Preds.insert(SinglePred); | ||||
708 | } | ||||
709 | } | ||||
710 | |||||
711 | // (Repeatedly) merging blocks into their predecessors can create redundant | ||||
712 | // debug intrinsics. | ||||
713 | for (auto &Pred : Preds) | ||||
714 | if (auto *BB = cast_or_null<BasicBlock>(Pred)) | ||||
715 | RemoveRedundantDbgInstrs(BB); | ||||
716 | |||||
717 | return Changed; | ||||
718 | } | ||||
719 | |||||
720 | /// Find a destination block from BB if BB is mergeable empty block. | ||||
721 | BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) { | ||||
722 | // If this block doesn't end with an uncond branch, ignore it. | ||||
723 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); | ||||
724 | if (!BI || !BI->isUnconditional()) | ||||
725 | return nullptr; | ||||
726 | |||||
727 | // If the instruction before the branch (skipping debug info) isn't a phi | ||||
728 | // node, then other stuff is happening here. | ||||
729 | BasicBlock::iterator BBI = BI->getIterator(); | ||||
730 | if (BBI != BB->begin()) { | ||||
731 | --BBI; | ||||
732 | while (isa<DbgInfoIntrinsic>(BBI)) { | ||||
733 | if (BBI == BB->begin()) | ||||
734 | break; | ||||
735 | --BBI; | ||||
736 | } | ||||
737 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) | ||||
738 | return nullptr; | ||||
739 | } | ||||
740 | |||||
741 | // Do not break infinite loops. | ||||
742 | BasicBlock *DestBB = BI->getSuccessor(0); | ||||
743 | if (DestBB == BB) | ||||
744 | return nullptr; | ||||
745 | |||||
746 | if (!canMergeBlocks(BB, DestBB)) | ||||
747 | DestBB = nullptr; | ||||
748 | |||||
749 | return DestBB; | ||||
750 | } | ||||
751 | |||||
752 | /// Eliminate blocks that contain only PHI nodes, debug info directives, and an | ||||
753 | /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split | ||||
754 | /// edges in ways that are non-optimal for isel. Start by eliminating these | ||||
755 | /// blocks so we can split them the way we want them. | ||||
756 | bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) { | ||||
757 | SmallPtrSet<BasicBlock *, 16> Preheaders; | ||||
758 | SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end()); | ||||
759 | while (!LoopList.empty()) { | ||||
760 | Loop *L = LoopList.pop_back_val(); | ||||
761 | llvm::append_range(LoopList, *L); | ||||
762 | if (BasicBlock *Preheader = L->getLoopPreheader()) | ||||
763 | Preheaders.insert(Preheader); | ||||
764 | } | ||||
765 | |||||
766 | bool MadeChange = false; | ||||
767 | // Copy blocks into a temporary array to avoid iterator invalidation issues | ||||
768 | // as we remove them. | ||||
769 | // Note that this intentionally skips the entry block. | ||||
770 | SmallVector<WeakTrackingVH, 16> Blocks; | ||||
771 | for (auto &Block : llvm::drop_begin(F)) | ||||
772 | Blocks.push_back(&Block); | ||||
773 | |||||
774 | for (auto &Block : Blocks) { | ||||
775 | BasicBlock *BB = cast_or_null<BasicBlock>(Block); | ||||
776 | if (!BB) | ||||
777 | continue; | ||||
778 | BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB); | ||||
779 | if (!DestBB || | ||||
780 | !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB))) | ||||
781 | continue; | ||||
782 | |||||
783 | eliminateMostlyEmptyBlock(BB); | ||||
784 | MadeChange = true; | ||||
785 | } | ||||
786 | return MadeChange; | ||||
787 | } | ||||
788 | |||||
789 | bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB, | ||||
790 | BasicBlock *DestBB, | ||||
791 | bool isPreheader) { | ||||
792 | // Do not delete loop preheaders if doing so would create a critical edge. | ||||
793 | // Loop preheaders can be good locations to spill registers. If the | ||||
794 | // preheader is deleted and we create a critical edge, registers may be | ||||
795 | // spilled in the loop body instead. | ||||
796 | if (!DisablePreheaderProtect && isPreheader && | ||||
797 | !(BB->getSinglePredecessor() && | ||||
798 | BB->getSinglePredecessor()->getSingleSuccessor())) | ||||
799 | return false; | ||||
800 | |||||
801 | // Skip merging if the block's successor is also a successor to any callbr | ||||
802 | // that leads to this block. | ||||
803 | // FIXME: Is this really needed? Is this a correctness issue? | ||||
804 | for (BasicBlock *Pred : predecessors(BB)) { | ||||
805 | if (auto *CBI = dyn_cast<CallBrInst>((Pred)->getTerminator())) | ||||
806 | for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i) | ||||
807 | if (DestBB == CBI->getSuccessor(i)) | ||||
808 | return false; | ||||
809 | } | ||||
810 | |||||
811 | // Try to skip merging if the unique predecessor of BB is terminated by a | ||||
812 | // switch or indirect branch instruction, and BB is used as an incoming block | ||||
813 | // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to | ||||
814 | // add COPY instructions in the predecessor of BB instead of BB (if it is not | ||||
815 | // merged). Note that the critical edge created by merging such blocks wont be | ||||
816 | // split in MachineSink because the jump table is not analyzable. By keeping | ||||
817 | // such empty block (BB), ISel will place COPY instructions in BB, not in the | ||||
818 | // predecessor of BB. | ||||
819 | BasicBlock *Pred = BB->getUniquePredecessor(); | ||||
820 | if (!Pred || | ||||
821 | !(isa<SwitchInst>(Pred->getTerminator()) || | ||||
822 | isa<IndirectBrInst>(Pred->getTerminator()))) | ||||
823 | return true; | ||||
824 | |||||
825 | if (BB->getTerminator() != BB->getFirstNonPHIOrDbg()) | ||||
826 | return true; | ||||
827 | |||||
828 | // We use a simple cost heuristic which determine skipping merging is | ||||
829 | // profitable if the cost of skipping merging is less than the cost of | ||||
830 | // merging : Cost(skipping merging) < Cost(merging BB), where the | ||||
831 | // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and | ||||
832 | // the Cost(merging BB) is Freq(Pred) * Cost(Copy). | ||||
833 | // Assuming Cost(Copy) == Cost(Branch), we could simplify it to : | ||||
834 | // Freq(Pred) / Freq(BB) > 2. | ||||
835 | // Note that if there are multiple empty blocks sharing the same incoming | ||||
836 | // value for the PHIs in the DestBB, we consider them together. In such | ||||
837 | // case, Cost(merging BB) will be the sum of their frequencies. | ||||
838 | |||||
839 | if (!isa<PHINode>(DestBB->begin())) | ||||
840 | return true; | ||||
841 | |||||
842 | SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs; | ||||
843 | |||||
844 | // Find all other incoming blocks from which incoming values of all PHIs in | ||||
845 | // DestBB are the same as the ones from BB. | ||||
846 | for (BasicBlock *DestBBPred : predecessors(DestBB)) { | ||||
847 | if (DestBBPred == BB) | ||||
848 | continue; | ||||
849 | |||||
850 | if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) { | ||||
851 | return DestPN.getIncomingValueForBlock(BB) == | ||||
852 | DestPN.getIncomingValueForBlock(DestBBPred); | ||||
853 | })) | ||||
854 | SameIncomingValueBBs.insert(DestBBPred); | ||||
855 | } | ||||
856 | |||||
857 | // See if all BB's incoming values are same as the value from Pred. In this | ||||
858 | // case, no reason to skip merging because COPYs are expected to be place in | ||||
859 | // Pred already. | ||||
860 | if (SameIncomingValueBBs.count(Pred)) | ||||
861 | return true; | ||||
862 | |||||
863 | BlockFrequency PredFreq = BFI->getBlockFreq(Pred); | ||||
864 | BlockFrequency BBFreq = BFI->getBlockFreq(BB); | ||||
865 | |||||
866 | for (auto *SameValueBB : SameIncomingValueBBs) | ||||
867 | if (SameValueBB->getUniquePredecessor() == Pred && | ||||
868 | DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB)) | ||||
869 | BBFreq += BFI->getBlockFreq(SameValueBB); | ||||
870 | |||||
871 | return PredFreq.getFrequency() <= | ||||
872 | BBFreq.getFrequency() * FreqRatioToSkipMerge; | ||||
873 | } | ||||
874 | |||||
875 | /// Return true if we can merge BB into DestBB if there is a single | ||||
876 | /// unconditional branch between them, and BB contains no other non-phi | ||||
877 | /// instructions. | ||||
878 | bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB, | ||||
879 | const BasicBlock *DestBB) const { | ||||
880 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in | ||||
881 | // the successor. If there are more complex condition (e.g. preheaders), | ||||
882 | // don't mess around with them. | ||||
883 | for (const PHINode &PN : BB->phis()) { | ||||
884 | for (const User *U : PN.users()) { | ||||
885 | const Instruction *UI = cast<Instruction>(U); | ||||
886 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) | ||||
887 | return false; | ||||
888 | // If User is inside DestBB block and it is a PHINode then check | ||||
889 | // incoming value. If incoming value is not from BB then this is | ||||
890 | // a complex condition (e.g. preheaders) we want to avoid here. | ||||
891 | if (UI->getParent() == DestBB) { | ||||
892 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) | ||||
893 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { | ||||
894 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); | ||||
895 | if (Insn && Insn->getParent() == BB && | ||||
896 | Insn->getParent() != UPN->getIncomingBlock(I)) | ||||
897 | return false; | ||||
898 | } | ||||
899 | } | ||||
900 | } | ||||
901 | } | ||||
902 | |||||
903 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB | ||||
904 | // and DestBB may have conflicting incoming values for the block. If so, we | ||||
905 | // can't merge the block. | ||||
906 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); | ||||
907 | if (!DestBBPN) return true; // no conflict. | ||||
908 | |||||
909 | // Collect the preds of BB. | ||||
910 | SmallPtrSet<const BasicBlock*, 16> BBPreds; | ||||
911 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { | ||||
912 | // It is faster to get preds from a PHI than with pred_iterator. | ||||
913 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) | ||||
914 | BBPreds.insert(BBPN->getIncomingBlock(i)); | ||||
915 | } else { | ||||
916 | BBPreds.insert(pred_begin(BB), pred_end(BB)); | ||||
917 | } | ||||
918 | |||||
919 | // Walk the preds of DestBB. | ||||
920 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { | ||||
921 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); | ||||
922 | if (BBPreds.count(Pred)) { // Common predecessor? | ||||
923 | for (const PHINode &PN : DestBB->phis()) { | ||||
924 | const Value *V1 = PN.getIncomingValueForBlock(Pred); | ||||
925 | const Value *V2 = PN.getIncomingValueForBlock(BB); | ||||
926 | |||||
927 | // If V2 is a phi node in BB, look up what the mapped value will be. | ||||
928 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) | ||||
929 | if (V2PN->getParent() == BB) | ||||
930 | V2 = V2PN->getIncomingValueForBlock(Pred); | ||||
931 | |||||
932 | // If there is a conflict, bail out. | ||||
933 | if (V1 != V2) return false; | ||||
934 | } | ||||
935 | } | ||||
936 | } | ||||
937 | |||||
938 | return true; | ||||
939 | } | ||||
940 | |||||
941 | /// Eliminate a basic block that has only phi's and an unconditional branch in | ||||
942 | /// it. | ||||
943 | void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) { | ||||
944 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); | ||||
945 | BasicBlock *DestBB = BI->getSuccessor(0); | ||||
946 | |||||
947 | LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB; } } while (false) | ||||
948 | << *BB << *DestBB)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB; } } while (false); | ||||
949 | |||||
950 | // If the destination block has a single pred, then this is a trivial edge, | ||||
951 | // just collapse it. | ||||
952 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { | ||||
953 | if (SinglePred != DestBB) { | ||||
954 | assert(SinglePred == BB &&(static_cast <bool> (SinglePred == BB && "Single predecessor not the same as predecessor" ) ? void (0) : __assert_fail ("SinglePred == BB && \"Single predecessor not the same as predecessor\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 955, __extension__ __PRETTY_FUNCTION__ )) | ||||
955 | "Single predecessor not the same as predecessor")(static_cast <bool> (SinglePred == BB && "Single predecessor not the same as predecessor" ) ? void (0) : __assert_fail ("SinglePred == BB && \"Single predecessor not the same as predecessor\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 955, __extension__ __PRETTY_FUNCTION__ )); | ||||
956 | // Merge DestBB into SinglePred/BB and delete it. | ||||
957 | MergeBlockIntoPredecessor(DestBB); | ||||
958 | // Note: BB(=SinglePred) will not be deleted on this path. | ||||
959 | // DestBB(=its single successor) is the one that was deleted. | ||||
960 | LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n"; } } while (false); | ||||
961 | return; | ||||
962 | } | ||||
963 | } | ||||
964 | |||||
965 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB | ||||
966 | // to handle the new incoming edges it is about to have. | ||||
967 | for (PHINode &PN : DestBB->phis()) { | ||||
968 | // Remove the incoming value for BB, and remember it. | ||||
969 | Value *InVal = PN.removeIncomingValue(BB, false); | ||||
970 | |||||
971 | // Two options: either the InVal is a phi node defined in BB or it is some | ||||
972 | // value that dominates BB. | ||||
973 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); | ||||
974 | if (InValPhi && InValPhi->getParent() == BB) { | ||||
975 | // Add all of the input values of the input PHI as inputs of this phi. | ||||
976 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) | ||||
977 | PN.addIncoming(InValPhi->getIncomingValue(i), | ||||
978 | InValPhi->getIncomingBlock(i)); | ||||
979 | } else { | ||||
980 | // Otherwise, add one instance of the dominating value for each edge that | ||||
981 | // we will be adding. | ||||
982 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { | ||||
983 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) | ||||
984 | PN.addIncoming(InVal, BBPN->getIncomingBlock(i)); | ||||
985 | } else { | ||||
986 | for (BasicBlock *Pred : predecessors(BB)) | ||||
987 | PN.addIncoming(InVal, Pred); | ||||
988 | } | ||||
989 | } | ||||
990 | } | ||||
991 | |||||
992 | // The PHIs are now updated, change everything that refers to BB to use | ||||
993 | // DestBB and remove BB. | ||||
994 | BB->replaceAllUsesWith(DestBB); | ||||
995 | BB->eraseFromParent(); | ||||
996 | ++NumBlocksElim; | ||||
997 | |||||
998 | LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"; } } while (false); | ||||
999 | } | ||||
1000 | |||||
1001 | // Computes a map of base pointer relocation instructions to corresponding | ||||
1002 | // derived pointer relocation instructions given a vector of all relocate calls | ||||
1003 | static void computeBaseDerivedRelocateMap( | ||||
1004 | const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls, | ||||
1005 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> | ||||
1006 | &RelocateInstMap) { | ||||
1007 | // Collect information in two maps: one primarily for locating the base object | ||||
1008 | // while filling the second map; the second map is the final structure holding | ||||
1009 | // a mapping between Base and corresponding Derived relocate calls | ||||
1010 | DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap; | ||||
1011 | for (auto *ThisRelocate : AllRelocateCalls) { | ||||
1012 | auto K = std::make_pair(ThisRelocate->getBasePtrIndex(), | ||||
1013 | ThisRelocate->getDerivedPtrIndex()); | ||||
1014 | RelocateIdxMap.insert(std::make_pair(K, ThisRelocate)); | ||||
1015 | } | ||||
1016 | for (auto &Item : RelocateIdxMap) { | ||||
1017 | std::pair<unsigned, unsigned> Key = Item.first; | ||||
1018 | if (Key.first == Key.second) | ||||
1019 | // Base relocation: nothing to insert | ||||
1020 | continue; | ||||
1021 | |||||
1022 | GCRelocateInst *I = Item.second; | ||||
1023 | auto BaseKey = std::make_pair(Key.first, Key.first); | ||||
1024 | |||||
1025 | // We're iterating over RelocateIdxMap so we cannot modify it. | ||||
1026 | auto MaybeBase = RelocateIdxMap.find(BaseKey); | ||||
1027 | if (MaybeBase == RelocateIdxMap.end()) | ||||
1028 | // TODO: We might want to insert a new base object relocate and gep off | ||||
1029 | // that, if there are enough derived object relocates. | ||||
1030 | continue; | ||||
1031 | |||||
1032 | RelocateInstMap[MaybeBase->second].push_back(I); | ||||
1033 | } | ||||
1034 | } | ||||
1035 | |||||
1036 | // Accepts a GEP and extracts the operands into a vector provided they're all | ||||
1037 | // small integer constants | ||||
1038 | static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, | ||||
1039 | SmallVectorImpl<Value *> &OffsetV) { | ||||
1040 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) { | ||||
1041 | // Only accept small constant integer operands | ||||
1042 | auto *Op = dyn_cast<ConstantInt>(GEP->getOperand(i)); | ||||
1043 | if (!Op || Op->getZExtValue() > 20) | ||||
1044 | return false; | ||||
1045 | } | ||||
1046 | |||||
1047 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) | ||||
1048 | OffsetV.push_back(GEP->getOperand(i)); | ||||
1049 | return true; | ||||
1050 | } | ||||
1051 | |||||
1052 | // Takes a RelocatedBase (base pointer relocation instruction) and Targets to | ||||
1053 | // replace, computes a replacement, and affects it. | ||||
1054 | static bool | ||||
1055 | simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, | ||||
1056 | const SmallVectorImpl<GCRelocateInst *> &Targets) { | ||||
1057 | bool MadeChange = false; | ||||
1058 | // We must ensure the relocation of derived pointer is defined after | ||||
1059 | // relocation of base pointer. If we find a relocation corresponding to base | ||||
1060 | // defined earlier than relocation of base then we move relocation of base | ||||
1061 | // right before found relocation. We consider only relocation in the same | ||||
1062 | // basic block as relocation of base. Relocations from other basic block will | ||||
1063 | // be skipped by optimization and we do not care about them. | ||||
1064 | for (auto R = RelocatedBase->getParent()->getFirstInsertionPt(); | ||||
1065 | &*R != RelocatedBase; ++R) | ||||
1066 | if (auto *RI = dyn_cast<GCRelocateInst>(R)) | ||||
1067 | if (RI->getStatepoint() == RelocatedBase->getStatepoint()) | ||||
1068 | if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) { | ||||
1069 | RelocatedBase->moveBefore(RI); | ||||
1070 | break; | ||||
1071 | } | ||||
1072 | |||||
1073 | for (GCRelocateInst *ToReplace : Targets) { | ||||
1074 | assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&(static_cast <bool> (ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && "Not relocating a derived object of the original base object" ) ? void (0) : __assert_fail ("ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && \"Not relocating a derived object of the original base object\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1075, __extension__ __PRETTY_FUNCTION__ )) | ||||
1075 | "Not relocating a derived object of the original base object")(static_cast <bool> (ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && "Not relocating a derived object of the original base object" ) ? void (0) : __assert_fail ("ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && \"Not relocating a derived object of the original base object\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1075, __extension__ __PRETTY_FUNCTION__ )); | ||||
1076 | if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) { | ||||
1077 | // A duplicate relocate call. TODO: coalesce duplicates. | ||||
1078 | continue; | ||||
1079 | } | ||||
1080 | |||||
1081 | if (RelocatedBase->getParent() != ToReplace->getParent()) { | ||||
1082 | // Base and derived relocates are in different basic blocks. | ||||
1083 | // In this case transform is only valid when base dominates derived | ||||
1084 | // relocate. However it would be too expensive to check dominance | ||||
1085 | // for each such relocate, so we skip the whole transformation. | ||||
1086 | continue; | ||||
1087 | } | ||||
1088 | |||||
1089 | Value *Base = ToReplace->getBasePtr(); | ||||
1090 | auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr()); | ||||
1091 | if (!Derived || Derived->getPointerOperand() != Base) | ||||
1092 | continue; | ||||
1093 | |||||
1094 | SmallVector<Value *, 2> OffsetV; | ||||
1095 | if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV)) | ||||
1096 | continue; | ||||
1097 | |||||
1098 | // Create a Builder and replace the target callsite with a gep | ||||
1099 | assert(RelocatedBase->getNextNode() &&(static_cast <bool> (RelocatedBase->getNextNode() && "Should always have one since it's not a terminator") ? void (0) : __assert_fail ("RelocatedBase->getNextNode() && \"Should always have one since it's not a terminator\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1100, __extension__ __PRETTY_FUNCTION__ )) | ||||
1100 | "Should always have one since it's not a terminator")(static_cast <bool> (RelocatedBase->getNextNode() && "Should always have one since it's not a terminator") ? void (0) : __assert_fail ("RelocatedBase->getNextNode() && \"Should always have one since it's not a terminator\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1100, __extension__ __PRETTY_FUNCTION__ )); | ||||
1101 | |||||
1102 | // Insert after RelocatedBase | ||||
1103 | IRBuilder<> Builder(RelocatedBase->getNextNode()); | ||||
1104 | Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc()); | ||||
1105 | |||||
1106 | // If gc_relocate does not match the actual type, cast it to the right type. | ||||
1107 | // In theory, there must be a bitcast after gc_relocate if the type does not | ||||
1108 | // match, and we should reuse it to get the derived pointer. But it could be | ||||
1109 | // cases like this: | ||||
1110 | // bb1: | ||||
1111 | // ... | ||||
1112 | // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) | ||||
1113 | // br label %merge | ||||
1114 | // | ||||
1115 | // bb2: | ||||
1116 | // ... | ||||
1117 | // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) | ||||
1118 | // br label %merge | ||||
1119 | // | ||||
1120 | // merge: | ||||
1121 | // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ] | ||||
1122 | // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)* | ||||
1123 | // | ||||
1124 | // In this case, we can not find the bitcast any more. So we insert a new bitcast | ||||
1125 | // no matter there is already one or not. In this way, we can handle all cases, and | ||||
1126 | // the extra bitcast should be optimized away in later passes. | ||||
1127 | Value *ActualRelocatedBase = RelocatedBase; | ||||
1128 | if (RelocatedBase->getType() != Base->getType()) { | ||||
1129 | ActualRelocatedBase = | ||||
1130 | Builder.CreateBitCast(RelocatedBase, Base->getType()); | ||||
1131 | } | ||||
1132 | Value *Replacement = Builder.CreateGEP( | ||||
1133 | Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV)); | ||||
1134 | Replacement->takeName(ToReplace); | ||||
1135 | // If the newly generated derived pointer's type does not match the original derived | ||||
1136 | // pointer's type, cast the new derived pointer to match it. Same reasoning as above. | ||||
1137 | Value *ActualReplacement = Replacement; | ||||
1138 | if (Replacement->getType() != ToReplace->getType()) { | ||||
1139 | ActualReplacement = | ||||
1140 | Builder.CreateBitCast(Replacement, ToReplace->getType()); | ||||
1141 | } | ||||
1142 | ToReplace->replaceAllUsesWith(ActualReplacement); | ||||
1143 | ToReplace->eraseFromParent(); | ||||
1144 | |||||
1145 | MadeChange = true; | ||||
1146 | } | ||||
1147 | return MadeChange; | ||||
1148 | } | ||||
1149 | |||||
1150 | // Turns this: | ||||
1151 | // | ||||
1152 | // %base = ... | ||||
1153 | // %ptr = gep %base + 15 | ||||
1154 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) | ||||
1155 | // %base' = relocate(%tok, i32 4, i32 4) | ||||
1156 | // %ptr' = relocate(%tok, i32 4, i32 5) | ||||
1157 | // %val = load %ptr' | ||||
1158 | // | ||||
1159 | // into this: | ||||
1160 | // | ||||
1161 | // %base = ... | ||||
1162 | // %ptr = gep %base + 15 | ||||
1163 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) | ||||
1164 | // %base' = gc.relocate(%tok, i32 4, i32 4) | ||||
1165 | // %ptr' = gep %base' + 15 | ||||
1166 | // %val = load %ptr' | ||||
1167 | bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) { | ||||
1168 | bool MadeChange = false; | ||||
1169 | SmallVector<GCRelocateInst *, 2> AllRelocateCalls; | ||||
1170 | for (auto *U : I.users()) | ||||
1171 | if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U)) | ||||
1172 | // Collect all the relocate calls associated with a statepoint | ||||
1173 | AllRelocateCalls.push_back(Relocate); | ||||
1174 | |||||
1175 | // We need at least one base pointer relocation + one derived pointer | ||||
1176 | // relocation to mangle | ||||
1177 | if (AllRelocateCalls.size() < 2) | ||||
1178 | return false; | ||||
1179 | |||||
1180 | // RelocateInstMap is a mapping from the base relocate instruction to the | ||||
1181 | // corresponding derived relocate instructions | ||||
1182 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap; | ||||
1183 | computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap); | ||||
1184 | if (RelocateInstMap.empty()) | ||||
1185 | return false; | ||||
1186 | |||||
1187 | for (auto &Item : RelocateInstMap) | ||||
1188 | // Item.first is the RelocatedBase to offset against | ||||
1189 | // Item.second is the vector of Targets to replace | ||||
1190 | MadeChange = simplifyRelocatesOffABase(Item.first, Item.second); | ||||
1191 | return MadeChange; | ||||
1192 | } | ||||
1193 | |||||
1194 | /// Sink the specified cast instruction into its user blocks. | ||||
1195 | static bool SinkCast(CastInst *CI) { | ||||
1196 | BasicBlock *DefBB = CI->getParent(); | ||||
1197 | |||||
1198 | /// InsertedCasts - Only insert a cast in each block once. | ||||
1199 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; | ||||
1200 | |||||
1201 | bool MadeChange = false; | ||||
1202 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); | ||||
1203 | UI != E; ) { | ||||
1204 | Use &TheUse = UI.getUse(); | ||||
1205 | Instruction *User = cast<Instruction>(*UI); | ||||
1206 | |||||
1207 | // Figure out which BB this cast is used in. For PHI's this is the | ||||
1208 | // appropriate predecessor block. | ||||
1209 | BasicBlock *UserBB = User->getParent(); | ||||
1210 | if (PHINode *PN = dyn_cast<PHINode>(User)) { | ||||
1211 | UserBB = PN->getIncomingBlock(TheUse); | ||||
1212 | } | ||||
1213 | |||||
1214 | // Preincrement use iterator so we don't invalidate it. | ||||
1215 | ++UI; | ||||
1216 | |||||
1217 | // The first insertion point of a block containing an EH pad is after the | ||||
1218 | // pad. If the pad is the user, we cannot sink the cast past the pad. | ||||
1219 | if (User->isEHPad()) | ||||
1220 | continue; | ||||
1221 | |||||
1222 | // If the block selected to receive the cast is an EH pad that does not | ||||
1223 | // allow non-PHI instructions before the terminator, we can't sink the | ||||
1224 | // cast. | ||||
1225 | if (UserBB->getTerminator()->isEHPad()) | ||||
1226 | continue; | ||||
1227 | |||||
1228 | // If this user is in the same block as the cast, don't change the cast. | ||||
1229 | if (UserBB == DefBB) continue; | ||||
1230 | |||||
1231 | // If we have already inserted a cast into this block, use it. | ||||
1232 | CastInst *&InsertedCast = InsertedCasts[UserBB]; | ||||
1233 | |||||
1234 | if (!InsertedCast) { | ||||
1235 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); | ||||
1236 | assert(InsertPt != UserBB->end())(static_cast <bool> (InsertPt != UserBB->end()) ? void (0) : __assert_fail ("InsertPt != UserBB->end()", "llvm/lib/CodeGen/CodeGenPrepare.cpp" , 1236, __extension__ __PRETTY_FUNCTION__)); | ||||
1237 | InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0), | ||||
1238 | CI->getType(), "", &*InsertPt); | ||||
1239 | InsertedCast->setDebugLoc(CI->getDebugLoc()); | ||||
1240 | } | ||||
1241 | |||||
1242 | // Replace a use of the cast with a use of the new cast. | ||||
1243 | TheUse = InsertedCast; | ||||
1244 | MadeChange = true; | ||||
1245 | ++NumCastUses; | ||||
1246 | } | ||||
1247 | |||||
1248 | // If we removed all uses, nuke the cast. | ||||
1249 | if (CI->use_empty()) { | ||||
1250 | salvageDebugInfo(*CI); | ||||
1251 | CI->eraseFromParent(); | ||||
1252 | MadeChange = true; | ||||
1253 | } | ||||
1254 | |||||
1255 | return MadeChange; | ||||
1256 | } | ||||
1257 | |||||
1258 | /// If the specified cast instruction is a noop copy (e.g. it's casting from | ||||
1259 | /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to | ||||
1260 | /// reduce the number of virtual registers that must be created and coalesced. | ||||
1261 | /// | ||||
1262 | /// Return true if any changes are made. | ||||
1263 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, | ||||
1264 | const DataLayout &DL) { | ||||
1265 | // Sink only "cheap" (or nop) address-space casts. This is a weaker condition | ||||
1266 | // than sinking only nop casts, but is helpful on some platforms. | ||||
1267 | if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) { | ||||
1268 | if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(), | ||||
1269 | ASC->getDestAddressSpace())) | ||||
1270 | return false; | ||||
1271 | } | ||||
1272 | |||||
1273 | // If this is a noop copy, | ||||
1274 | EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType()); | ||||
1275 | EVT DstVT = TLI.getValueType(DL, CI->getType()); | ||||
1276 | |||||
1277 | // This is an fp<->int conversion? | ||||
1278 | if (SrcVT.isInteger() != DstVT.isInteger()) | ||||
1279 | return false; | ||||
1280 | |||||
1281 | // If this is an extension, it will be a zero or sign extension, which | ||||
1282 | // isn't a noop. | ||||
1283 | if (SrcVT.bitsLT(DstVT)) return false; | ||||
1284 | |||||
1285 | // If these values will be promoted, find out what they will be promoted | ||||
1286 | // to. This helps us consider truncates on PPC as noop copies when they | ||||
1287 | // are. | ||||
1288 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == | ||||
1289 | TargetLowering::TypePromoteInteger) | ||||
1290 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); | ||||
1291 | if (TLI.getTypeAction(CI->getContext(), DstVT) == | ||||
1292 | TargetLowering::TypePromoteInteger) | ||||
1293 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); | ||||
1294 | |||||
1295 | // If, after promotion, these are the same types, this is a noop copy. | ||||
1296 | if (SrcVT != DstVT) | ||||
1297 | return false; | ||||
1298 | |||||
1299 | return SinkCast(CI); | ||||
1300 | } | ||||
1301 | |||||
1302 | // Match a simple increment by constant operation. Note that if a sub is | ||||
1303 | // matched, the step is negated (as if the step had been canonicalized to | ||||
1304 | // an add, even though we leave the instruction alone.) | ||||
1305 | bool matchIncrement(const Instruction* IVInc, Instruction *&LHS, | ||||
1306 | Constant *&Step) { | ||||
1307 | if (match(IVInc, m_Add(m_Instruction(LHS), m_Constant(Step))) || | ||||
1308 | match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::uadd_with_overflow>( | ||||
1309 | m_Instruction(LHS), m_Constant(Step))))) | ||||
1310 | return true; | ||||
1311 | if (match(IVInc, m_Sub(m_Instruction(LHS), m_Constant(Step))) || | ||||
1312 | match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>( | ||||
1313 | m_Instruction(LHS), m_Constant(Step))))) { | ||||
1314 | Step = ConstantExpr::getNeg(Step); | ||||
1315 | return true; | ||||
1316 | } | ||||
1317 | return false; | ||||
1318 | } | ||||
1319 | |||||
1320 | /// If given \p PN is an inductive variable with value IVInc coming from the | ||||
1321 | /// backedge, and on each iteration it gets increased by Step, return pair | ||||
1322 | /// <IVInc, Step>. Otherwise, return None. | ||||
1323 | static Optional<std::pair<Instruction *, Constant *> > | ||||
1324 | getIVIncrement(const PHINode *PN, const LoopInfo *LI) { | ||||
1325 | const Loop *L = LI->getLoopFor(PN->getParent()); | ||||
1326 | if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch()) | ||||
1327 | return None; | ||||
1328 | auto *IVInc = | ||||
1329 | dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch())); | ||||
1330 | if (!IVInc || LI->getLoopFor(IVInc->getParent()) != L) | ||||
1331 | return None; | ||||
1332 | Instruction *LHS = nullptr; | ||||
1333 | Constant *Step = nullptr; | ||||
1334 | if (matchIncrement(IVInc, LHS, Step) && LHS == PN) | ||||
1335 | return std::make_pair(IVInc, Step); | ||||
1336 | return None; | ||||
1337 | } | ||||
1338 | |||||
1339 | static bool isIVIncrement(const Value *V, const LoopInfo *LI) { | ||||
1340 | auto *I = dyn_cast<Instruction>(V); | ||||
1341 | if (!I) | ||||
1342 | return false; | ||||
1343 | Instruction *LHS = nullptr; | ||||
1344 | Constant *Step = nullptr; | ||||
1345 | if (!matchIncrement(I, LHS, Step)) | ||||
1346 | return false; | ||||
1347 | if (auto *PN = dyn_cast<PHINode>(LHS)) | ||||
1348 | if (auto IVInc = getIVIncrement(PN, LI)) | ||||
1349 | return IVInc->first == I; | ||||
1350 | return false; | ||||
1351 | } | ||||
1352 | |||||
1353 | bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO, | ||||
1354 | Value *Arg0, Value *Arg1, | ||||
1355 | CmpInst *Cmp, | ||||
1356 | Intrinsic::ID IID) { | ||||
1357 | auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) { | ||||
1358 | if (!isIVIncrement(BO, LI)) | ||||
1359 | return false; | ||||
1360 | const Loop *L = LI->getLoopFor(BO->getParent()); | ||||
1361 | assert(L && "L should not be null after isIVIncrement()")(static_cast <bool> (L && "L should not be null after isIVIncrement()" ) ? void (0) : __assert_fail ("L && \"L should not be null after isIVIncrement()\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1361, __extension__ __PRETTY_FUNCTION__ )); | ||||
1362 | // Do not risk on moving increment into a child loop. | ||||
1363 | if (LI->getLoopFor(Cmp->getParent()) != L) | ||||
1364 | return false; | ||||
1365 | |||||
1366 | // Finally, we need to ensure that the insert point will dominate all | ||||
1367 | // existing uses of the increment. | ||||
1368 | |||||
1369 | auto &DT = getDT(*BO->getParent()->getParent()); | ||||
1370 | if (DT.dominates(Cmp->getParent(), BO->getParent())) | ||||
1371 | // If we're moving up the dom tree, all uses are trivially dominated. | ||||
1372 | // (This is the common case for code produced by LSR.) | ||||
1373 | return true; | ||||
1374 | |||||
1375 | // Otherwise, special case the single use in the phi recurrence. | ||||
1376 | return BO->hasOneUse() && DT.dominates(Cmp->getParent(), L->getLoopLatch()); | ||||
1377 | }; | ||||
1378 | if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) { | ||||
1379 | // We used to use a dominator tree here to allow multi-block optimization. | ||||
1380 | // But that was problematic because: | ||||
1381 | // 1. It could cause a perf regression by hoisting the math op into the | ||||
1382 | // critical path. | ||||
1383 | // 2. It could cause a perf regression by creating a value that was live | ||||
1384 | // across multiple blocks and increasing register pressure. | ||||
1385 | // 3. Use of a dominator tree could cause large compile-time regression. | ||||
1386 | // This is because we recompute the DT on every change in the main CGP | ||||
1387 | // run-loop. The recomputing is probably unnecessary in many cases, so if | ||||
1388 | // that was fixed, using a DT here would be ok. | ||||
1389 | // | ||||
1390 | // There is one important particular case we still want to handle: if BO is | ||||
1391 | // the IV increment. Important properties that make it profitable: | ||||
1392 | // - We can speculate IV increment anywhere in the loop (as long as the | ||||
1393 | // indvar Phi is its only user); | ||||
1394 | // - Upon computing Cmp, we effectively compute something equivalent to the | ||||
1395 | // IV increment (despite it loops differently in the IR). So moving it up | ||||
1396 | // to the cmp point does not really increase register pressure. | ||||
1397 | return false; | ||||
1398 | } | ||||
1399 | |||||
1400 | // We allow matching the canonical IR (add X, C) back to (usubo X, -C). | ||||
1401 | if (BO->getOpcode() == Instruction::Add && | ||||
1402 | IID == Intrinsic::usub_with_overflow) { | ||||
1403 | assert(isa<Constant>(Arg1) && "Unexpected input for usubo")(static_cast <bool> (isa<Constant>(Arg1) && "Unexpected input for usubo") ? void (0) : __assert_fail ("isa<Constant>(Arg1) && \"Unexpected input for usubo\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1403, __extension__ __PRETTY_FUNCTION__ )); | ||||
1404 | Arg1 = ConstantExpr::getNeg(cast<Constant>(Arg1)); | ||||
1405 | } | ||||
1406 | |||||
1407 | // Insert at the first instruction of the pair. | ||||
1408 | Instruction *InsertPt = nullptr; | ||||
1409 | for (Instruction &Iter : *Cmp->getParent()) { | ||||
1410 | // If BO is an XOR, it is not guaranteed that it comes after both inputs to | ||||
1411 | // the overflow intrinsic are defined. | ||||
1412 | if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) { | ||||
1413 | InsertPt = &Iter; | ||||
1414 | break; | ||||
1415 | } | ||||
1416 | } | ||||
1417 | assert(InsertPt != nullptr && "Parent block did not contain cmp or binop")(static_cast <bool> (InsertPt != nullptr && "Parent block did not contain cmp or binop" ) ? void (0) : __assert_fail ("InsertPt != nullptr && \"Parent block did not contain cmp or binop\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1417, __extension__ __PRETTY_FUNCTION__ )); | ||||
1418 | |||||
1419 | IRBuilder<> Builder(InsertPt); | ||||
1420 | Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1); | ||||
1421 | if (BO->getOpcode() != Instruction::Xor) { | ||||
1422 | Value *Math = Builder.CreateExtractValue(MathOV, 0, "math"); | ||||
1423 | BO->replaceAllUsesWith(Math); | ||||
1424 | } else | ||||
1425 | assert(BO->hasOneUse() &&(static_cast <bool> (BO->hasOneUse() && "Patterns with XOr should use the BO only in the compare" ) ? void (0) : __assert_fail ("BO->hasOneUse() && \"Patterns with XOr should use the BO only in the compare\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1426, __extension__ __PRETTY_FUNCTION__ )) | ||||
1426 | "Patterns with XOr should use the BO only in the compare")(static_cast <bool> (BO->hasOneUse() && "Patterns with XOr should use the BO only in the compare" ) ? void (0) : __assert_fail ("BO->hasOneUse() && \"Patterns with XOr should use the BO only in the compare\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1426, __extension__ __PRETTY_FUNCTION__ )); | ||||
1427 | Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov"); | ||||
1428 | Cmp->replaceAllUsesWith(OV); | ||||
1429 | Cmp->eraseFromParent(); | ||||
1430 | BO->eraseFromParent(); | ||||
1431 | return true; | ||||
1432 | } | ||||
1433 | |||||
1434 | /// Match special-case patterns that check for unsigned add overflow. | ||||
1435 | static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp, | ||||
1436 | BinaryOperator *&Add) { | ||||
1437 | // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val) | ||||
1438 | // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero) | ||||
1439 | Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1); | ||||
1440 | |||||
1441 | // We are not expecting non-canonical/degenerate code. Just bail out. | ||||
1442 | if (isa<Constant>(A)) | ||||
1443 | return false; | ||||
1444 | |||||
1445 | ICmpInst::Predicate Pred = Cmp->getPredicate(); | ||||
1446 | if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes())) | ||||
1447 | B = ConstantInt::get(B->getType(), 1); | ||||
1448 | else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) | ||||
1449 | B = ConstantInt::get(B->getType(), -1); | ||||
1450 | else | ||||
1451 | return false; | ||||
1452 | |||||
1453 | // Check the users of the variable operand of the compare looking for an add | ||||
1454 | // with the adjusted constant. | ||||
1455 | for (User *U : A->users()) { | ||||
1456 | if (match(U, m_Add(m_Specific(A), m_Specific(B)))) { | ||||
1457 | Add = cast<BinaryOperator>(U); | ||||
1458 | return true; | ||||
1459 | } | ||||
1460 | } | ||||
1461 | return false; | ||||
1462 | } | ||||
1463 | |||||
1464 | /// Try to combine the compare into a call to the llvm.uadd.with.overflow | ||||
1465 | /// intrinsic. Return true if any changes were made. | ||||
1466 | bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp, | ||||
1467 | bool &ModifiedDT) { | ||||
1468 | Value *A, *B; | ||||
1469 | BinaryOperator *Add; | ||||
1470 | if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) { | ||||
1471 | if (!matchUAddWithOverflowConstantEdgeCases(Cmp, Add)) | ||||
1472 | return false; | ||||
1473 | // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases. | ||||
1474 | A = Add->getOperand(0); | ||||
1475 | B = Add->getOperand(1); | ||||
1476 | } | ||||
1477 | |||||
1478 | if (!TLI->shouldFormOverflowOp(ISD::UADDO, | ||||
1479 | TLI->getValueType(*DL, Add->getType()), | ||||
1480 | Add->hasNUsesOrMore(2))) | ||||
1481 | return false; | ||||
1482 | |||||
1483 | // We don't want to move around uses of condition values this late, so we | ||||
1484 | // check if it is legal to create the call to the intrinsic in the basic | ||||
1485 | // block containing the icmp. | ||||
1486 | if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse()) | ||||
1487 | return false; | ||||
1488 | |||||
1489 | if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp, | ||||
1490 | Intrinsic::uadd_with_overflow)) | ||||
1491 | return false; | ||||
1492 | |||||
1493 | // Reset callers - do not crash by iterating over a dead instruction. | ||||
1494 | ModifiedDT = true; | ||||
1495 | return true; | ||||
1496 | } | ||||
1497 | |||||
1498 | bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp, | ||||
1499 | bool &ModifiedDT) { | ||||
1500 | // We are not expecting non-canonical/degenerate code. Just bail out. | ||||
1501 | Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1); | ||||
1502 | if (isa<Constant>(A) && isa<Constant>(B)) | ||||
1503 | return false; | ||||
1504 | |||||
1505 | // Convert (A u> B) to (A u< B) to simplify pattern matching. | ||||
1506 | ICmpInst::Predicate Pred = Cmp->getPredicate(); | ||||
1507 | if (Pred == ICmpInst::ICMP_UGT) { | ||||
1508 | std::swap(A, B); | ||||
1509 | Pred = ICmpInst::ICMP_ULT; | ||||
1510 | } | ||||
1511 | // Convert special-case: (A == 0) is the same as (A u< 1). | ||||
1512 | if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) { | ||||
1513 | B = ConstantInt::get(B->getType(), 1); | ||||
1514 | Pred = ICmpInst::ICMP_ULT; | ||||
1515 | } | ||||
1516 | // Convert special-case: (A != 0) is the same as (0 u< A). | ||||
1517 | if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) { | ||||
1518 | std::swap(A, B); | ||||
1519 | Pred = ICmpInst::ICMP_ULT; | ||||
1520 | } | ||||
1521 | if (Pred != ICmpInst::ICMP_ULT) | ||||
1522 | return false; | ||||
1523 | |||||
1524 | // Walk the users of a variable operand of a compare looking for a subtract or | ||||
1525 | // add with that same operand. Also match the 2nd operand of the compare to | ||||
1526 | // the add/sub, but that may be a negated constant operand of an add. | ||||
1527 | Value *CmpVariableOperand = isa<Constant>(A) ? B : A; | ||||
1528 | BinaryOperator *Sub = nullptr; | ||||
1529 | for (User *U : CmpVariableOperand->users()) { | ||||
1530 | // A - B, A u< B --> usubo(A, B) | ||||
1531 | if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) { | ||||
1532 | Sub = cast<BinaryOperator>(U); | ||||
1533 | break; | ||||
1534 | } | ||||
1535 | |||||
1536 | // A + (-C), A u< C (canonicalized form of (sub A, C)) | ||||
1537 | const APInt *CmpC, *AddC; | ||||
1538 | if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) && | ||||
1539 | match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) { | ||||
1540 | Sub = cast<BinaryOperator>(U); | ||||
1541 | break; | ||||
1542 | } | ||||
1543 | } | ||||
1544 | if (!Sub) | ||||
1545 | return false; | ||||
1546 | |||||
1547 | if (!TLI->shouldFormOverflowOp(ISD::USUBO, | ||||
1548 | TLI->getValueType(*DL, Sub->getType()), | ||||
1549 | Sub->hasNUsesOrMore(2))) | ||||
1550 | return false; | ||||
1551 | |||||
1552 | if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1), | ||||
1553 | Cmp, Intrinsic::usub_with_overflow)) | ||||
1554 | return false; | ||||
1555 | |||||
1556 | // Reset callers - do not crash by iterating over a dead instruction. | ||||
1557 | ModifiedDT = true; | ||||
1558 | return true; | ||||
1559 | } | ||||
1560 | |||||
1561 | /// Sink the given CmpInst into user blocks to reduce the number of virtual | ||||
1562 | /// registers that must be created and coalesced. This is a clear win except on | ||||
1563 | /// targets with multiple condition code registers (PowerPC), where it might | ||||
1564 | /// lose; some adjustment may be wanted there. | ||||
1565 | /// | ||||
1566 | /// Return true if any changes are made. | ||||
1567 | static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) { | ||||
1568 | if (TLI.hasMultipleConditionRegisters()) | ||||
1569 | return false; | ||||
1570 | |||||
1571 | // Avoid sinking soft-FP comparisons, since this can move them into a loop. | ||||
1572 | if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp)) | ||||
1573 | return false; | ||||
1574 | |||||
1575 | // Only insert a cmp in each block once. | ||||
1576 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; | ||||
1577 | |||||
1578 | bool MadeChange = false; | ||||
1579 | for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end(); | ||||
1580 | UI != E; ) { | ||||
1581 | Use &TheUse = UI.getUse(); | ||||
1582 | Instruction *User = cast<Instruction>(*UI); | ||||
1583 | |||||
1584 | // Preincrement use iterator so we don't invalidate it. | ||||
1585 | ++UI; | ||||
1586 | |||||
1587 | // Don't bother for PHI nodes. | ||||
1588 | if (isa<PHINode>(User)) | ||||
1589 | continue; | ||||
1590 | |||||
1591 | // Figure out which BB this cmp is used in. | ||||
1592 | BasicBlock *UserBB = User->getParent(); | ||||
1593 | BasicBlock *DefBB = Cmp->getParent(); | ||||
1594 | |||||
1595 | // If this user is in the same block as the cmp, don't change the cmp. | ||||
1596 | if (UserBB == DefBB) continue; | ||||
1597 | |||||
1598 | // If we have already inserted a cmp into this block, use it. | ||||
1599 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; | ||||
1600 | |||||
1601 | if (!InsertedCmp) { | ||||
1602 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); | ||||
1603 | assert(InsertPt != UserBB->end())(static_cast <bool> (InsertPt != UserBB->end()) ? void (0) : __assert_fail ("InsertPt != UserBB->end()", "llvm/lib/CodeGen/CodeGenPrepare.cpp" , 1603, __extension__ __PRETTY_FUNCTION__)); | ||||
1604 | InsertedCmp = | ||||
1605 | CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), | ||||
1606 | Cmp->getOperand(0), Cmp->getOperand(1), "", | ||||
1607 | &*InsertPt); | ||||
1608 | // Propagate the debug info. | ||||
1609 | InsertedCmp->setDebugLoc(Cmp->getDebugLoc()); | ||||
1610 | } | ||||
1611 | |||||
1612 | // Replace a use of the cmp with a use of the new cmp. | ||||
1613 | TheUse = InsertedCmp; | ||||
1614 | MadeChange = true; | ||||
1615 | ++NumCmpUses; | ||||
1616 | } | ||||
1617 | |||||
1618 | // If we removed all uses, nuke the cmp. | ||||
1619 | if (Cmp->use_empty()) { | ||||
1620 | Cmp->eraseFromParent(); | ||||
1621 | MadeChange = true; | ||||
1622 | } | ||||
1623 | |||||
1624 | return MadeChange; | ||||
1625 | } | ||||
1626 | |||||
1627 | /// For pattern like: | ||||
1628 | /// | ||||
1629 | /// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB) | ||||
1630 | /// ... | ||||
1631 | /// DomBB: | ||||
1632 | /// ... | ||||
1633 | /// br DomCond, TrueBB, CmpBB | ||||
1634 | /// CmpBB: (with DomBB being the single predecessor) | ||||
1635 | /// ... | ||||
1636 | /// Cmp = icmp eq CmpOp0, CmpOp1 | ||||
1637 | /// ... | ||||
1638 | /// | ||||
1639 | /// It would use two comparison on targets that lowering of icmp sgt/slt is | ||||
1640 | /// different from lowering of icmp eq (PowerPC). This function try to convert | ||||
1641 | /// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'. | ||||
1642 | /// After that, DomCond and Cmp can use the same comparison so reduce one | ||||
1643 | /// comparison. | ||||
1644 | /// | ||||
1645 | /// Return true if any changes are made. | ||||
1646 | static bool foldICmpWithDominatingICmp(CmpInst *Cmp, | ||||
1647 | const TargetLowering &TLI) { | ||||
1648 | if (!EnableICMP_EQToICMP_ST && TLI.isEqualityCmpFoldedWithSignedCmp()) | ||||
1649 | return false; | ||||
1650 | |||||
1651 | ICmpInst::Predicate Pred = Cmp->getPredicate(); | ||||
1652 | if (Pred != ICmpInst::ICMP_EQ) | ||||
1653 | return false; | ||||
1654 | |||||
1655 | // If icmp eq has users other than BranchInst and SelectInst, converting it to | ||||
1656 | // icmp slt/sgt would introduce more redundant LLVM IR. | ||||
1657 | for (User *U : Cmp->users()) { | ||||
1658 | if (isa<BranchInst>(U)) | ||||
1659 | continue; | ||||
1660 | if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp) | ||||
1661 | continue; | ||||
1662 | return false; | ||||
1663 | } | ||||
1664 | |||||
1665 | // This is a cheap/incomplete check for dominance - just match a single | ||||
1666 | // predecessor with a conditional branch. | ||||
1667 | BasicBlock *CmpBB = Cmp->getParent(); | ||||
1668 | BasicBlock *DomBB = CmpBB->getSinglePredecessor(); | ||||
1669 | if (!DomBB) | ||||
1670 | return false; | ||||
1671 | |||||
1672 | // We want to ensure that the only way control gets to the comparison of | ||||
1673 | // interest is that a less/greater than comparison on the same operands is | ||||
1674 | // false. | ||||
1675 | Value *DomCond; | ||||
1676 | BasicBlock *TrueBB, *FalseBB; | ||||
1677 | if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB))) | ||||
1678 | return false; | ||||
1679 | if (CmpBB != FalseBB) | ||||
1680 | return false; | ||||
1681 | |||||
1682 | Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1); | ||||
1683 | ICmpInst::Predicate DomPred; | ||||
1684 | if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1)))) | ||||
1685 | return false; | ||||
1686 | if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT) | ||||
1687 | return false; | ||||
1688 | |||||
1689 | // Convert the equality comparison to the opposite of the dominating | ||||
1690 | // comparison and swap the direction for all branch/select users. | ||||
1691 | // We have conceptually converted: | ||||
1692 | // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>; | ||||
1693 | // to | ||||
1694 | // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>; | ||||
1695 | // And similarly for branches. | ||||
1696 | for (User *U : Cmp->users()) { | ||||
1697 | if (auto *BI = dyn_cast<BranchInst>(U)) { | ||||
1698 | assert(BI->isConditional() && "Must be conditional")(static_cast <bool> (BI->isConditional() && "Must be conditional" ) ? void (0) : __assert_fail ("BI->isConditional() && \"Must be conditional\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1698, __extension__ __PRETTY_FUNCTION__ )); | ||||
1699 | BI->swapSuccessors(); | ||||
1700 | continue; | ||||
1701 | } | ||||
1702 | if (auto *SI = dyn_cast<SelectInst>(U)) { | ||||
1703 | // Swap operands | ||||
1704 | SI->swapValues(); | ||||
1705 | SI->swapProfMetadata(); | ||||
1706 | continue; | ||||
1707 | } | ||||
1708 | llvm_unreachable("Must be a branch or a select")::llvm::llvm_unreachable_internal("Must be a branch or a select" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1708); | ||||
1709 | } | ||||
1710 | Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred)); | ||||
1711 | return true; | ||||
1712 | } | ||||
1713 | |||||
1714 | bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, bool &ModifiedDT) { | ||||
1715 | if (sinkCmpExpression(Cmp, *TLI)) | ||||
1716 | return true; | ||||
1717 | |||||
1718 | if (combineToUAddWithOverflow(Cmp, ModifiedDT)) | ||||
1719 | return true; | ||||
1720 | |||||
1721 | if (combineToUSubWithOverflow(Cmp, ModifiedDT)) | ||||
1722 | return true; | ||||
1723 | |||||
1724 | if (foldICmpWithDominatingICmp(Cmp, *TLI)) | ||||
1725 | return true; | ||||
1726 | |||||
1727 | return false; | ||||
1728 | } | ||||
1729 | |||||
1730 | /// Duplicate and sink the given 'and' instruction into user blocks where it is | ||||
1731 | /// used in a compare to allow isel to generate better code for targets where | ||||
1732 | /// this operation can be combined. | ||||
1733 | /// | ||||
1734 | /// Return true if any changes are made. | ||||
1735 | static bool sinkAndCmp0Expression(Instruction *AndI, | ||||
1736 | const TargetLowering &TLI, | ||||
1737 | SetOfInstrs &InsertedInsts) { | ||||
1738 | // Double-check that we're not trying to optimize an instruction that was | ||||
1739 | // already optimized by some other part of this pass. | ||||
1740 | assert(!InsertedInsts.count(AndI) &&(static_cast <bool> (!InsertedInsts.count(AndI) && "Attempting to optimize already optimized and instruction") ? void (0) : __assert_fail ("!InsertedInsts.count(AndI) && \"Attempting to optimize already optimized and instruction\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1741, __extension__ __PRETTY_FUNCTION__ )) | ||||
1741 | "Attempting to optimize already optimized and instruction")(static_cast <bool> (!InsertedInsts.count(AndI) && "Attempting to optimize already optimized and instruction") ? void (0) : __assert_fail ("!InsertedInsts.count(AndI) && \"Attempting to optimize already optimized and instruction\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1741, __extension__ __PRETTY_FUNCTION__ )); | ||||
1742 | (void) InsertedInsts; | ||||
1743 | |||||
1744 | // Nothing to do for single use in same basic block. | ||||
1745 | if (AndI->hasOneUse() && | ||||
1746 | AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent()) | ||||
1747 | return false; | ||||
1748 | |||||
1749 | // Try to avoid cases where sinking/duplicating is likely to increase register | ||||
1750 | // pressure. | ||||
1751 | if (!isa<ConstantInt>(AndI->getOperand(0)) && | ||||
1752 | !isa<ConstantInt>(AndI->getOperand(1)) && | ||||
1753 | AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse()) | ||||
1754 | return false; | ||||
1755 | |||||
1756 | for (auto *U : AndI->users()) { | ||||
1757 | Instruction *User = cast<Instruction>(U); | ||||
1758 | |||||
1759 | // Only sink 'and' feeding icmp with 0. | ||||
1760 | if (!isa<ICmpInst>(User)) | ||||
1761 | return false; | ||||
1762 | |||||
1763 | auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1)); | ||||
1764 | if (!CmpC || !CmpC->isZero()) | ||||
1765 | return false; | ||||
1766 | } | ||||
1767 | |||||
1768 | if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI)) | ||||
1769 | return false; | ||||
1770 | |||||
1771 | LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "found 'and' feeding only icmp 0;\n" ; } } while (false); | ||||
1772 | LLVM_DEBUG(AndI->getParent()->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { AndI->getParent()->dump(); } } while (false); | ||||
1773 | |||||
1774 | // Push the 'and' into the same block as the icmp 0. There should only be | ||||
1775 | // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any | ||||
1776 | // others, so we don't need to keep track of which BBs we insert into. | ||||
1777 | for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end(); | ||||
1778 | UI != E; ) { | ||||
1779 | Use &TheUse = UI.getUse(); | ||||
1780 | Instruction *User = cast<Instruction>(*UI); | ||||
1781 | |||||
1782 | // Preincrement use iterator so we don't invalidate it. | ||||
1783 | ++UI; | ||||
1784 | |||||
1785 | LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "sinking 'and' use: " << *User << "\n"; } } while (false); | ||||
1786 | |||||
1787 | // Keep the 'and' in the same place if the use is already in the same block. | ||||
1788 | Instruction *InsertPt = | ||||
1789 | User->getParent() == AndI->getParent() ? AndI : User; | ||||
1790 | Instruction *InsertedAnd = | ||||
1791 | BinaryOperator::Create(Instruction::And, AndI->getOperand(0), | ||||
1792 | AndI->getOperand(1), "", InsertPt); | ||||
1793 | // Propagate the debug info. | ||||
1794 | InsertedAnd->setDebugLoc(AndI->getDebugLoc()); | ||||
1795 | |||||
1796 | // Replace a use of the 'and' with a use of the new 'and'. | ||||
1797 | TheUse = InsertedAnd; | ||||
1798 | ++NumAndUses; | ||||
1799 | LLVM_DEBUG(User->getParent()->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { User->getParent()->dump(); } } while (false); | ||||
1800 | } | ||||
1801 | |||||
1802 | // We removed all uses, nuke the and. | ||||
1803 | AndI->eraseFromParent(); | ||||
1804 | return true; | ||||
1805 | } | ||||
1806 | |||||
1807 | /// Check if the candidates could be combined with a shift instruction, which | ||||
1808 | /// includes: | ||||
1809 | /// 1. Truncate instruction | ||||
1810 | /// 2. And instruction and the imm is a mask of the low bits: | ||||
1811 | /// imm & (imm+1) == 0 | ||||
1812 | static bool isExtractBitsCandidateUse(Instruction *User) { | ||||
1813 | if (!isa<TruncInst>(User)) { | ||||
1814 | if (User->getOpcode() != Instruction::And || | ||||
1815 | !isa<ConstantInt>(User->getOperand(1))) | ||||
1816 | return false; | ||||
1817 | |||||
1818 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); | ||||
1819 | |||||
1820 | if ((Cimm & (Cimm + 1)).getBoolValue()) | ||||
1821 | return false; | ||||
1822 | } | ||||
1823 | return true; | ||||
1824 | } | ||||
1825 | |||||
1826 | /// Sink both shift and truncate instruction to the use of truncate's BB. | ||||
1827 | static bool | ||||
1828 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, | ||||
1829 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, | ||||
1830 | const TargetLowering &TLI, const DataLayout &DL) { | ||||
1831 | BasicBlock *UserBB = User->getParent(); | ||||
1832 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; | ||||
1833 | auto *TruncI = cast<TruncInst>(User); | ||||
1834 | bool MadeChange = false; | ||||
1835 | |||||
1836 | for (Value::user_iterator TruncUI = TruncI->user_begin(), | ||||
1837 | TruncE = TruncI->user_end(); | ||||
1838 | TruncUI != TruncE;) { | ||||
1839 | |||||
1840 | Use &TruncTheUse = TruncUI.getUse(); | ||||
1841 | Instruction *TruncUser = cast<Instruction>(*TruncUI); | ||||
1842 | // Preincrement use iterator so we don't invalidate it. | ||||
1843 | |||||
1844 | ++TruncUI; | ||||
1845 | |||||
1846 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); | ||||
1847 | if (!ISDOpcode) | ||||
1848 | continue; | ||||
1849 | |||||
1850 | // If the use is actually a legal node, there will not be an | ||||
1851 | // implicit truncate. | ||||
1852 | // FIXME: always querying the result type is just an | ||||
1853 | // approximation; some nodes' legality is determined by the | ||||
1854 | // operand or other means. There's no good way to find out though. | ||||
1855 | if (TLI.isOperationLegalOrCustom( | ||||
1856 | ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true))) | ||||
1857 | continue; | ||||
1858 | |||||
1859 | // Don't bother for PHI nodes. | ||||
1860 | if (isa<PHINode>(TruncUser)) | ||||
1861 | continue; | ||||
1862 | |||||
1863 | BasicBlock *TruncUserBB = TruncUser->getParent(); | ||||
1864 | |||||
1865 | if (UserBB == TruncUserBB) | ||||
1866 | continue; | ||||
1867 | |||||
1868 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; | ||||
1869 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; | ||||
1870 | |||||
1871 | if (!InsertedShift && !InsertedTrunc) { | ||||
1872 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); | ||||
1873 | assert(InsertPt != TruncUserBB->end())(static_cast <bool> (InsertPt != TruncUserBB->end()) ? void (0) : __assert_fail ("InsertPt != TruncUserBB->end()" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1873, __extension__ __PRETTY_FUNCTION__ )); | ||||
1874 | // Sink the shift | ||||
1875 | if (ShiftI->getOpcode() == Instruction::AShr) | ||||
1876 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, | ||||
1877 | "", &*InsertPt); | ||||
1878 | else | ||||
1879 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, | ||||
1880 | "", &*InsertPt); | ||||
1881 | InsertedShift->setDebugLoc(ShiftI->getDebugLoc()); | ||||
1882 | |||||
1883 | // Sink the trunc | ||||
1884 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); | ||||
1885 | TruncInsertPt++; | ||||
1886 | assert(TruncInsertPt != TruncUserBB->end())(static_cast <bool> (TruncInsertPt != TruncUserBB->end ()) ? void (0) : __assert_fail ("TruncInsertPt != TruncUserBB->end()" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 1886, __extension__ __PRETTY_FUNCTION__ )); | ||||
1887 | |||||
1888 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, | ||||
1889 | TruncI->getType(), "", &*TruncInsertPt); | ||||
1890 | InsertedTrunc->setDebugLoc(TruncI->getDebugLoc()); | ||||
1891 | |||||
1892 | MadeChange = true; | ||||
1893 | |||||
1894 | TruncTheUse = InsertedTrunc; | ||||
1895 | } | ||||
1896 | } | ||||
1897 | return MadeChange; | ||||
1898 | } | ||||
1899 | |||||
1900 | /// Sink the shift *right* instruction into user blocks if the uses could | ||||
1901 | /// potentially be combined with this shift instruction and generate BitExtract | ||||
1902 | /// instruction. It will only be applied if the architecture supports BitExtract | ||||
1903 | /// instruction. Here is an example: | ||||
1904 | /// BB1: | ||||
1905 | /// %x.extract.shift = lshr i64 %arg1, 32 | ||||
1906 | /// BB2: | ||||
1907 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 | ||||
1908 | /// ==> | ||||
1909 | /// | ||||
1910 | /// BB2: | ||||
1911 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 | ||||
1912 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 | ||||
1913 | /// | ||||
1914 | /// CodeGen will recognize the pattern in BB2 and generate BitExtract | ||||
1915 | /// instruction. | ||||
1916 | /// Return true if any changes are made. | ||||
1917 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, | ||||
1918 | const TargetLowering &TLI, | ||||
1919 | const DataLayout &DL) { | ||||
1920 | BasicBlock *DefBB = ShiftI->getParent(); | ||||
1921 | |||||
1922 | /// Only insert instructions in each block once. | ||||
1923 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; | ||||
1924 | |||||
1925 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType())); | ||||
1926 | |||||
1927 | bool MadeChange = false; | ||||
1928 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); | ||||
1929 | UI != E;) { | ||||
1930 | Use &TheUse = UI.getUse(); | ||||
1931 | Instruction *User = cast<Instruction>(*UI); | ||||
1932 | // Preincrement use iterator so we don't invalidate it. | ||||
1933 | ++UI; | ||||
1934 | |||||
1935 | // Don't bother for PHI nodes. | ||||
1936 | if (isa<PHINode>(User)) | ||||
1937 | continue; | ||||
1938 | |||||
1939 | if (!isExtractBitsCandidateUse(User)) | ||||
1940 | continue; | ||||
1941 | |||||
1942 | BasicBlock *UserBB = User->getParent(); | ||||
1943 | |||||
1944 | if (UserBB == DefBB) { | ||||
1945 | // If the shift and truncate instruction are in the same BB. The use of | ||||
1946 | // the truncate(TruncUse) may still introduce another truncate if not | ||||
1947 | // legal. In this case, we would like to sink both shift and truncate | ||||
1948 | // instruction to the BB of TruncUse. | ||||
1949 | // for example: | ||||
1950 | // BB1: | ||||
1951 | // i64 shift.result = lshr i64 opnd, imm | ||||
1952 | // trunc.result = trunc shift.result to i16 | ||||
1953 | // | ||||
1954 | // BB2: | ||||
1955 | // ----> We will have an implicit truncate here if the architecture does | ||||
1956 | // not have i16 compare. | ||||
1957 | // cmp i16 trunc.result, opnd2 | ||||
1958 | // | ||||
1959 | if (isa<TruncInst>(User) && shiftIsLegal | ||||
1960 | // If the type of the truncate is legal, no truncate will be | ||||
1961 | // introduced in other basic blocks. | ||||
1962 | && | ||||
1963 | (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType())))) | ||||
1964 | MadeChange = | ||||
1965 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL); | ||||
1966 | |||||
1967 | continue; | ||||
1968 | } | ||||
1969 | // If we have already inserted a shift into this block, use it. | ||||
1970 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; | ||||
1971 | |||||
1972 | if (!InsertedShift) { | ||||
1973 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); | ||||
1974 | assert(InsertPt != UserBB->end())(static_cast <bool> (InsertPt != UserBB->end()) ? void (0) : __assert_fail ("InsertPt != UserBB->end()", "llvm/lib/CodeGen/CodeGenPrepare.cpp" , 1974, __extension__ __PRETTY_FUNCTION__)); | ||||
1975 | |||||
1976 | if (ShiftI->getOpcode() == Instruction::AShr) | ||||
1977 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, | ||||
1978 | "", &*InsertPt); | ||||
1979 | else | ||||
1980 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, | ||||
1981 | "", &*InsertPt); | ||||
1982 | InsertedShift->setDebugLoc(ShiftI->getDebugLoc()); | ||||
1983 | |||||
1984 | MadeChange = true; | ||||
1985 | } | ||||
1986 | |||||
1987 | // Replace a use of the shift with a use of the new shift. | ||||
1988 | TheUse = InsertedShift; | ||||
1989 | } | ||||
1990 | |||||
1991 | // If we removed all uses, or there are none, nuke the shift. | ||||
1992 | if (ShiftI->use_empty()) { | ||||
1993 | salvageDebugInfo(*ShiftI); | ||||
1994 | ShiftI->eraseFromParent(); | ||||
1995 | MadeChange = true; | ||||
1996 | } | ||||
1997 | |||||
1998 | return MadeChange; | ||||
1999 | } | ||||
2000 | |||||
2001 | /// If counting leading or trailing zeros is an expensive operation and a zero | ||||
2002 | /// input is defined, add a check for zero to avoid calling the intrinsic. | ||||
2003 | /// | ||||
2004 | /// We want to transform: | ||||
2005 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false) | ||||
2006 | /// | ||||
2007 | /// into: | ||||
2008 | /// entry: | ||||
2009 | /// %cmpz = icmp eq i64 %A, 0 | ||||
2010 | /// br i1 %cmpz, label %cond.end, label %cond.false | ||||
2011 | /// cond.false: | ||||
2012 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true) | ||||
2013 | /// br label %cond.end | ||||
2014 | /// cond.end: | ||||
2015 | /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ] | ||||
2016 | /// | ||||
2017 | /// If the transform is performed, return true and set ModifiedDT to true. | ||||
2018 | static bool despeculateCountZeros(IntrinsicInst *CountZeros, | ||||
2019 | const TargetLowering *TLI, | ||||
2020 | const DataLayout *DL, | ||||
2021 | bool &ModifiedDT) { | ||||
2022 | // If a zero input is undefined, it doesn't make sense to despeculate that. | ||||
2023 | if (match(CountZeros->getOperand(1), m_One())) | ||||
2024 | return false; | ||||
2025 | |||||
2026 | // If it's cheap to speculate, there's nothing to do. | ||||
2027 | auto IntrinsicID = CountZeros->getIntrinsicID(); | ||||
2028 | if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) || | ||||
2029 | (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz())) | ||||
2030 | return false; | ||||
2031 | |||||
2032 | // Only handle legal scalar cases. Anything else requires too much work. | ||||
2033 | Type *Ty = CountZeros->getType(); | ||||
2034 | unsigned SizeInBits = Ty->getScalarSizeInBits(); | ||||
2035 | if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits()) | ||||
2036 | return false; | ||||
2037 | |||||
2038 | // Bail if the value is never zero. | ||||
2039 | if (llvm::isKnownNonZero(CountZeros->getOperand(0), *DL)) | ||||
2040 | return false; | ||||
2041 | |||||
2042 | // The intrinsic will be sunk behind a compare against zero and branch. | ||||
2043 | BasicBlock *StartBlock = CountZeros->getParent(); | ||||
2044 | BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false"); | ||||
2045 | |||||
2046 | // Create another block after the count zero intrinsic. A PHI will be added | ||||
2047 | // in this block to select the result of the intrinsic or the bit-width | ||||
2048 | // constant if the input to the intrinsic is zero. | ||||
2049 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros)); | ||||
2050 | BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end"); | ||||
2051 | |||||
2052 | // Set up a builder to create a compare, conditional branch, and PHI. | ||||
2053 | IRBuilder<> Builder(CountZeros->getContext()); | ||||
2054 | Builder.SetInsertPoint(StartBlock->getTerminator()); | ||||
2055 | Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc()); | ||||
2056 | |||||
2057 | // Replace the unconditional branch that was created by the first split with | ||||
2058 | // a compare against zero and a conditional branch. | ||||
2059 | Value *Zero = Constant::getNullValue(Ty); | ||||
2060 | Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz"); | ||||
2061 | Builder.CreateCondBr(Cmp, EndBlock, CallBlock); | ||||
2062 | StartBlock->getTerminator()->eraseFromParent(); | ||||
2063 | |||||
2064 | // Create a PHI in the end block to select either the output of the intrinsic | ||||
2065 | // or the bit width of the operand. | ||||
2066 | Builder.SetInsertPoint(&EndBlock->front()); | ||||
2067 | PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz"); | ||||
2068 | CountZeros->replaceAllUsesWith(PN); | ||||
2069 | Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits)); | ||||
2070 | PN->addIncoming(BitWidth, StartBlock); | ||||
2071 | PN->addIncoming(CountZeros, CallBlock); | ||||
2072 | |||||
2073 | // We are explicitly handling the zero case, so we can set the intrinsic's | ||||
2074 | // undefined zero argument to 'true'. This will also prevent reprocessing the | ||||
2075 | // intrinsic; we only despeculate when a zero input is defined. | ||||
2076 | CountZeros->setArgOperand(1, Builder.getTrue()); | ||||
2077 | ModifiedDT = true; | ||||
2078 | return true; | ||||
2079 | } | ||||
2080 | |||||
2081 | bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) { | ||||
2082 | BasicBlock *BB = CI->getParent(); | ||||
2083 | |||||
2084 | // Lower inline assembly if we can. | ||||
2085 | // If we found an inline asm expession, and if the target knows how to | ||||
2086 | // lower it to normal LLVM code, do so now. | ||||
2087 | if (CI->isInlineAsm()) { | ||||
2088 | if (TLI->ExpandInlineAsm(CI)) { | ||||
2089 | // Avoid invalidating the iterator. | ||||
2090 | CurInstIterator = BB->begin(); | ||||
2091 | // Avoid processing instructions out of order, which could cause | ||||
2092 | // reuse before a value is defined. | ||||
2093 | SunkAddrs.clear(); | ||||
2094 | return true; | ||||
2095 | } | ||||
2096 | // Sink address computing for memory operands into the block. | ||||
2097 | if (optimizeInlineAsmInst(CI)) | ||||
2098 | return true; | ||||
2099 | } | ||||
2100 | |||||
2101 | // Align the pointer arguments to this call if the target thinks it's a good | ||||
2102 | // idea | ||||
2103 | unsigned MinSize, PrefAlign; | ||||
2104 | if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) { | ||||
2105 | for (auto &Arg : CI->args()) { | ||||
2106 | // We want to align both objects whose address is used directly and | ||||
2107 | // objects whose address is used in casts and GEPs, though it only makes | ||||
2108 | // sense for GEPs if the offset is a multiple of the desired alignment and | ||||
2109 | // if size - offset meets the size threshold. | ||||
2110 | if (!Arg->getType()->isPointerTy()) | ||||
2111 | continue; | ||||
2112 | APInt Offset(DL->getIndexSizeInBits( | ||||
2113 | cast<PointerType>(Arg->getType())->getAddressSpace()), | ||||
2114 | 0); | ||||
2115 | Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset); | ||||
2116 | uint64_t Offset2 = Offset.getLimitedValue(); | ||||
2117 | if ((Offset2 & (PrefAlign-1)) != 0) | ||||
2118 | continue; | ||||
2119 | AllocaInst *AI; | ||||
2120 | if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign && | ||||
2121 | DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2) | ||||
2122 | AI->setAlignment(Align(PrefAlign)); | ||||
2123 | // Global variables can only be aligned if they are defined in this | ||||
2124 | // object (i.e. they are uniquely initialized in this object), and | ||||
2125 | // over-aligning global variables that have an explicit section is | ||||
2126 | // forbidden. | ||||
2127 | GlobalVariable *GV; | ||||
2128 | if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() && | ||||
2129 | GV->getPointerAlignment(*DL) < PrefAlign && | ||||
2130 | DL->getTypeAllocSize(GV->getValueType()) >= | ||||
2131 | MinSize + Offset2) | ||||
2132 | GV->setAlignment(MaybeAlign(PrefAlign)); | ||||
2133 | } | ||||
2134 | // If this is a memcpy (or similar) then we may be able to improve the | ||||
2135 | // alignment | ||||
2136 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) { | ||||
2137 | Align DestAlign = getKnownAlignment(MI->getDest(), *DL); | ||||
2138 | MaybeAlign MIDestAlign = MI->getDestAlign(); | ||||
2139 | if (!MIDestAlign || DestAlign > *MIDestAlign) | ||||
2140 | MI->setDestAlignment(DestAlign); | ||||
2141 | if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { | ||||
2142 | MaybeAlign MTISrcAlign = MTI->getSourceAlign(); | ||||
2143 | Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL); | ||||
2144 | if (!MTISrcAlign || SrcAlign > *MTISrcAlign) | ||||
2145 | MTI->setSourceAlignment(SrcAlign); | ||||
2146 | } | ||||
2147 | } | ||||
2148 | } | ||||
2149 | |||||
2150 | // If we have a cold call site, try to sink addressing computation into the | ||||
2151 | // cold block. This interacts with our handling for loads and stores to | ||||
2152 | // ensure that we can fold all uses of a potential addressing computation | ||||
2153 | // into their uses. TODO: generalize this to work over profiling data | ||||
2154 | if (CI->hasFnAttr(Attribute::Cold) && | ||||
2155 | !OptSize && !llvm::shouldOptimizeForSize(BB, PSI, BFI.get())) | ||||
2156 | for (auto &Arg : CI->args()) { | ||||
2157 | if (!Arg->getType()->isPointerTy()) | ||||
2158 | continue; | ||||
2159 | unsigned AS = Arg->getType()->getPointerAddressSpace(); | ||||
2160 | return optimizeMemoryInst(CI, Arg, Arg->getType(), AS); | ||||
2161 | } | ||||
2162 | |||||
2163 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); | ||||
2164 | if (II) { | ||||
2165 | switch (II->getIntrinsicID()) { | ||||
2166 | default: break; | ||||
2167 | case Intrinsic::assume: | ||||
2168 | llvm_unreachable("llvm.assume should have been removed already")::llvm::llvm_unreachable_internal("llvm.assume should have been removed already" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 2168); | ||||
2169 | case Intrinsic::experimental_widenable_condition: { | ||||
2170 | // Give up on future widening oppurtunties so that we can fold away dead | ||||
2171 | // paths and merge blocks before going into block-local instruction | ||||
2172 | // selection. | ||||
2173 | if (II->use_empty()) { | ||||
2174 | II->eraseFromParent(); | ||||
2175 | return true; | ||||
2176 | } | ||||
2177 | Constant *RetVal = ConstantInt::getTrue(II->getContext()); | ||||
2178 | resetIteratorIfInvalidatedWhileCalling(BB, [&]() { | ||||
2179 | replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr); | ||||
2180 | }); | ||||
2181 | return true; | ||||
2182 | } | ||||
2183 | case Intrinsic::objectsize: | ||||
2184 | llvm_unreachable("llvm.objectsize.* should have been lowered already")::llvm::llvm_unreachable_internal("llvm.objectsize.* should have been lowered already" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 2184); | ||||
2185 | case Intrinsic::is_constant: | ||||
2186 | llvm_unreachable("llvm.is.constant.* should have been lowered already")::llvm::llvm_unreachable_internal("llvm.is.constant.* should have been lowered already" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 2186); | ||||
2187 | case Intrinsic::aarch64_stlxr: | ||||
2188 | case Intrinsic::aarch64_stxr: { | ||||
2189 | ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); | ||||
2190 | if (!ExtVal || !ExtVal->hasOneUse() || | ||||
2191 | ExtVal->getParent() == CI->getParent()) | ||||
2192 | return false; | ||||
2193 | // Sink a zext feeding stlxr/stxr before it, so it can be folded into it. | ||||
2194 | ExtVal->moveBefore(CI); | ||||
2195 | // Mark this instruction as "inserted by CGP", so that other | ||||
2196 | // optimizations don't touch it. | ||||
2197 | InsertedInsts.insert(ExtVal); | ||||
2198 | return true; | ||||
2199 | } | ||||
2200 | |||||
2201 | case Intrinsic::launder_invariant_group: | ||||
2202 | case Intrinsic::strip_invariant_group: { | ||||
2203 | Value *ArgVal = II->getArgOperand(0); | ||||
2204 | auto it = LargeOffsetGEPMap.find(II); | ||||
2205 | if (it != LargeOffsetGEPMap.end()) { | ||||
2206 | // Merge entries in LargeOffsetGEPMap to reflect the RAUW. | ||||
2207 | // Make sure not to have to deal with iterator invalidation | ||||
2208 | // after possibly adding ArgVal to LargeOffsetGEPMap. | ||||
2209 | auto GEPs = std::move(it->second); | ||||
2210 | LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end()); | ||||
2211 | LargeOffsetGEPMap.erase(II); | ||||
2212 | } | ||||
2213 | |||||
2214 | II->replaceAllUsesWith(ArgVal); | ||||
2215 | II->eraseFromParent(); | ||||
2216 | return true; | ||||
2217 | } | ||||
2218 | case Intrinsic::cttz: | ||||
2219 | case Intrinsic::ctlz: | ||||
2220 | // If counting zeros is expensive, try to avoid it. | ||||
2221 | return despeculateCountZeros(II, TLI, DL, ModifiedDT); | ||||
2222 | case Intrinsic::fshl: | ||||
2223 | case Intrinsic::fshr: | ||||
2224 | return optimizeFunnelShift(II); | ||||
2225 | case Intrinsic::dbg_value: | ||||
2226 | return fixupDbgValue(II); | ||||
2227 | case Intrinsic::vscale: { | ||||
2228 | // If datalayout has no special restrictions on vector data layout, | ||||
2229 | // replace `llvm.vscale` by an equivalent constant expression | ||||
2230 | // to benefit from cheap constant propagation. | ||||
2231 | Type *ScalableVectorTy = | ||||
2232 | VectorType::get(Type::getInt8Ty(II->getContext()), 1, true); | ||||
2233 | if (DL->getTypeAllocSize(ScalableVectorTy).getKnownMinSize() == 8) { | ||||
2234 | auto *Null = Constant::getNullValue(ScalableVectorTy->getPointerTo()); | ||||
2235 | auto *One = ConstantInt::getSigned(II->getType(), 1); | ||||
2236 | auto *CGep = | ||||
2237 | ConstantExpr::getGetElementPtr(ScalableVectorTy, Null, One); | ||||
2238 | II->replaceAllUsesWith(ConstantExpr::getPtrToInt(CGep, II->getType())); | ||||
2239 | II->eraseFromParent(); | ||||
2240 | return true; | ||||
2241 | } | ||||
2242 | break; | ||||
2243 | } | ||||
2244 | case Intrinsic::masked_gather: | ||||
2245 | return optimizeGatherScatterInst(II, II->getArgOperand(0)); | ||||
2246 | case Intrinsic::masked_scatter: | ||||
2247 | return optimizeGatherScatterInst(II, II->getArgOperand(1)); | ||||
2248 | } | ||||
2249 | |||||
2250 | SmallVector<Value *, 2> PtrOps; | ||||
2251 | Type *AccessTy; | ||||
2252 | if (TLI->getAddrModeArguments(II, PtrOps, AccessTy)) | ||||
2253 | while (!PtrOps.empty()) { | ||||
2254 | Value *PtrVal = PtrOps.pop_back_val(); | ||||
2255 | unsigned AS = PtrVal->getType()->getPointerAddressSpace(); | ||||
2256 | if (optimizeMemoryInst(II, PtrVal, AccessTy, AS)) | ||||
2257 | return true; | ||||
2258 | } | ||||
2259 | } | ||||
2260 | |||||
2261 | // From here on out we're working with named functions. | ||||
2262 | if (!CI->getCalledFunction()) return false; | ||||
2263 | |||||
2264 | // Lower all default uses of _chk calls. This is very similar | ||||
2265 | // to what InstCombineCalls does, but here we are only lowering calls | ||||
2266 | // to fortified library functions (e.g. __memcpy_chk) that have the default | ||||
2267 | // "don't know" as the objectsize. Anything else should be left alone. | ||||
2268 | FortifiedLibCallSimplifier Simplifier(TLInfo, true); | ||||
2269 | IRBuilder<> Builder(CI); | ||||
2270 | if (Value *V = Simplifier.optimizeCall(CI, Builder)) { | ||||
2271 | CI->replaceAllUsesWith(V); | ||||
2272 | CI->eraseFromParent(); | ||||
2273 | return true; | ||||
2274 | } | ||||
2275 | |||||
2276 | return false; | ||||
2277 | } | ||||
2278 | |||||
2279 | /// Look for opportunities to duplicate return instructions to the predecessor | ||||
2280 | /// to enable tail call optimizations. The case it is currently looking for is: | ||||
2281 | /// @code | ||||
2282 | /// bb0: | ||||
2283 | /// %tmp0 = tail call i32 @f0() | ||||
2284 | /// br label %return | ||||
2285 | /// bb1: | ||||
2286 | /// %tmp1 = tail call i32 @f1() | ||||
2287 | /// br label %return | ||||
2288 | /// bb2: | ||||
2289 | /// %tmp2 = tail call i32 @f2() | ||||
2290 | /// br label %return | ||||
2291 | /// return: | ||||
2292 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] | ||||
2293 | /// ret i32 %retval | ||||
2294 | /// @endcode | ||||
2295 | /// | ||||
2296 | /// => | ||||
2297 | /// | ||||
2298 | /// @code | ||||
2299 | /// bb0: | ||||
2300 | /// %tmp0 = tail call i32 @f0() | ||||
2301 | /// ret i32 %tmp0 | ||||
2302 | /// bb1: | ||||
2303 | /// %tmp1 = tail call i32 @f1() | ||||
2304 | /// ret i32 %tmp1 | ||||
2305 | /// bb2: | ||||
2306 | /// %tmp2 = tail call i32 @f2() | ||||
2307 | /// ret i32 %tmp2 | ||||
2308 | /// @endcode | ||||
2309 | bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT) { | ||||
2310 | ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator()); | ||||
| |||||
2311 | if (!RetI
| ||||
2312 | return false; | ||||
2313 | |||||
2314 | PHINode *PN = nullptr; | ||||
2315 | ExtractValueInst *EVI = nullptr; | ||||
2316 | BitCastInst *BCI = nullptr; | ||||
2317 | Value *V = RetI->getReturnValue(); | ||||
2318 | if (V
| ||||
2319 | BCI = dyn_cast<BitCastInst>(V); | ||||
2320 | if (BCI) | ||||
2321 | V = BCI->getOperand(0); | ||||
2322 | |||||
2323 | EVI = dyn_cast<ExtractValueInst>(V); | ||||
2324 | if (EVI) { | ||||
2325 | V = EVI->getOperand(0); | ||||
2326 | if (!llvm::all_of(EVI->indices(), [](unsigned idx) { return idx == 0; })) | ||||
2327 | return false; | ||||
2328 | } | ||||
2329 | |||||
2330 | PN = dyn_cast<PHINode>(V); | ||||
2331 | if (!PN) | ||||
2332 | return false; | ||||
2333 | } | ||||
2334 | |||||
2335 | if (PN
| ||||
2336 | return false; | ||||
2337 | |||||
2338 | auto isLifetimeEndOrBitCastFor = [](const Instruction *Inst) { | ||||
2339 | const BitCastInst *BC = dyn_cast<BitCastInst>(Inst); | ||||
2340 | if (BC && BC->hasOneUse()) | ||||
2341 | Inst = BC->user_back(); | ||||
2342 | |||||
2343 | if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) | ||||
2344 | return II->getIntrinsicID() == Intrinsic::lifetime_end; | ||||
2345 | return false; | ||||
2346 | }; | ||||
2347 | |||||
2348 | // Make sure there are no instructions between the first instruction | ||||
2349 | // and return. | ||||
2350 | const Instruction *BI = BB->getFirstNonPHI(); | ||||
2351 | // Skip over debug and the bitcast. | ||||
2352 | while (isa<DbgInfoIntrinsic>(BI) || BI == BCI || BI == EVI || | ||||
2353 | isa<PseudoProbeInst>(BI) || isLifetimeEndOrBitCastFor(BI)) | ||||
2354 | BI = BI->getNextNode(); | ||||
| |||||
2355 | if (BI != RetI) | ||||
2356 | return false; | ||||
2357 | |||||
2358 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail | ||||
2359 | /// call. | ||||
2360 | const Function *F = BB->getParent(); | ||||
2361 | SmallVector<BasicBlock*, 4> TailCallBBs; | ||||
2362 | if (PN) { | ||||
2363 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { | ||||
2364 | // Look through bitcasts. | ||||
2365 | Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts(); | ||||
2366 | CallInst *CI = dyn_cast<CallInst>(IncomingVal); | ||||
2367 | BasicBlock *PredBB = PN->getIncomingBlock(I); | ||||
2368 | // Make sure the phi value is indeed produced by the tail call. | ||||
2369 | if (CI && CI->hasOneUse() && CI->getParent() == PredBB && | ||||
2370 | TLI->mayBeEmittedAsTailCall(CI) && | ||||
2371 | attributesPermitTailCall(F, CI, RetI, *TLI)) | ||||
2372 | TailCallBBs.push_back(PredBB); | ||||
2373 | } | ||||
2374 | } else { | ||||
2375 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; | ||||
2376 | for (BasicBlock *Pred : predecessors(BB)) { | ||||
2377 | if (!VisitedBBs.insert(Pred).second) | ||||
2378 | continue; | ||||
2379 | if (Instruction *I = Pred->rbegin()->getPrevNonDebugInstruction(true)) { | ||||
2380 | CallInst *CI = dyn_cast<CallInst>(I); | ||||
2381 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) && | ||||
2382 | attributesPermitTailCall(F, CI, RetI, *TLI)) | ||||
2383 | TailCallBBs.push_back(Pred); | ||||
2384 | } | ||||
2385 | } | ||||
2386 | } | ||||
2387 | |||||
2388 | bool Changed = false; | ||||
2389 | for (auto const &TailCallBB : TailCallBBs) { | ||||
2390 | // Make sure the call instruction is followed by an unconditional branch to | ||||
2391 | // the return block. | ||||
2392 | BranchInst *BI = dyn_cast<BranchInst>(TailCallBB->getTerminator()); | ||||
2393 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) | ||||
2394 | continue; | ||||
2395 | |||||
2396 | // Duplicate the return into TailCallBB. | ||||
2397 | (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB); | ||||
2398 | assert(!VerifyBFIUpdates ||(static_cast <bool> (!VerifyBFIUpdates || BFI->getBlockFreq (BB) >= BFI->getBlockFreq(TailCallBB)) ? void (0) : __assert_fail ("!VerifyBFIUpdates || BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB)" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 2399, __extension__ __PRETTY_FUNCTION__ )) | ||||
2399 | BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB))(static_cast <bool> (!VerifyBFIUpdates || BFI->getBlockFreq (BB) >= BFI->getBlockFreq(TailCallBB)) ? void (0) : __assert_fail ("!VerifyBFIUpdates || BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB)" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 2399, __extension__ __PRETTY_FUNCTION__ )); | ||||
2400 | BFI->setBlockFreq( | ||||
2401 | BB, | ||||
2402 | (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)).getFrequency()); | ||||
2403 | ModifiedDT = Changed = true; | ||||
2404 | ++NumRetsDup; | ||||
2405 | } | ||||
2406 | |||||
2407 | // If we eliminated all predecessors of the block, delete the block now. | ||||
2408 | if (Changed && !BB->hasAddressTaken() && pred_empty(BB)) | ||||
2409 | BB->eraseFromParent(); | ||||
2410 | |||||
2411 | return Changed; | ||||
2412 | } | ||||
2413 | |||||
2414 | //===----------------------------------------------------------------------===// | ||||
2415 | // Memory Optimization | ||||
2416 | //===----------------------------------------------------------------------===// | ||||
2417 | |||||
2418 | namespace { | ||||
2419 | |||||
2420 | /// This is an extended version of TargetLowering::AddrMode | ||||
2421 | /// which holds actual Value*'s for register values. | ||||
2422 | struct ExtAddrMode : public TargetLowering::AddrMode { | ||||
2423 | Value *BaseReg = nullptr; | ||||
2424 | Value *ScaledReg = nullptr; | ||||
2425 | Value *OriginalValue = nullptr; | ||||
2426 | bool InBounds = true; | ||||
2427 | |||||
2428 | enum FieldName { | ||||
2429 | NoField = 0x00, | ||||
2430 | BaseRegField = 0x01, | ||||
2431 | BaseGVField = 0x02, | ||||
2432 | BaseOffsField = 0x04, | ||||
2433 | ScaledRegField = 0x08, | ||||
2434 | ScaleField = 0x10, | ||||
2435 | MultipleFields = 0xff | ||||
2436 | }; | ||||
2437 | |||||
2438 | |||||
2439 | ExtAddrMode() = default; | ||||
2440 | |||||
2441 | void print(raw_ostream &OS) const; | ||||
2442 | void dump() const; | ||||
2443 | |||||
2444 | FieldName compare(const ExtAddrMode &other) { | ||||
2445 | // First check that the types are the same on each field, as differing types | ||||
2446 | // is something we can't cope with later on. | ||||
2447 | if (BaseReg && other.BaseReg && | ||||
2448 | BaseReg->getType() != other.BaseReg->getType()) | ||||
2449 | return MultipleFields; | ||||
2450 | if (BaseGV && other.BaseGV && | ||||
2451 | BaseGV->getType() != other.BaseGV->getType()) | ||||
2452 | return MultipleFields; | ||||
2453 | if (ScaledReg && other.ScaledReg && | ||||
2454 | ScaledReg->getType() != other.ScaledReg->getType()) | ||||
2455 | return MultipleFields; | ||||
2456 | |||||
2457 | // Conservatively reject 'inbounds' mismatches. | ||||
2458 | if (InBounds != other.InBounds) | ||||
2459 | return MultipleFields; | ||||
2460 | |||||
2461 | // Check each field to see if it differs. | ||||
2462 | unsigned Result = NoField; | ||||
2463 | if (BaseReg != other.BaseReg) | ||||
2464 | Result |= BaseRegField; | ||||
2465 | if (BaseGV != other.BaseGV) | ||||
2466 | Result |= BaseGVField; | ||||
2467 | if (BaseOffs != other.BaseOffs) | ||||
2468 | Result |= BaseOffsField; | ||||
2469 | if (ScaledReg != other.ScaledReg) | ||||
2470 | Result |= ScaledRegField; | ||||
2471 | // Don't count 0 as being a different scale, because that actually means | ||||
2472 | // unscaled (which will already be counted by having no ScaledReg). | ||||
2473 | if (Scale && other.Scale && Scale != other.Scale) | ||||
2474 | Result |= ScaleField; | ||||
2475 | |||||
2476 | if (countPopulation(Result) > 1) | ||||
2477 | return MultipleFields; | ||||
2478 | else | ||||
2479 | return static_cast<FieldName>(Result); | ||||
2480 | } | ||||
2481 | |||||
2482 | // An AddrMode is trivial if it involves no calculation i.e. it is just a base | ||||
2483 | // with no offset. | ||||
2484 | bool isTrivial() { | ||||
2485 | // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is | ||||
2486 | // trivial if at most one of these terms is nonzero, except that BaseGV and | ||||
2487 | // BaseReg both being zero actually means a null pointer value, which we | ||||
2488 | // consider to be 'non-zero' here. | ||||
2489 | return !BaseOffs && !Scale && !(BaseGV && BaseReg); | ||||
2490 | } | ||||
2491 | |||||
2492 | Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) { | ||||
2493 | switch (Field) { | ||||
2494 | default: | ||||
2495 | return nullptr; | ||||
2496 | case BaseRegField: | ||||
2497 | return BaseReg; | ||||
2498 | case BaseGVField: | ||||
2499 | return BaseGV; | ||||
2500 | case ScaledRegField: | ||||
2501 | return ScaledReg; | ||||
2502 | case BaseOffsField: | ||||
2503 | return ConstantInt::get(IntPtrTy, BaseOffs); | ||||
2504 | } | ||||
2505 | } | ||||
2506 | |||||
2507 | void SetCombinedField(FieldName Field, Value *V, | ||||
2508 | const SmallVectorImpl<ExtAddrMode> &AddrModes) { | ||||
2509 | switch (Field) { | ||||
2510 | default: | ||||
2511 | llvm_unreachable("Unhandled fields are expected to be rejected earlier")::llvm::llvm_unreachable_internal("Unhandled fields are expected to be rejected earlier" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 2511); | ||||
2512 | break; | ||||
2513 | case ExtAddrMode::BaseRegField: | ||||
2514 | BaseReg = V; | ||||
2515 | break; | ||||
2516 | case ExtAddrMode::BaseGVField: | ||||
2517 | // A combined BaseGV is an Instruction, not a GlobalValue, so it goes | ||||
2518 | // in the BaseReg field. | ||||
2519 | assert(BaseReg == nullptr)(static_cast <bool> (BaseReg == nullptr) ? void (0) : __assert_fail ("BaseReg == nullptr", "llvm/lib/CodeGen/CodeGenPrepare.cpp" , 2519, __extension__ __PRETTY_FUNCTION__)); | ||||
2520 | BaseReg = V; | ||||
2521 | BaseGV = nullptr; | ||||
2522 | break; | ||||
2523 | case ExtAddrMode::ScaledRegField: | ||||
2524 | ScaledReg = V; | ||||
2525 | // If we have a mix of scaled and unscaled addrmodes then we want scale | ||||
2526 | // to be the scale and not zero. | ||||
2527 | if (!Scale) | ||||
2528 | for (const ExtAddrMode &AM : AddrModes) | ||||
2529 | if (AM.Scale) { | ||||
2530 | Scale = AM.Scale; | ||||
2531 | break; | ||||
2532 | } | ||||
2533 | break; | ||||
2534 | case ExtAddrMode::BaseOffsField: | ||||
2535 | // The offset is no longer a constant, so it goes in ScaledReg with a | ||||
2536 | // scale of 1. | ||||
2537 | assert(ScaledReg == nullptr)(static_cast <bool> (ScaledReg == nullptr) ? void (0) : __assert_fail ("ScaledReg == nullptr", "llvm/lib/CodeGen/CodeGenPrepare.cpp" , 2537, __extension__ __PRETTY_FUNCTION__)); | ||||
2538 | ScaledReg = V; | ||||
2539 | Scale = 1; | ||||
2540 | BaseOffs = 0; | ||||
2541 | break; | ||||
2542 | } | ||||
2543 | } | ||||
2544 | }; | ||||
2545 | |||||
2546 | } // end anonymous namespace | ||||
2547 | |||||
2548 | #ifndef NDEBUG | ||||
2549 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { | ||||
2550 | AM.print(OS); | ||||
2551 | return OS; | ||||
2552 | } | ||||
2553 | #endif | ||||
2554 | |||||
2555 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) | ||||
2556 | void ExtAddrMode::print(raw_ostream &OS) const { | ||||
2557 | bool NeedPlus = false; | ||||
2558 | OS << "["; | ||||
2559 | if (InBounds) | ||||
2560 | OS << "inbounds "; | ||||
2561 | if (BaseGV) { | ||||
2562 | OS << (NeedPlus ? " + " : "") | ||||
2563 | << "GV:"; | ||||
2564 | BaseGV->printAsOperand(OS, /*PrintType=*/false); | ||||
2565 | NeedPlus = true; | ||||
2566 | } | ||||
2567 | |||||
2568 | if (BaseOffs) { | ||||
2569 | OS << (NeedPlus ? " + " : "") | ||||
2570 | << BaseOffs; | ||||
2571 | NeedPlus = true; | ||||
2572 | } | ||||
2573 | |||||
2574 | if (BaseReg) { | ||||
2575 | OS << (NeedPlus ? " + " : "") | ||||
2576 | << "Base:"; | ||||
2577 | BaseReg->printAsOperand(OS, /*PrintType=*/false); | ||||
2578 | NeedPlus = true; | ||||
2579 | } | ||||
2580 | if (Scale) { | ||||
2581 | OS << (NeedPlus ? " + " : "") | ||||
2582 | << Scale << "*"; | ||||
2583 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); | ||||
2584 | } | ||||
2585 | |||||
2586 | OS << ']'; | ||||
2587 | } | ||||
2588 | |||||
2589 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void ExtAddrMode::dump() const { | ||||
2590 | print(dbgs()); | ||||
2591 | dbgs() << '\n'; | ||||
2592 | } | ||||
2593 | #endif | ||||
2594 | |||||
2595 | namespace { | ||||
2596 | |||||
2597 | /// This class provides transaction based operation on the IR. | ||||
2598 | /// Every change made through this class is recorded in the internal state and | ||||
2599 | /// can be undone (rollback) until commit is called. | ||||
2600 | /// CGP does not check if instructions could be speculatively executed when | ||||
2601 | /// moved. Preserving the original location would pessimize the debugging | ||||
2602 | /// experience, as well as negatively impact the quality of sample PGO. | ||||
2603 | class TypePromotionTransaction { | ||||
2604 | /// This represents the common interface of the individual transaction. | ||||
2605 | /// Each class implements the logic for doing one specific modification on | ||||
2606 | /// the IR via the TypePromotionTransaction. | ||||
2607 | class TypePromotionAction { | ||||
2608 | protected: | ||||
2609 | /// The Instruction modified. | ||||
2610 | Instruction *Inst; | ||||
2611 | |||||
2612 | public: | ||||
2613 | /// Constructor of the action. | ||||
2614 | /// The constructor performs the related action on the IR. | ||||
2615 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} | ||||
2616 | |||||
2617 | virtual ~TypePromotionAction() = default; | ||||
2618 | |||||
2619 | /// Undo the modification done by this action. | ||||
2620 | /// When this method is called, the IR must be in the same state as it was | ||||
2621 | /// before this action was applied. | ||||
2622 | /// \pre Undoing the action works if and only if the IR is in the exact same | ||||
2623 | /// state as it was directly after this action was applied. | ||||
2624 | virtual void undo() = 0; | ||||
2625 | |||||
2626 | /// Advocate every change made by this action. | ||||
2627 | /// When the results on the IR of the action are to be kept, it is important | ||||
2628 | /// to call this function, otherwise hidden information may be kept forever. | ||||
2629 | virtual void commit() { | ||||
2630 | // Nothing to be done, this action is not doing anything. | ||||
2631 | } | ||||
2632 | }; | ||||
2633 | |||||
2634 | /// Utility to remember the position of an instruction. | ||||
2635 | class InsertionHandler { | ||||
2636 | /// Position of an instruction. | ||||
2637 | /// Either an instruction: | ||||
2638 | /// - Is the first in a basic block: BB is used. | ||||
2639 | /// - Has a previous instruction: PrevInst is used. | ||||
2640 | union { | ||||
2641 | Instruction *PrevInst; | ||||
2642 | BasicBlock *BB; | ||||
2643 | } Point; | ||||
2644 | |||||
2645 | /// Remember whether or not the instruction had a previous instruction. | ||||
2646 | bool HasPrevInstruction; | ||||
2647 | |||||
2648 | public: | ||||
2649 | /// Record the position of \p Inst. | ||||
2650 | InsertionHandler(Instruction *Inst) { | ||||
2651 | BasicBlock::iterator It = Inst->getIterator(); | ||||
2652 | HasPrevInstruction = (It != (Inst->getParent()->begin())); | ||||
2653 | if (HasPrevInstruction) | ||||
2654 | Point.PrevInst = &*--It; | ||||
2655 | else | ||||
2656 | Point.BB = Inst->getParent(); | ||||
2657 | } | ||||
2658 | |||||
2659 | /// Insert \p Inst at the recorded position. | ||||
2660 | void insert(Instruction *Inst) { | ||||
2661 | if (HasPrevInstruction) { | ||||
2662 | if (Inst->getParent()) | ||||
2663 | Inst->removeFromParent(); | ||||
2664 | Inst->insertAfter(Point.PrevInst); | ||||
2665 | } else { | ||||
2666 | Instruction *Position = &*Point.BB->getFirstInsertionPt(); | ||||
2667 | if (Inst->getParent()) | ||||
2668 | Inst->moveBefore(Position); | ||||
2669 | else | ||||
2670 | Inst->insertBefore(Position); | ||||
2671 | } | ||||
2672 | } | ||||
2673 | }; | ||||
2674 | |||||
2675 | /// Move an instruction before another. | ||||
2676 | class InstructionMoveBefore : public TypePromotionAction { | ||||
2677 | /// Original position of the instruction. | ||||
2678 | InsertionHandler Position; | ||||
2679 | |||||
2680 | public: | ||||
2681 | /// Move \p Inst before \p Before. | ||||
2682 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) | ||||
2683 | : TypePromotionAction(Inst), Position(Inst) { | ||||
2684 | LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Beforedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Do: move: " << * Inst << "\nbefore: " << *Before << "\n"; } } while (false) | ||||
2685 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Do: move: " << * Inst << "\nbefore: " << *Before << "\n"; } } while (false); | ||||
2686 | Inst->moveBefore(Before); | ||||
2687 | } | ||||
2688 | |||||
2689 | /// Move the instruction back to its original position. | ||||
2690 | void undo() override { | ||||
2691 | LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Undo: moveBefore: " << *Inst << "\n"; } } while (false); | ||||
2692 | Position.insert(Inst); | ||||
2693 | } | ||||
2694 | }; | ||||
2695 | |||||
2696 | /// Set the operand of an instruction with a new value. | ||||
2697 | class OperandSetter : public TypePromotionAction { | ||||
2698 | /// Original operand of the instruction. | ||||
2699 | Value *Origin; | ||||
2700 | |||||
2701 | /// Index of the modified instruction. | ||||
2702 | unsigned Idx; | ||||
2703 | |||||
2704 | public: | ||||
2705 | /// Set \p Idx operand of \p Inst with \p NewVal. | ||||
2706 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) | ||||
2707 | : TypePromotionAction(Inst), Idx(Idx) { | ||||
2708 | LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Do: setOperand: " << Idx << "\n" << "for:" << *Inst << "\n" << "with:" << *NewVal << "\n"; } } while ( false) | ||||
2709 | << "for:" << *Inst << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Do: setOperand: " << Idx << "\n" << "for:" << *Inst << "\n" << "with:" << *NewVal << "\n"; } } while ( false) | ||||
2710 | << "with:" << *NewVal << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Do: setOperand: " << Idx << "\n" << "for:" << *Inst << "\n" << "with:" << *NewVal << "\n"; } } while ( false); | ||||
2711 | Origin = Inst->getOperand(Idx); | ||||
2712 | Inst->setOperand(Idx, NewVal); | ||||
2713 | } | ||||
2714 | |||||
2715 | /// Restore the original value of the instruction. | ||||
2716 | void undo() override { | ||||
2717 | LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Undo: setOperand:" << Idx << "\n" << "for: " << *Inst << "\n" << "with: " << *Origin << "\n"; } } while ( false) | ||||
2718 | << "for: " << *Inst << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Undo: setOperand:" << Idx << "\n" << "for: " << *Inst << "\n" << "with: " << *Origin << "\n"; } } while ( false) | ||||
2719 | << "with: " << *Origin << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Undo: setOperand:" << Idx << "\n" << "for: " << *Inst << "\n" << "with: " << *Origin << "\n"; } } while ( false); | ||||
2720 | Inst->setOperand(Idx, Origin); | ||||
2721 | } | ||||
2722 | }; | ||||
2723 | |||||
2724 | /// Hide the operands of an instruction. | ||||
2725 | /// Do as if this instruction was not using any of its operands. | ||||
2726 | class OperandsHider : public TypePromotionAction { | ||||
2727 | /// The list of original operands. | ||||
2728 | SmallVector<Value *, 4> OriginalValues; | ||||
2729 | |||||
2730 | public: | ||||
2731 | /// Remove \p Inst from the uses of the operands of \p Inst. | ||||
2732 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { | ||||
2733 | LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Do: OperandsHider: " << *Inst << "\n"; } } while (false); | ||||
2734 | unsigned NumOpnds = Inst->getNumOperands(); | ||||
2735 | OriginalValues.reserve(NumOpnds); | ||||
2736 | for (unsigned It = 0; It < NumOpnds; ++It) { | ||||
2737 | // Save the current operand. | ||||
2738 | Value *Val = Inst->getOperand(It); | ||||
2739 | OriginalValues.push_back(Val); | ||||
2740 | // Set a dummy one. | ||||
2741 | // We could use OperandSetter here, but that would imply an overhead | ||||
2742 | // that we are not willing to pay. | ||||
2743 | Inst->setOperand(It, UndefValue::get(Val->getType())); | ||||
2744 | } | ||||
2745 | } | ||||
2746 | |||||
2747 | /// Restore the original list of uses. | ||||
2748 | void undo() override { | ||||
2749 | LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Undo: OperandsHider: " << *Inst << "\n"; } } while (false); | ||||
2750 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) | ||||
2751 | Inst->setOperand(It, OriginalValues[It]); | ||||
2752 | } | ||||
2753 | }; | ||||
2754 | |||||
2755 | /// Build a truncate instruction. | ||||
2756 | class TruncBuilder : public TypePromotionAction { | ||||
2757 | Value *Val; | ||||
2758 | |||||
2759 | public: | ||||
2760 | /// Build a truncate instruction of \p Opnd producing a \p Ty | ||||
2761 | /// result. | ||||
2762 | /// trunc Opnd to Ty. | ||||
2763 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { | ||||
2764 | IRBuilder<> Builder(Opnd); | ||||
2765 | Builder.SetCurrentDebugLocation(DebugLoc()); | ||||
2766 | Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); | ||||
2767 | LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Do: TruncBuilder: " << *Val << "\n"; } } while (false); | ||||
2768 | } | ||||
2769 | |||||
2770 | /// Get the built value. | ||||
2771 | Value *getBuiltValue() { return Val; } | ||||
2772 | |||||
2773 | /// Remove the built instruction. | ||||
2774 | void undo() override { | ||||
2775 | LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Undo: TruncBuilder: " << *Val << "\n"; } } while (false); | ||||
2776 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) | ||||
2777 | IVal->eraseFromParent(); | ||||
2778 | } | ||||
2779 | }; | ||||
2780 | |||||
2781 | /// Build a sign extension instruction. | ||||
2782 | class SExtBuilder : public TypePromotionAction { | ||||
2783 | Value *Val; | ||||
2784 | |||||
2785 | public: | ||||
2786 | /// Build a sign extension instruction of \p Opnd producing a \p Ty | ||||
2787 | /// result. | ||||
2788 | /// sext Opnd to Ty. | ||||
2789 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) | ||||
2790 | : TypePromotionAction(InsertPt) { | ||||
2791 | IRBuilder<> Builder(InsertPt); | ||||
2792 | Val = Builder.CreateSExt(Opnd, Ty, "promoted"); | ||||
2793 | LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Do: SExtBuilder: " << *Val << "\n"; } } while (false); | ||||
2794 | } | ||||
2795 | |||||
2796 | /// Get the built value. | ||||
2797 | Value *getBuiltValue() { return Val; } | ||||
2798 | |||||
2799 | /// Remove the built instruction. | ||||
2800 | void undo() override { | ||||
2801 | LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Undo: SExtBuilder: " << *Val << "\n"; } } while (false); | ||||
2802 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) | ||||
2803 | IVal->eraseFromParent(); | ||||
2804 | } | ||||
2805 | }; | ||||
2806 | |||||
2807 | /// Build a zero extension instruction. | ||||
2808 | class ZExtBuilder : public TypePromotionAction { | ||||
2809 | Value *Val; | ||||
2810 | |||||
2811 | public: | ||||
2812 | /// Build a zero extension instruction of \p Opnd producing a \p Ty | ||||
2813 | /// result. | ||||
2814 | /// zext Opnd to Ty. | ||||
2815 | ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) | ||||
2816 | : TypePromotionAction(InsertPt) { | ||||
2817 | IRBuilder<> Builder(InsertPt); | ||||
2818 | Builder.SetCurrentDebugLocation(DebugLoc()); | ||||
2819 | Val = Builder.CreateZExt(Opnd, Ty, "promoted"); | ||||
2820 | LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Do: ZExtBuilder: " << *Val << "\n"; } } while (false); | ||||
2821 | } | ||||
2822 | |||||
2823 | /// Get the built value. | ||||
2824 | Value *getBuiltValue() { return Val; } | ||||
2825 | |||||
2826 | /// Remove the built instruction. | ||||
2827 | void undo() override { | ||||
2828 | LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Undo: ZExtBuilder: " << *Val << "\n"; } } while (false); | ||||
2829 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) | ||||
2830 | IVal->eraseFromParent(); | ||||
2831 | } | ||||
2832 | }; | ||||
2833 | |||||
2834 | /// Mutate an instruction to another type. | ||||
2835 | class TypeMutator : public TypePromotionAction { | ||||
2836 | /// Record the original type. | ||||
2837 | Type *OrigTy; | ||||
2838 | |||||
2839 | public: | ||||
2840 | /// Mutate the type of \p Inst into \p NewTy. | ||||
2841 | TypeMutator(Instruction *Inst, Type *NewTy) | ||||
2842 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { | ||||
2843 | LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTydo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy << "\n"; } } while (false) | ||||
2844 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy << "\n"; } } while (false); | ||||
2845 | Inst->mutateType(NewTy); | ||||
2846 | } | ||||
2847 | |||||
2848 | /// Mutate the instruction back to its original type. | ||||
2849 | void undo() override { | ||||
2850 | LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTydo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy << "\n"; } } while (false) | ||||
2851 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy << "\n"; } } while (false); | ||||
2852 | Inst->mutateType(OrigTy); | ||||
2853 | } | ||||
2854 | }; | ||||
2855 | |||||
2856 | /// Replace the uses of an instruction by another instruction. | ||||
2857 | class UsesReplacer : public TypePromotionAction { | ||||
2858 | /// Helper structure to keep track of the replaced uses. | ||||
2859 | struct InstructionAndIdx { | ||||
2860 | /// The instruction using the instruction. | ||||
2861 | Instruction *Inst; | ||||
2862 | |||||
2863 | /// The index where this instruction is used for Inst. | ||||
2864 | unsigned Idx; | ||||
2865 | |||||
2866 | InstructionAndIdx(Instruction *Inst, unsigned Idx) | ||||
2867 | : Inst(Inst), Idx(Idx) {} | ||||
2868 | }; | ||||
2869 | |||||
2870 | /// Keep track of the original uses (pair Instruction, Index). | ||||
2871 | SmallVector<InstructionAndIdx, 4> OriginalUses; | ||||
2872 | /// Keep track of the debug users. | ||||
2873 | SmallVector<DbgValueInst *, 1> DbgValues; | ||||
2874 | |||||
2875 | /// Keep track of the new value so that we can undo it by replacing | ||||
2876 | /// instances of the new value with the original value. | ||||
2877 | Value *New; | ||||
2878 | |||||
2879 | using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator; | ||||
2880 | |||||
2881 | public: | ||||
2882 | /// Replace all the use of \p Inst by \p New. | ||||
2883 | UsesReplacer(Instruction *Inst, Value *New) | ||||
2884 | : TypePromotionAction(Inst), New(New) { | ||||
2885 | LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *Newdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New << "\n"; } } while (false) | ||||
2886 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New << "\n"; } } while (false); | ||||
2887 | // Record the original uses. | ||||
2888 | for (Use &U : Inst->uses()) { | ||||
2889 | Instruction *UserI = cast<Instruction>(U.getUser()); | ||||
2890 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); | ||||
2891 | } | ||||
2892 | // Record the debug uses separately. They are not in the instruction's | ||||
2893 | // use list, but they are replaced by RAUW. | ||||
2894 | findDbgValues(DbgValues, Inst); | ||||
2895 | |||||
2896 | // Now, we can replace the uses. | ||||
2897 | Inst->replaceAllUsesWith(New); | ||||
2898 | } | ||||
2899 | |||||
2900 | /// Reassign the original uses of Inst to Inst. | ||||
2901 | void undo() override { | ||||
2902 | LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"; } } while (false); | ||||
2903 | for (InstructionAndIdx &Use : OriginalUses) | ||||
2904 | Use.Inst->setOperand(Use.Idx, Inst); | ||||
2905 | // RAUW has replaced all original uses with references to the new value, | ||||
2906 | // including the debug uses. Since we are undoing the replacements, | ||||
2907 | // the original debug uses must also be reinstated to maintain the | ||||
2908 | // correctness and utility of debug value instructions. | ||||
2909 | for (auto *DVI : DbgValues) | ||||
2910 | DVI->replaceVariableLocationOp(New, Inst); | ||||
2911 | } | ||||
2912 | }; | ||||
2913 | |||||
2914 | /// Remove an instruction from the IR. | ||||
2915 | class InstructionRemover : public TypePromotionAction { | ||||
2916 | /// Original position of the instruction. | ||||
2917 | InsertionHandler Inserter; | ||||
2918 | |||||
2919 | /// Helper structure to hide all the link to the instruction. In other | ||||
2920 | /// words, this helps to do as if the instruction was removed. | ||||
2921 | OperandsHider Hider; | ||||
2922 | |||||
2923 | /// Keep track of the uses replaced, if any. | ||||
2924 | UsesReplacer *Replacer = nullptr; | ||||
2925 | |||||
2926 | /// Keep track of instructions removed. | ||||
2927 | SetOfInstrs &RemovedInsts; | ||||
2928 | |||||
2929 | public: | ||||
2930 | /// Remove all reference of \p Inst and optionally replace all its | ||||
2931 | /// uses with New. | ||||
2932 | /// \p RemovedInsts Keep track of the instructions removed by this Action. | ||||
2933 | /// \pre If !Inst->use_empty(), then New != nullptr | ||||
2934 | InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts, | ||||
2935 | Value *New = nullptr) | ||||
2936 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), | ||||
2937 | RemovedInsts(RemovedInsts) { | ||||
2938 | if (New) | ||||
2939 | Replacer = new UsesReplacer(Inst, New); | ||||
2940 | LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Do: InstructionRemover: " << *Inst << "\n"; } } while (false); | ||||
2941 | RemovedInsts.insert(Inst); | ||||
2942 | /// The instructions removed here will be freed after completing | ||||
2943 | /// optimizeBlock() for all blocks as we need to keep track of the | ||||
2944 | /// removed instructions during promotion. | ||||
2945 | Inst->removeFromParent(); | ||||
2946 | } | ||||
2947 | |||||
2948 | ~InstructionRemover() override { delete Replacer; } | ||||
2949 | |||||
2950 | /// Resurrect the instruction and reassign it to the proper uses if | ||||
2951 | /// new value was provided when build this action. | ||||
2952 | void undo() override { | ||||
2953 | LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"; } } while (false); | ||||
2954 | Inserter.insert(Inst); | ||||
2955 | if (Replacer) | ||||
2956 | Replacer->undo(); | ||||
2957 | Hider.undo(); | ||||
2958 | RemovedInsts.erase(Inst); | ||||
2959 | } | ||||
2960 | }; | ||||
2961 | |||||
2962 | public: | ||||
2963 | /// Restoration point. | ||||
2964 | /// The restoration point is a pointer to an action instead of an iterator | ||||
2965 | /// because the iterator may be invalidated but not the pointer. | ||||
2966 | using ConstRestorationPt = const TypePromotionAction *; | ||||
2967 | |||||
2968 | TypePromotionTransaction(SetOfInstrs &RemovedInsts) | ||||
2969 | : RemovedInsts(RemovedInsts) {} | ||||
2970 | |||||
2971 | /// Advocate every changes made in that transaction. Return true if any change | ||||
2972 | /// happen. | ||||
2973 | bool commit(); | ||||
2974 | |||||
2975 | /// Undo all the changes made after the given point. | ||||
2976 | void rollback(ConstRestorationPt Point); | ||||
2977 | |||||
2978 | /// Get the current restoration point. | ||||
2979 | ConstRestorationPt getRestorationPoint() const; | ||||
2980 | |||||
2981 | /// \name API for IR modification with state keeping to support rollback. | ||||
2982 | /// @{ | ||||
2983 | /// Same as Instruction::setOperand. | ||||
2984 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); | ||||
2985 | |||||
2986 | /// Same as Instruction::eraseFromParent. | ||||
2987 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); | ||||
2988 | |||||
2989 | /// Same as Value::replaceAllUsesWith. | ||||
2990 | void replaceAllUsesWith(Instruction *Inst, Value *New); | ||||
2991 | |||||
2992 | /// Same as Value::mutateType. | ||||
2993 | void mutateType(Instruction *Inst, Type *NewTy); | ||||
2994 | |||||
2995 | /// Same as IRBuilder::createTrunc. | ||||
2996 | Value *createTrunc(Instruction *Opnd, Type *Ty); | ||||
2997 | |||||
2998 | /// Same as IRBuilder::createSExt. | ||||
2999 | Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); | ||||
3000 | |||||
3001 | /// Same as IRBuilder::createZExt. | ||||
3002 | Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); | ||||
3003 | |||||
3004 | /// Same as Instruction::moveBefore. | ||||
3005 | void moveBefore(Instruction *Inst, Instruction *Before); | ||||
3006 | /// @} | ||||
3007 | |||||
3008 | private: | ||||
3009 | /// The ordered list of actions made so far. | ||||
3010 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; | ||||
3011 | |||||
3012 | using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator; | ||||
3013 | |||||
3014 | SetOfInstrs &RemovedInsts; | ||||
3015 | }; | ||||
3016 | |||||
3017 | } // end anonymous namespace | ||||
3018 | |||||
3019 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, | ||||
3020 | Value *NewVal) { | ||||
3021 | Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>( | ||||
3022 | Inst, Idx, NewVal)); | ||||
3023 | } | ||||
3024 | |||||
3025 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, | ||||
3026 | Value *NewVal) { | ||||
3027 | Actions.push_back( | ||||
3028 | std::make_unique<TypePromotionTransaction::InstructionRemover>( | ||||
3029 | Inst, RemovedInsts, NewVal)); | ||||
3030 | } | ||||
3031 | |||||
3032 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, | ||||
3033 | Value *New) { | ||||
3034 | Actions.push_back( | ||||
3035 | std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); | ||||
3036 | } | ||||
3037 | |||||
3038 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { | ||||
3039 | Actions.push_back( | ||||
3040 | std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); | ||||
3041 | } | ||||
3042 | |||||
3043 | Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, | ||||
3044 | Type *Ty) { | ||||
3045 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); | ||||
3046 | Value *Val = Ptr->getBuiltValue(); | ||||
3047 | Actions.push_back(std::move(Ptr)); | ||||
3048 | return Val; | ||||
3049 | } | ||||
3050 | |||||
3051 | Value *TypePromotionTransaction::createSExt(Instruction *Inst, | ||||
3052 | Value *Opnd, Type *Ty) { | ||||
3053 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); | ||||
3054 | Value *Val = Ptr->getBuiltValue(); | ||||
3055 | Actions.push_back(std::move(Ptr)); | ||||
3056 | return Val; | ||||
3057 | } | ||||
3058 | |||||
3059 | Value *TypePromotionTransaction::createZExt(Instruction *Inst, | ||||
3060 | Value *Opnd, Type *Ty) { | ||||
3061 | std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); | ||||
3062 | Value *Val = Ptr->getBuiltValue(); | ||||
3063 | Actions.push_back(std::move(Ptr)); | ||||
3064 | return Val; | ||||
3065 | } | ||||
3066 | |||||
3067 | void TypePromotionTransaction::moveBefore(Instruction *Inst, | ||||
3068 | Instruction *Before) { | ||||
3069 | Actions.push_back( | ||||
3070 | std::make_unique<TypePromotionTransaction::InstructionMoveBefore>( | ||||
3071 | Inst, Before)); | ||||
3072 | } | ||||
3073 | |||||
3074 | TypePromotionTransaction::ConstRestorationPt | ||||
3075 | TypePromotionTransaction::getRestorationPoint() const { | ||||
3076 | return !Actions.empty() ? Actions.back().get() : nullptr; | ||||
3077 | } | ||||
3078 | |||||
3079 | bool TypePromotionTransaction::commit() { | ||||
3080 | for (std::unique_ptr<TypePromotionAction> &Action : Actions) | ||||
3081 | Action->commit(); | ||||
3082 | bool Modified = !Actions.empty(); | ||||
3083 | Actions.clear(); | ||||
3084 | return Modified; | ||||
3085 | } | ||||
3086 | |||||
3087 | void TypePromotionTransaction::rollback( | ||||
3088 | TypePromotionTransaction::ConstRestorationPt Point) { | ||||
3089 | while (!Actions.empty() && Point != Actions.back().get()) { | ||||
3090 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); | ||||
3091 | Curr->undo(); | ||||
3092 | } | ||||
3093 | } | ||||
3094 | |||||
3095 | namespace { | ||||
3096 | |||||
3097 | /// A helper class for matching addressing modes. | ||||
3098 | /// | ||||
3099 | /// This encapsulates the logic for matching the target-legal addressing modes. | ||||
3100 | class AddressingModeMatcher { | ||||
3101 | SmallVectorImpl<Instruction*> &AddrModeInsts; | ||||
3102 | const TargetLowering &TLI; | ||||
3103 | const TargetRegisterInfo &TRI; | ||||
3104 | const DataLayout &DL; | ||||
3105 | const LoopInfo &LI; | ||||
3106 | const std::function<const DominatorTree &()> getDTFn; | ||||
3107 | |||||
3108 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and | ||||
3109 | /// the memory instruction that we're computing this address for. | ||||
3110 | Type *AccessTy; | ||||
3111 | unsigned AddrSpace; | ||||
3112 | Instruction *MemoryInst; | ||||
3113 | |||||
3114 | /// This is the addressing mode that we're building up. This is | ||||
3115 | /// part of the return value of this addressing mode matching stuff. | ||||
3116 | ExtAddrMode &AddrMode; | ||||
3117 | |||||
3118 | /// The instructions inserted by other CodeGenPrepare optimizations. | ||||
3119 | const SetOfInstrs &InsertedInsts; | ||||
3120 | |||||
3121 | /// A map from the instructions to their type before promotion. | ||||
3122 | InstrToOrigTy &PromotedInsts; | ||||
3123 | |||||
3124 | /// The ongoing transaction where every action should be registered. | ||||
3125 | TypePromotionTransaction &TPT; | ||||
3126 | |||||
3127 | // A GEP which has too large offset to be folded into the addressing mode. | ||||
3128 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP; | ||||
3129 | |||||
3130 | /// This is set to true when we should not do profitability checks. | ||||
3131 | /// When true, IsProfitableToFoldIntoAddressingMode always returns true. | ||||
3132 | bool IgnoreProfitability; | ||||
3133 | |||||
3134 | /// True if we are optimizing for size. | ||||
3135 | bool OptSize; | ||||
3136 | |||||
3137 | ProfileSummaryInfo *PSI; | ||||
3138 | BlockFrequencyInfo *BFI; | ||||
3139 | |||||
3140 | AddressingModeMatcher( | ||||
3141 | SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI, | ||||
3142 | const TargetRegisterInfo &TRI, const LoopInfo &LI, | ||||
3143 | const std::function<const DominatorTree &()> getDTFn, | ||||
3144 | Type *AT, unsigned AS, Instruction *MI, ExtAddrMode &AM, | ||||
3145 | const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts, | ||||
3146 | TypePromotionTransaction &TPT, | ||||
3147 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP, | ||||
3148 | bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) | ||||
3149 | : AddrModeInsts(AMI), TLI(TLI), TRI(TRI), | ||||
3150 | DL(MI->getModule()->getDataLayout()), LI(LI), getDTFn(getDTFn), | ||||
3151 | AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM), | ||||
3152 | InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT), | ||||
3153 | LargeOffsetGEP(LargeOffsetGEP), OptSize(OptSize), PSI(PSI), BFI(BFI) { | ||||
3154 | IgnoreProfitability = false; | ||||
3155 | } | ||||
3156 | |||||
3157 | public: | ||||
3158 | /// Find the maximal addressing mode that a load/store of V can fold, | ||||
3159 | /// give an access type of AccessTy. This returns a list of involved | ||||
3160 | /// instructions in AddrModeInsts. | ||||
3161 | /// \p InsertedInsts The instructions inserted by other CodeGenPrepare | ||||
3162 | /// optimizations. | ||||
3163 | /// \p PromotedInsts maps the instructions to their type before promotion. | ||||
3164 | /// \p The ongoing transaction where every action should be registered. | ||||
3165 | static ExtAddrMode | ||||
3166 | Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst, | ||||
3167 | SmallVectorImpl<Instruction *> &AddrModeInsts, | ||||
3168 | const TargetLowering &TLI, const LoopInfo &LI, | ||||
3169 | const std::function<const DominatorTree &()> getDTFn, | ||||
3170 | const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts, | ||||
3171 | InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT, | ||||
3172 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP, | ||||
3173 | bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) { | ||||
3174 | ExtAddrMode Result; | ||||
3175 | |||||
3176 | bool Success = AddressingModeMatcher( | ||||
3177 | AddrModeInsts, TLI, TRI, LI, getDTFn, AccessTy, AS, MemoryInst, Result, | ||||
3178 | InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI, | ||||
3179 | BFI).matchAddr(V, 0); | ||||
3180 | (void)Success; assert(Success && "Couldn't select *anything*?")(static_cast <bool> (Success && "Couldn't select *anything*?" ) ? void (0) : __assert_fail ("Success && \"Couldn't select *anything*?\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3180, __extension__ __PRETTY_FUNCTION__ )); | ||||
3181 | return Result; | ||||
3182 | } | ||||
3183 | |||||
3184 | private: | ||||
3185 | bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); | ||||
3186 | bool matchAddr(Value *Addr, unsigned Depth); | ||||
3187 | bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth, | ||||
3188 | bool *MovedAway = nullptr); | ||||
3189 | bool isProfitableToFoldIntoAddressingMode(Instruction *I, | ||||
3190 | ExtAddrMode &AMBefore, | ||||
3191 | ExtAddrMode &AMAfter); | ||||
3192 | bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); | ||||
3193 | bool isPromotionProfitable(unsigned NewCost, unsigned OldCost, | ||||
3194 | Value *PromotedOperand) const; | ||||
3195 | }; | ||||
3196 | |||||
3197 | class PhiNodeSet; | ||||
3198 | |||||
3199 | /// An iterator for PhiNodeSet. | ||||
3200 | class PhiNodeSetIterator { | ||||
3201 | PhiNodeSet * const Set; | ||||
3202 | size_t CurrentIndex = 0; | ||||
3203 | |||||
3204 | public: | ||||
3205 | /// The constructor. Start should point to either a valid element, or be equal | ||||
3206 | /// to the size of the underlying SmallVector of the PhiNodeSet. | ||||
3207 | PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start); | ||||
3208 | PHINode * operator*() const; | ||||
3209 | PhiNodeSetIterator& operator++(); | ||||
3210 | bool operator==(const PhiNodeSetIterator &RHS) const; | ||||
3211 | bool operator!=(const PhiNodeSetIterator &RHS) const; | ||||
3212 | }; | ||||
3213 | |||||
3214 | /// Keeps a set of PHINodes. | ||||
3215 | /// | ||||
3216 | /// This is a minimal set implementation for a specific use case: | ||||
3217 | /// It is very fast when there are very few elements, but also provides good | ||||
3218 | /// performance when there are many. It is similar to SmallPtrSet, but also | ||||
3219 | /// provides iteration by insertion order, which is deterministic and stable | ||||
3220 | /// across runs. It is also similar to SmallSetVector, but provides removing | ||||
3221 | /// elements in O(1) time. This is achieved by not actually removing the element | ||||
3222 | /// from the underlying vector, so comes at the cost of using more memory, but | ||||
3223 | /// that is fine, since PhiNodeSets are used as short lived objects. | ||||
3224 | class PhiNodeSet { | ||||
3225 | friend class PhiNodeSetIterator; | ||||
3226 | |||||
3227 | using MapType = SmallDenseMap<PHINode *, size_t, 32>; | ||||
3228 | using iterator = PhiNodeSetIterator; | ||||
3229 | |||||
3230 | /// Keeps the elements in the order of their insertion in the underlying | ||||
3231 | /// vector. To achieve constant time removal, it never deletes any element. | ||||
3232 | SmallVector<PHINode *, 32> NodeList; | ||||
3233 | |||||
3234 | /// Keeps the elements in the underlying set implementation. This (and not the | ||||
3235 | /// NodeList defined above) is the source of truth on whether an element | ||||
3236 | /// is actually in the collection. | ||||
3237 | MapType NodeMap; | ||||
3238 | |||||
3239 | /// Points to the first valid (not deleted) element when the set is not empty | ||||
3240 | /// and the value is not zero. Equals to the size of the underlying vector | ||||
3241 | /// when the set is empty. When the value is 0, as in the beginning, the | ||||
3242 | /// first element may or may not be valid. | ||||
3243 | size_t FirstValidElement = 0; | ||||
3244 | |||||
3245 | public: | ||||
3246 | /// Inserts a new element to the collection. | ||||
3247 | /// \returns true if the element is actually added, i.e. was not in the | ||||
3248 | /// collection before the operation. | ||||
3249 | bool insert(PHINode *Ptr) { | ||||
3250 | if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) { | ||||
3251 | NodeList.push_back(Ptr); | ||||
3252 | return true; | ||||
3253 | } | ||||
3254 | return false; | ||||
3255 | } | ||||
3256 | |||||
3257 | /// Removes the element from the collection. | ||||
3258 | /// \returns whether the element is actually removed, i.e. was in the | ||||
3259 | /// collection before the operation. | ||||
3260 | bool erase(PHINode *Ptr) { | ||||
3261 | if (NodeMap.erase(Ptr)) { | ||||
3262 | SkipRemovedElements(FirstValidElement); | ||||
3263 | return true; | ||||
3264 | } | ||||
3265 | return false; | ||||
3266 | } | ||||
3267 | |||||
3268 | /// Removes all elements and clears the collection. | ||||
3269 | void clear() { | ||||
3270 | NodeMap.clear(); | ||||
3271 | NodeList.clear(); | ||||
3272 | FirstValidElement = 0; | ||||
3273 | } | ||||
3274 | |||||
3275 | /// \returns an iterator that will iterate the elements in the order of | ||||
3276 | /// insertion. | ||||
3277 | iterator begin() { | ||||
3278 | if (FirstValidElement == 0) | ||||
3279 | SkipRemovedElements(FirstValidElement); | ||||
3280 | return PhiNodeSetIterator(this, FirstValidElement); | ||||
3281 | } | ||||
3282 | |||||
3283 | /// \returns an iterator that points to the end of the collection. | ||||
3284 | iterator end() { return PhiNodeSetIterator(this, NodeList.size()); } | ||||
3285 | |||||
3286 | /// Returns the number of elements in the collection. | ||||
3287 | size_t size() const { | ||||
3288 | return NodeMap.size(); | ||||
3289 | } | ||||
3290 | |||||
3291 | /// \returns 1 if the given element is in the collection, and 0 if otherwise. | ||||
3292 | size_t count(PHINode *Ptr) const { | ||||
3293 | return NodeMap.count(Ptr); | ||||
3294 | } | ||||
3295 | |||||
3296 | private: | ||||
3297 | /// Updates the CurrentIndex so that it will point to a valid element. | ||||
3298 | /// | ||||
3299 | /// If the element of NodeList at CurrentIndex is valid, it does not | ||||
3300 | /// change it. If there are no more valid elements, it updates CurrentIndex | ||||
3301 | /// to point to the end of the NodeList. | ||||
3302 | void SkipRemovedElements(size_t &CurrentIndex) { | ||||
3303 | while (CurrentIndex < NodeList.size()) { | ||||
3304 | auto it = NodeMap.find(NodeList[CurrentIndex]); | ||||
3305 | // If the element has been deleted and added again later, NodeMap will | ||||
3306 | // point to a different index, so CurrentIndex will still be invalid. | ||||
3307 | if (it != NodeMap.end() && it->second == CurrentIndex) | ||||
3308 | break; | ||||
3309 | ++CurrentIndex; | ||||
3310 | } | ||||
3311 | } | ||||
3312 | }; | ||||
3313 | |||||
3314 | PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start) | ||||
3315 | : Set(Set), CurrentIndex(Start) {} | ||||
3316 | |||||
3317 | PHINode * PhiNodeSetIterator::operator*() const { | ||||
3318 | assert(CurrentIndex < Set->NodeList.size() &&(static_cast <bool> (CurrentIndex < Set->NodeList .size() && "PhiNodeSet access out of range") ? void ( 0) : __assert_fail ("CurrentIndex < Set->NodeList.size() && \"PhiNodeSet access out of range\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3319, __extension__ __PRETTY_FUNCTION__ )) | ||||
3319 | "PhiNodeSet access out of range")(static_cast <bool> (CurrentIndex < Set->NodeList .size() && "PhiNodeSet access out of range") ? void ( 0) : __assert_fail ("CurrentIndex < Set->NodeList.size() && \"PhiNodeSet access out of range\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3319, __extension__ __PRETTY_FUNCTION__ )); | ||||
3320 | return Set->NodeList[CurrentIndex]; | ||||
3321 | } | ||||
3322 | |||||
3323 | PhiNodeSetIterator& PhiNodeSetIterator::operator++() { | ||||
3324 | assert(CurrentIndex < Set->NodeList.size() &&(static_cast <bool> (CurrentIndex < Set->NodeList .size() && "PhiNodeSet access out of range") ? void ( 0) : __assert_fail ("CurrentIndex < Set->NodeList.size() && \"PhiNodeSet access out of range\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3325, __extension__ __PRETTY_FUNCTION__ )) | ||||
3325 | "PhiNodeSet access out of range")(static_cast <bool> (CurrentIndex < Set->NodeList .size() && "PhiNodeSet access out of range") ? void ( 0) : __assert_fail ("CurrentIndex < Set->NodeList.size() && \"PhiNodeSet access out of range\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3325, __extension__ __PRETTY_FUNCTION__ )); | ||||
3326 | ++CurrentIndex; | ||||
3327 | Set->SkipRemovedElements(CurrentIndex); | ||||
3328 | return *this; | ||||
3329 | } | ||||
3330 | |||||
3331 | bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const { | ||||
3332 | return CurrentIndex == RHS.CurrentIndex; | ||||
3333 | } | ||||
3334 | |||||
3335 | bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const { | ||||
3336 | return !((*this) == RHS); | ||||
3337 | } | ||||
3338 | |||||
3339 | /// Keep track of simplification of Phi nodes. | ||||
3340 | /// Accept the set of all phi nodes and erase phi node from this set | ||||
3341 | /// if it is simplified. | ||||
3342 | class SimplificationTracker { | ||||
3343 | DenseMap<Value *, Value *> Storage; | ||||
3344 | const SimplifyQuery &SQ; | ||||
3345 | // Tracks newly created Phi nodes. The elements are iterated by insertion | ||||
3346 | // order. | ||||
3347 | PhiNodeSet AllPhiNodes; | ||||
3348 | // Tracks newly created Select nodes. | ||||
3349 | SmallPtrSet<SelectInst *, 32> AllSelectNodes; | ||||
3350 | |||||
3351 | public: | ||||
3352 | SimplificationTracker(const SimplifyQuery &sq) | ||||
3353 | : SQ(sq) {} | ||||
3354 | |||||
3355 | Value *Get(Value *V) { | ||||
3356 | do { | ||||
3357 | auto SV = Storage.find(V); | ||||
3358 | if (SV == Storage.end()) | ||||
3359 | return V; | ||||
3360 | V = SV->second; | ||||
3361 | } while (true); | ||||
3362 | } | ||||
3363 | |||||
3364 | Value *Simplify(Value *Val) { | ||||
3365 | SmallVector<Value *, 32> WorkList; | ||||
3366 | SmallPtrSet<Value *, 32> Visited; | ||||
3367 | WorkList.push_back(Val); | ||||
3368 | while (!WorkList.empty()) { | ||||
3369 | auto *P = WorkList.pop_back_val(); | ||||
3370 | if (!Visited.insert(P).second) | ||||
3371 | continue; | ||||
3372 | if (auto *PI = dyn_cast<Instruction>(P)) | ||||
3373 | if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) { | ||||
3374 | for (auto *U : PI->users()) | ||||
3375 | WorkList.push_back(cast<Value>(U)); | ||||
3376 | Put(PI, V); | ||||
3377 | PI->replaceAllUsesWith(V); | ||||
3378 | if (auto *PHI = dyn_cast<PHINode>(PI)) | ||||
3379 | AllPhiNodes.erase(PHI); | ||||
3380 | if (auto *Select = dyn_cast<SelectInst>(PI)) | ||||
3381 | AllSelectNodes.erase(Select); | ||||
3382 | PI->eraseFromParent(); | ||||
3383 | } | ||||
3384 | } | ||||
3385 | return Get(Val); | ||||
3386 | } | ||||
3387 | |||||
3388 | void Put(Value *From, Value *To) { | ||||
3389 | Storage.insert({ From, To }); | ||||
3390 | } | ||||
3391 | |||||
3392 | void ReplacePhi(PHINode *From, PHINode *To) { | ||||
3393 | Value* OldReplacement = Get(From); | ||||
3394 | while (OldReplacement != From) { | ||||
3395 | From = To; | ||||
3396 | To = dyn_cast<PHINode>(OldReplacement); | ||||
3397 | OldReplacement = Get(From); | ||||
3398 | } | ||||
3399 | assert(To && Get(To) == To && "Replacement PHI node is already replaced.")(static_cast <bool> (To && Get(To) == To && "Replacement PHI node is already replaced.") ? void (0) : __assert_fail ("To && Get(To) == To && \"Replacement PHI node is already replaced.\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3399, __extension__ __PRETTY_FUNCTION__ )); | ||||
3400 | Put(From, To); | ||||
3401 | From->replaceAllUsesWith(To); | ||||
3402 | AllPhiNodes.erase(From); | ||||
3403 | From->eraseFromParent(); | ||||
3404 | } | ||||
3405 | |||||
3406 | PhiNodeSet& newPhiNodes() { return AllPhiNodes; } | ||||
3407 | |||||
3408 | void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); } | ||||
3409 | |||||
3410 | void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); } | ||||
3411 | |||||
3412 | unsigned countNewPhiNodes() const { return AllPhiNodes.size(); } | ||||
3413 | |||||
3414 | unsigned countNewSelectNodes() const { return AllSelectNodes.size(); } | ||||
3415 | |||||
3416 | void destroyNewNodes(Type *CommonType) { | ||||
3417 | // For safe erasing, replace the uses with dummy value first. | ||||
3418 | auto *Dummy = UndefValue::get(CommonType); | ||||
3419 | for (auto *I : AllPhiNodes) { | ||||
3420 | I->replaceAllUsesWith(Dummy); | ||||
3421 | I->eraseFromParent(); | ||||
3422 | } | ||||
3423 | AllPhiNodes.clear(); | ||||
3424 | for (auto *I : AllSelectNodes) { | ||||
3425 | I->replaceAllUsesWith(Dummy); | ||||
3426 | I->eraseFromParent(); | ||||
3427 | } | ||||
3428 | AllSelectNodes.clear(); | ||||
3429 | } | ||||
3430 | }; | ||||
3431 | |||||
3432 | /// A helper class for combining addressing modes. | ||||
3433 | class AddressingModeCombiner { | ||||
3434 | typedef DenseMap<Value *, Value *> FoldAddrToValueMapping; | ||||
3435 | typedef std::pair<PHINode *, PHINode *> PHIPair; | ||||
3436 | |||||
3437 | private: | ||||
3438 | /// The addressing modes we've collected. | ||||
3439 | SmallVector<ExtAddrMode, 16> AddrModes; | ||||
3440 | |||||
3441 | /// The field in which the AddrModes differ, when we have more than one. | ||||
3442 | ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField; | ||||
3443 | |||||
3444 | /// Are the AddrModes that we have all just equal to their original values? | ||||
3445 | bool AllAddrModesTrivial = true; | ||||
3446 | |||||
3447 | /// Common Type for all different fields in addressing modes. | ||||
3448 | Type *CommonType = nullptr; | ||||
3449 | |||||
3450 | /// SimplifyQuery for simplifyInstruction utility. | ||||
3451 | const SimplifyQuery &SQ; | ||||
3452 | |||||
3453 | /// Original Address. | ||||
3454 | Value *Original; | ||||
3455 | |||||
3456 | public: | ||||
3457 | AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue) | ||||
3458 | : SQ(_SQ), Original(OriginalValue) {} | ||||
3459 | |||||
3460 | /// Get the combined AddrMode | ||||
3461 | const ExtAddrMode &getAddrMode() const { | ||||
3462 | return AddrModes[0]; | ||||
3463 | } | ||||
3464 | |||||
3465 | /// Add a new AddrMode if it's compatible with the AddrModes we already | ||||
3466 | /// have. | ||||
3467 | /// \return True iff we succeeded in doing so. | ||||
3468 | bool addNewAddrMode(ExtAddrMode &NewAddrMode) { | ||||
3469 | // Take note of if we have any non-trivial AddrModes, as we need to detect | ||||
3470 | // when all AddrModes are trivial as then we would introduce a phi or select | ||||
3471 | // which just duplicates what's already there. | ||||
3472 | AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial(); | ||||
3473 | |||||
3474 | // If this is the first addrmode then everything is fine. | ||||
3475 | if (AddrModes.empty()) { | ||||
3476 | AddrModes.emplace_back(NewAddrMode); | ||||
3477 | return true; | ||||
3478 | } | ||||
3479 | |||||
3480 | // Figure out how different this is from the other address modes, which we | ||||
3481 | // can do just by comparing against the first one given that we only care | ||||
3482 | // about the cumulative difference. | ||||
3483 | ExtAddrMode::FieldName ThisDifferentField = | ||||
3484 | AddrModes[0].compare(NewAddrMode); | ||||
3485 | if (DifferentField == ExtAddrMode::NoField) | ||||
3486 | DifferentField = ThisDifferentField; | ||||
3487 | else if (DifferentField != ThisDifferentField) | ||||
3488 | DifferentField = ExtAddrMode::MultipleFields; | ||||
3489 | |||||
3490 | // If NewAddrMode differs in more than one dimension we cannot handle it. | ||||
3491 | bool CanHandle = DifferentField != ExtAddrMode::MultipleFields; | ||||
3492 | |||||
3493 | // If Scale Field is different then we reject. | ||||
3494 | CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField; | ||||
3495 | |||||
3496 | // We also must reject the case when base offset is different and | ||||
3497 | // scale reg is not null, we cannot handle this case due to merge of | ||||
3498 | // different offsets will be used as ScaleReg. | ||||
3499 | CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField || | ||||
3500 | !NewAddrMode.ScaledReg); | ||||
3501 | |||||
3502 | // We also must reject the case when GV is different and BaseReg installed | ||||
3503 | // due to we want to use base reg as a merge of GV values. | ||||
3504 | CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField || | ||||
3505 | !NewAddrMode.HasBaseReg); | ||||
3506 | |||||
3507 | // Even if NewAddMode is the same we still need to collect it due to | ||||
3508 | // original value is different. And later we will need all original values | ||||
3509 | // as anchors during finding the common Phi node. | ||||
3510 | if (CanHandle) | ||||
3511 | AddrModes.emplace_back(NewAddrMode); | ||||
3512 | else | ||||
3513 | AddrModes.clear(); | ||||
3514 | |||||
3515 | return CanHandle; | ||||
3516 | } | ||||
3517 | |||||
3518 | /// Combine the addressing modes we've collected into a single | ||||
3519 | /// addressing mode. | ||||
3520 | /// \return True iff we successfully combined them or we only had one so | ||||
3521 | /// didn't need to combine them anyway. | ||||
3522 | bool combineAddrModes() { | ||||
3523 | // If we have no AddrModes then they can't be combined. | ||||
3524 | if (AddrModes.size() == 0) | ||||
3525 | return false; | ||||
3526 | |||||
3527 | // A single AddrMode can trivially be combined. | ||||
3528 | if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField) | ||||
3529 | return true; | ||||
3530 | |||||
3531 | // If the AddrModes we collected are all just equal to the value they are | ||||
3532 | // derived from then combining them wouldn't do anything useful. | ||||
3533 | if (AllAddrModesTrivial) | ||||
3534 | return false; | ||||
3535 | |||||
3536 | if (!addrModeCombiningAllowed()) | ||||
3537 | return false; | ||||
3538 | |||||
3539 | // Build a map between <original value, basic block where we saw it> to | ||||
3540 | // value of base register. | ||||
3541 | // Bail out if there is no common type. | ||||
3542 | FoldAddrToValueMapping Map; | ||||
3543 | if (!initializeMap(Map)) | ||||
3544 | return false; | ||||
3545 | |||||
3546 | Value *CommonValue = findCommon(Map); | ||||
3547 | if (CommonValue) | ||||
3548 | AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes); | ||||
3549 | return CommonValue != nullptr; | ||||
3550 | } | ||||
3551 | |||||
3552 | private: | ||||
3553 | /// Initialize Map with anchor values. For address seen | ||||
3554 | /// we set the value of different field saw in this address. | ||||
3555 | /// At the same time we find a common type for different field we will | ||||
3556 | /// use to create new Phi/Select nodes. Keep it in CommonType field. | ||||
3557 | /// Return false if there is no common type found. | ||||
3558 | bool initializeMap(FoldAddrToValueMapping &Map) { | ||||
3559 | // Keep track of keys where the value is null. We will need to replace it | ||||
3560 | // with constant null when we know the common type. | ||||
3561 | SmallVector<Value *, 2> NullValue; | ||||
3562 | Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType()); | ||||
3563 | for (auto &AM : AddrModes) { | ||||
3564 | Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy); | ||||
3565 | if (DV) { | ||||
3566 | auto *Type = DV->getType(); | ||||
3567 | if (CommonType && CommonType != Type) | ||||
3568 | return false; | ||||
3569 | CommonType = Type; | ||||
3570 | Map[AM.OriginalValue] = DV; | ||||
3571 | } else { | ||||
3572 | NullValue.push_back(AM.OriginalValue); | ||||
3573 | } | ||||
3574 | } | ||||
3575 | assert(CommonType && "At least one non-null value must be!")(static_cast <bool> (CommonType && "At least one non-null value must be!" ) ? void (0) : __assert_fail ("CommonType && \"At least one non-null value must be!\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3575, __extension__ __PRETTY_FUNCTION__ )); | ||||
3576 | for (auto *V : NullValue) | ||||
3577 | Map[V] = Constant::getNullValue(CommonType); | ||||
3578 | return true; | ||||
3579 | } | ||||
3580 | |||||
3581 | /// We have mapping between value A and other value B where B was a field in | ||||
3582 | /// addressing mode represented by A. Also we have an original value C | ||||
3583 | /// representing an address we start with. Traversing from C through phi and | ||||
3584 | /// selects we ended up with A's in a map. This utility function tries to find | ||||
3585 | /// a value V which is a field in addressing mode C and traversing through phi | ||||
3586 | /// nodes and selects we will end up in corresponded values B in a map. | ||||
3587 | /// The utility will create a new Phi/Selects if needed. | ||||
3588 | // The simple example looks as follows: | ||||
3589 | // BB1: | ||||
3590 | // p1 = b1 + 40 | ||||
3591 | // br cond BB2, BB3 | ||||
3592 | // BB2: | ||||
3593 | // p2 = b2 + 40 | ||||
3594 | // br BB3 | ||||
3595 | // BB3: | ||||
3596 | // p = phi [p1, BB1], [p2, BB2] | ||||
3597 | // v = load p | ||||
3598 | // Map is | ||||
3599 | // p1 -> b1 | ||||
3600 | // p2 -> b2 | ||||
3601 | // Request is | ||||
3602 | // p -> ? | ||||
3603 | // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3. | ||||
3604 | Value *findCommon(FoldAddrToValueMapping &Map) { | ||||
3605 | // Tracks the simplification of newly created phi nodes. The reason we use | ||||
3606 | // this mapping is because we will add new created Phi nodes in AddrToBase. | ||||
3607 | // Simplification of Phi nodes is recursive, so some Phi node may | ||||
3608 | // be simplified after we added it to AddrToBase. In reality this | ||||
3609 | // simplification is possible only if original phi/selects were not | ||||
3610 | // simplified yet. | ||||
3611 | // Using this mapping we can find the current value in AddrToBase. | ||||
3612 | SimplificationTracker ST(SQ); | ||||
3613 | |||||
3614 | // First step, DFS to create PHI nodes for all intermediate blocks. | ||||
3615 | // Also fill traverse order for the second step. | ||||
3616 | SmallVector<Value *, 32> TraverseOrder; | ||||
3617 | InsertPlaceholders(Map, TraverseOrder, ST); | ||||
3618 | |||||
3619 | // Second Step, fill new nodes by merged values and simplify if possible. | ||||
3620 | FillPlaceholders(Map, TraverseOrder, ST); | ||||
3621 | |||||
3622 | if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) { | ||||
3623 | ST.destroyNewNodes(CommonType); | ||||
3624 | return nullptr; | ||||
3625 | } | ||||
3626 | |||||
3627 | // Now we'd like to match New Phi nodes to existed ones. | ||||
3628 | unsigned PhiNotMatchedCount = 0; | ||||
3629 | if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) { | ||||
3630 | ST.destroyNewNodes(CommonType); | ||||
3631 | return nullptr; | ||||
3632 | } | ||||
3633 | |||||
3634 | auto *Result = ST.Get(Map.find(Original)->second); | ||||
3635 | if (Result) { | ||||
3636 | NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount; | ||||
3637 | NumMemoryInstsSelectCreated += ST.countNewSelectNodes(); | ||||
3638 | } | ||||
3639 | return Result; | ||||
3640 | } | ||||
3641 | |||||
3642 | /// Try to match PHI node to Candidate. | ||||
3643 | /// Matcher tracks the matched Phi nodes. | ||||
3644 | bool MatchPhiNode(PHINode *PHI, PHINode *Candidate, | ||||
3645 | SmallSetVector<PHIPair, 8> &Matcher, | ||||
3646 | PhiNodeSet &PhiNodesToMatch) { | ||||
3647 | SmallVector<PHIPair, 8> WorkList; | ||||
3648 | Matcher.insert({ PHI, Candidate }); | ||||
3649 | SmallSet<PHINode *, 8> MatchedPHIs; | ||||
3650 | MatchedPHIs.insert(PHI); | ||||
3651 | WorkList.push_back({ PHI, Candidate }); | ||||
3652 | SmallSet<PHIPair, 8> Visited; | ||||
3653 | while (!WorkList.empty()) { | ||||
3654 | auto Item = WorkList.pop_back_val(); | ||||
3655 | if (!Visited.insert(Item).second) | ||||
3656 | continue; | ||||
3657 | // We iterate over all incoming values to Phi to compare them. | ||||
3658 | // If values are different and both of them Phi and the first one is a | ||||
3659 | // Phi we added (subject to match) and both of them is in the same basic | ||||
3660 | // block then we can match our pair if values match. So we state that | ||||
3661 | // these values match and add it to work list to verify that. | ||||
3662 | for (auto B : Item.first->blocks()) { | ||||
3663 | Value *FirstValue = Item.first->getIncomingValueForBlock(B); | ||||
3664 | Value *SecondValue = Item.second->getIncomingValueForBlock(B); | ||||
3665 | if (FirstValue == SecondValue) | ||||
3666 | continue; | ||||
3667 | |||||
3668 | PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue); | ||||
3669 | PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue); | ||||
3670 | |||||
3671 | // One of them is not Phi or | ||||
3672 | // The first one is not Phi node from the set we'd like to match or | ||||
3673 | // Phi nodes from different basic blocks then | ||||
3674 | // we will not be able to match. | ||||
3675 | if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) || | ||||
3676 | FirstPhi->getParent() != SecondPhi->getParent()) | ||||
3677 | return false; | ||||
3678 | |||||
3679 | // If we already matched them then continue. | ||||
3680 | if (Matcher.count({ FirstPhi, SecondPhi })) | ||||
3681 | continue; | ||||
3682 | // So the values are different and does not match. So we need them to | ||||
3683 | // match. (But we register no more than one match per PHI node, so that | ||||
3684 | // we won't later try to replace them twice.) | ||||
3685 | if (MatchedPHIs.insert(FirstPhi).second) | ||||
3686 | Matcher.insert({ FirstPhi, SecondPhi }); | ||||
3687 | // But me must check it. | ||||
3688 | WorkList.push_back({ FirstPhi, SecondPhi }); | ||||
3689 | } | ||||
3690 | } | ||||
3691 | return true; | ||||
3692 | } | ||||
3693 | |||||
3694 | /// For the given set of PHI nodes (in the SimplificationTracker) try | ||||
3695 | /// to find their equivalents. | ||||
3696 | /// Returns false if this matching fails and creation of new Phi is disabled. | ||||
3697 | bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes, | ||||
3698 | unsigned &PhiNotMatchedCount) { | ||||
3699 | // Matched and PhiNodesToMatch iterate their elements in a deterministic | ||||
3700 | // order, so the replacements (ReplacePhi) are also done in a deterministic | ||||
3701 | // order. | ||||
3702 | SmallSetVector<PHIPair, 8> Matched; | ||||
3703 | SmallPtrSet<PHINode *, 8> WillNotMatch; | ||||
3704 | PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes(); | ||||
3705 | while (PhiNodesToMatch.size()) { | ||||
3706 | PHINode *PHI = *PhiNodesToMatch.begin(); | ||||
3707 | |||||
3708 | // Add us, if no Phi nodes in the basic block we do not match. | ||||
3709 | WillNotMatch.clear(); | ||||
3710 | WillNotMatch.insert(PHI); | ||||
3711 | |||||
3712 | // Traverse all Phis until we found equivalent or fail to do that. | ||||
3713 | bool IsMatched = false; | ||||
3714 | for (auto &P : PHI->getParent()->phis()) { | ||||
3715 | // Skip new Phi nodes. | ||||
3716 | if (PhiNodesToMatch.count(&P)) | ||||
3717 | continue; | ||||
3718 | if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch))) | ||||
3719 | break; | ||||
3720 | // If it does not match, collect all Phi nodes from matcher. | ||||
3721 | // if we end up with no match, them all these Phi nodes will not match | ||||
3722 | // later. | ||||
3723 | for (auto M : Matched) | ||||
3724 | WillNotMatch.insert(M.first); | ||||
3725 | Matched.clear(); | ||||
3726 | } | ||||
3727 | if (IsMatched) { | ||||
3728 | // Replace all matched values and erase them. | ||||
3729 | for (auto MV : Matched) | ||||
3730 | ST.ReplacePhi(MV.first, MV.second); | ||||
3731 | Matched.clear(); | ||||
3732 | continue; | ||||
3733 | } | ||||
3734 | // If we are not allowed to create new nodes then bail out. | ||||
3735 | if (!AllowNewPhiNodes) | ||||
3736 | return false; | ||||
3737 | // Just remove all seen values in matcher. They will not match anything. | ||||
3738 | PhiNotMatchedCount += WillNotMatch.size(); | ||||
3739 | for (auto *P : WillNotMatch) | ||||
3740 | PhiNodesToMatch.erase(P); | ||||
3741 | } | ||||
3742 | return true; | ||||
3743 | } | ||||
3744 | /// Fill the placeholders with values from predecessors and simplify them. | ||||
3745 | void FillPlaceholders(FoldAddrToValueMapping &Map, | ||||
3746 | SmallVectorImpl<Value *> &TraverseOrder, | ||||
3747 | SimplificationTracker &ST) { | ||||
3748 | while (!TraverseOrder.empty()) { | ||||
3749 | Value *Current = TraverseOrder.pop_back_val(); | ||||
3750 | assert(Map.find(Current) != Map.end() && "No node to fill!!!")(static_cast <bool> (Map.find(Current) != Map.end() && "No node to fill!!!") ? void (0) : __assert_fail ("Map.find(Current) != Map.end() && \"No node to fill!!!\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3750, __extension__ __PRETTY_FUNCTION__ )); | ||||
3751 | Value *V = Map[Current]; | ||||
3752 | |||||
3753 | if (SelectInst *Select = dyn_cast<SelectInst>(V)) { | ||||
3754 | // CurrentValue also must be Select. | ||||
3755 | auto *CurrentSelect = cast<SelectInst>(Current); | ||||
3756 | auto *TrueValue = CurrentSelect->getTrueValue(); | ||||
3757 | assert(Map.find(TrueValue) != Map.end() && "No True Value!")(static_cast <bool> (Map.find(TrueValue) != Map.end() && "No True Value!") ? void (0) : __assert_fail ("Map.find(TrueValue) != Map.end() && \"No True Value!\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3757, __extension__ __PRETTY_FUNCTION__ )); | ||||
3758 | Select->setTrueValue(ST.Get(Map[TrueValue])); | ||||
3759 | auto *FalseValue = CurrentSelect->getFalseValue(); | ||||
3760 | assert(Map.find(FalseValue) != Map.end() && "No False Value!")(static_cast <bool> (Map.find(FalseValue) != Map.end() && "No False Value!") ? void (0) : __assert_fail ("Map.find(FalseValue) != Map.end() && \"No False Value!\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3760, __extension__ __PRETTY_FUNCTION__ )); | ||||
3761 | Select->setFalseValue(ST.Get(Map[FalseValue])); | ||||
3762 | } else { | ||||
3763 | // Must be a Phi node then. | ||||
3764 | auto *PHI = cast<PHINode>(V); | ||||
3765 | // Fill the Phi node with values from predecessors. | ||||
3766 | for (auto *B : predecessors(PHI->getParent())) { | ||||
3767 | Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B); | ||||
3768 | assert(Map.find(PV) != Map.end() && "No predecessor Value!")(static_cast <bool> (Map.find(PV) != Map.end() && "No predecessor Value!") ? void (0) : __assert_fail ("Map.find(PV) != Map.end() && \"No predecessor Value!\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3768, __extension__ __PRETTY_FUNCTION__ )); | ||||
3769 | PHI->addIncoming(ST.Get(Map[PV]), B); | ||||
3770 | } | ||||
3771 | } | ||||
3772 | Map[Current] = ST.Simplify(V); | ||||
3773 | } | ||||
3774 | } | ||||
3775 | |||||
3776 | /// Starting from original value recursively iterates over def-use chain up to | ||||
3777 | /// known ending values represented in a map. For each traversed phi/select | ||||
3778 | /// inserts a placeholder Phi or Select. | ||||
3779 | /// Reports all new created Phi/Select nodes by adding them to set. | ||||
3780 | /// Also reports and order in what values have been traversed. | ||||
3781 | void InsertPlaceholders(FoldAddrToValueMapping &Map, | ||||
3782 | SmallVectorImpl<Value *> &TraverseOrder, | ||||
3783 | SimplificationTracker &ST) { | ||||
3784 | SmallVector<Value *, 32> Worklist; | ||||
3785 | assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&(static_cast <bool> ((isa<PHINode>(Original) || isa <SelectInst>(Original)) && "Address must be a Phi or Select node" ) ? void (0) : __assert_fail ("(isa<PHINode>(Original) || isa<SelectInst>(Original)) && \"Address must be a Phi or Select node\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3786, __extension__ __PRETTY_FUNCTION__ )) | ||||
3786 | "Address must be a Phi or Select node")(static_cast <bool> ((isa<PHINode>(Original) || isa <SelectInst>(Original)) && "Address must be a Phi or Select node" ) ? void (0) : __assert_fail ("(isa<PHINode>(Original) || isa<SelectInst>(Original)) && \"Address must be a Phi or Select node\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3786, __extension__ __PRETTY_FUNCTION__ )); | ||||
3787 | auto *Dummy = UndefValue::get(CommonType); | ||||
3788 | Worklist.push_back(Original); | ||||
3789 | while (!Worklist.empty()) { | ||||
3790 | Value *Current = Worklist.pop_back_val(); | ||||
3791 | // if it is already visited or it is an ending value then skip it. | ||||
3792 | if (Map.find(Current) != Map.end()) | ||||
3793 | continue; | ||||
3794 | TraverseOrder.push_back(Current); | ||||
3795 | |||||
3796 | // CurrentValue must be a Phi node or select. All others must be covered | ||||
3797 | // by anchors. | ||||
3798 | if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) { | ||||
3799 | // Is it OK to get metadata from OrigSelect?! | ||||
3800 | // Create a Select placeholder with dummy value. | ||||
3801 | SelectInst *Select = SelectInst::Create( | ||||
3802 | CurrentSelect->getCondition(), Dummy, Dummy, | ||||
3803 | CurrentSelect->getName(), CurrentSelect, CurrentSelect); | ||||
3804 | Map[Current] = Select; | ||||
3805 | ST.insertNewSelect(Select); | ||||
3806 | // We are interested in True and False values. | ||||
3807 | Worklist.push_back(CurrentSelect->getTrueValue()); | ||||
3808 | Worklist.push_back(CurrentSelect->getFalseValue()); | ||||
3809 | } else { | ||||
3810 | // It must be a Phi node then. | ||||
3811 | PHINode *CurrentPhi = cast<PHINode>(Current); | ||||
3812 | unsigned PredCount = CurrentPhi->getNumIncomingValues(); | ||||
3813 | PHINode *PHI = | ||||
3814 | PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi); | ||||
3815 | Map[Current] = PHI; | ||||
3816 | ST.insertNewPhi(PHI); | ||||
3817 | append_range(Worklist, CurrentPhi->incoming_values()); | ||||
3818 | } | ||||
3819 | } | ||||
3820 | } | ||||
3821 | |||||
3822 | bool addrModeCombiningAllowed() { | ||||
3823 | if (DisableComplexAddrModes) | ||||
3824 | return false; | ||||
3825 | switch (DifferentField) { | ||||
3826 | default: | ||||
3827 | return false; | ||||
3828 | case ExtAddrMode::BaseRegField: | ||||
3829 | return AddrSinkCombineBaseReg; | ||||
3830 | case ExtAddrMode::BaseGVField: | ||||
3831 | return AddrSinkCombineBaseGV; | ||||
3832 | case ExtAddrMode::BaseOffsField: | ||||
3833 | return AddrSinkCombineBaseOffs; | ||||
3834 | case ExtAddrMode::ScaledRegField: | ||||
3835 | return AddrSinkCombineScaledReg; | ||||
3836 | } | ||||
3837 | } | ||||
3838 | }; | ||||
3839 | } // end anonymous namespace | ||||
3840 | |||||
3841 | /// Try adding ScaleReg*Scale to the current addressing mode. | ||||
3842 | /// Return true and update AddrMode if this addr mode is legal for the target, | ||||
3843 | /// false if not. | ||||
3844 | bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale, | ||||
3845 | unsigned Depth) { | ||||
3846 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing | ||||
3847 | // mode. Just process that directly. | ||||
3848 | if (Scale == 1) | ||||
3849 | return matchAddr(ScaleReg, Depth); | ||||
3850 | |||||
3851 | // If the scale is 0, it takes nothing to add this. | ||||
3852 | if (Scale == 0) | ||||
3853 | return true; | ||||
3854 | |||||
3855 | // If we already have a scale of this value, we can add to it, otherwise, we | ||||
3856 | // need an available scale field. | ||||
3857 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) | ||||
3858 | return false; | ||||
3859 | |||||
3860 | ExtAddrMode TestAddrMode = AddrMode; | ||||
3861 | |||||
3862 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like | ||||
3863 | // [A+B + A*7] -> [B+A*8]. | ||||
3864 | TestAddrMode.Scale += Scale; | ||||
3865 | TestAddrMode.ScaledReg = ScaleReg; | ||||
3866 | |||||
3867 | // If the new address isn't legal, bail out. | ||||
3868 | if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) | ||||
3869 | return false; | ||||
3870 | |||||
3871 | // It was legal, so commit it. | ||||
3872 | AddrMode = TestAddrMode; | ||||
3873 | |||||
3874 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now | ||||
3875 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding | ||||
3876 | // X*Scale + C*Scale to addr mode. If we found available IV increment, do not | ||||
3877 | // go any further: we can reuse it and cannot eliminate it. | ||||
3878 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; | ||||
3879 | if (isa<Instruction>(ScaleReg) && // not a constant expr. | ||||
3880 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) && | ||||
3881 | !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(64)) { | ||||
3882 | TestAddrMode.InBounds = false; | ||||
3883 | TestAddrMode.ScaledReg = AddLHS; | ||||
3884 | TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale; | ||||
3885 | |||||
3886 | // If this addressing mode is legal, commit it and remember that we folded | ||||
3887 | // this instruction. | ||||
3888 | if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) { | ||||
3889 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); | ||||
3890 | AddrMode = TestAddrMode; | ||||
3891 | return true; | ||||
3892 | } | ||||
3893 | // Restore status quo. | ||||
3894 | TestAddrMode = AddrMode; | ||||
3895 | } | ||||
3896 | |||||
3897 | // If this is an add recurrence with a constant step, return the increment | ||||
3898 | // instruction and the canonicalized step. | ||||
3899 | auto GetConstantStep = [this](const Value * V) | ||||
3900 | ->Optional<std::pair<Instruction *, APInt> > { | ||||
3901 | auto *PN = dyn_cast<PHINode>(V); | ||||
3902 | if (!PN) | ||||
3903 | return None; | ||||
3904 | auto IVInc = getIVIncrement(PN, &LI); | ||||
3905 | if (!IVInc) | ||||
3906 | return None; | ||||
3907 | // TODO: The result of the intrinsics above is two-compliment. However when | ||||
3908 | // IV inc is expressed as add or sub, iv.next is potentially a poison value. | ||||
3909 | // If it has nuw or nsw flags, we need to make sure that these flags are | ||||
3910 | // inferrable at the point of memory instruction. Otherwise we are replacing | ||||
3911 | // well-defined two-compliment computation with poison. Currently, to avoid | ||||
3912 | // potentially complex analysis needed to prove this, we reject such cases. | ||||
3913 | if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(IVInc->first)) | ||||
3914 | if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap()) | ||||
3915 | return None; | ||||
3916 | if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second)) | ||||
3917 | return std::make_pair(IVInc->first, ConstantStep->getValue()); | ||||
3918 | return None; | ||||
3919 | }; | ||||
3920 | |||||
3921 | // Try to account for the following special case: | ||||
3922 | // 1. ScaleReg is an inductive variable; | ||||
3923 | // 2. We use it with non-zero offset; | ||||
3924 | // 3. IV's increment is available at the point of memory instruction. | ||||
3925 | // | ||||
3926 | // In this case, we may reuse the IV increment instead of the IV Phi to | ||||
3927 | // achieve the following advantages: | ||||
3928 | // 1. If IV step matches the offset, we will have no need in the offset; | ||||
3929 | // 2. Even if they don't match, we will reduce the overlap of living IV | ||||
3930 | // and IV increment, that will potentially lead to better register | ||||
3931 | // assignment. | ||||
3932 | if (AddrMode.BaseOffs) { | ||||
3933 | if (auto IVStep = GetConstantStep(ScaleReg)) { | ||||
3934 | Instruction *IVInc = IVStep->first; | ||||
3935 | // The following assert is important to ensure a lack of infinite loops. | ||||
3936 | // This transforms is (intentionally) the inverse of the one just above. | ||||
3937 | // If they don't agree on the definition of an increment, we'd alternate | ||||
3938 | // back and forth indefinitely. | ||||
3939 | assert(isIVIncrement(IVInc, &LI) && "implied by GetConstantStep")(static_cast <bool> (isIVIncrement(IVInc, &LI) && "implied by GetConstantStep") ? void (0) : __assert_fail ("isIVIncrement(IVInc, &LI) && \"implied by GetConstantStep\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 3939, __extension__ __PRETTY_FUNCTION__ )); | ||||
3940 | APInt Step = IVStep->second; | ||||
3941 | APInt Offset = Step * AddrMode.Scale; | ||||
3942 | if (Offset.isSignedIntN(64)) { | ||||
3943 | TestAddrMode.InBounds = false; | ||||
3944 | TestAddrMode.ScaledReg = IVInc; | ||||
3945 | TestAddrMode.BaseOffs -= Offset.getLimitedValue(); | ||||
3946 | // If this addressing mode is legal, commit it.. | ||||
3947 | // (Note that we defer the (expensive) domtree base legality check | ||||
3948 | // to the very last possible point.) | ||||
3949 | if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace) && | ||||
3950 | getDTFn().dominates(IVInc, MemoryInst)) { | ||||
3951 | AddrModeInsts.push_back(cast<Instruction>(IVInc)); | ||||
3952 | AddrMode = TestAddrMode; | ||||
3953 | return true; | ||||
3954 | } | ||||
3955 | // Restore status quo. | ||||
3956 | TestAddrMode = AddrMode; | ||||
3957 | } | ||||
3958 | } | ||||
3959 | } | ||||
3960 | |||||
3961 | // Otherwise, just return what we have. | ||||
3962 | return true; | ||||
3963 | } | ||||
3964 | |||||
3965 | /// This is a little filter, which returns true if an addressing computation | ||||
3966 | /// involving I might be folded into a load/store accessing it. | ||||
3967 | /// This doesn't need to be perfect, but needs to accept at least | ||||
3968 | /// the set of instructions that MatchOperationAddr can. | ||||
3969 | static bool MightBeFoldableInst(Instruction *I) { | ||||
3970 | switch (I->getOpcode()) { | ||||
3971 | case Instruction::BitCast: | ||||
3972 | case Instruction::AddrSpaceCast: | ||||
3973 | // Don't touch identity bitcasts. | ||||
3974 | if (I->getType() == I->getOperand(0)->getType()) | ||||
3975 | return false; | ||||
3976 | return I->getType()->isIntOrPtrTy(); | ||||
3977 | case Instruction::PtrToInt: | ||||
3978 | // PtrToInt is always a noop, as we know that the int type is pointer sized. | ||||
3979 | return true; | ||||
3980 | case Instruction::IntToPtr: | ||||
3981 | // We know the input is intptr_t, so this is foldable. | ||||
3982 | return true; | ||||
3983 | case Instruction::Add: | ||||
3984 | return true; | ||||
3985 | case Instruction::Mul: | ||||
3986 | case Instruction::Shl: | ||||
3987 | // Can only handle X*C and X << C. | ||||
3988 | return isa<ConstantInt>(I->getOperand(1)); | ||||
3989 | case Instruction::GetElementPtr: | ||||
3990 | return true; | ||||
3991 | default: | ||||
3992 | return false; | ||||
3993 | } | ||||
3994 | } | ||||
3995 | |||||
3996 | /// Check whether or not \p Val is a legal instruction for \p TLI. | ||||
3997 | /// \note \p Val is assumed to be the product of some type promotion. | ||||
3998 | /// Therefore if \p Val has an undefined state in \p TLI, this is assumed | ||||
3999 | /// to be legal, as the non-promoted value would have had the same state. | ||||
4000 | static bool isPromotedInstructionLegal(const TargetLowering &TLI, | ||||
4001 | const DataLayout &DL, Value *Val) { | ||||
4002 | Instruction *PromotedInst = dyn_cast<Instruction>(Val); | ||||
4003 | if (!PromotedInst) | ||||
4004 | return false; | ||||
4005 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); | ||||
4006 | // If the ISDOpcode is undefined, it was undefined before the promotion. | ||||
4007 | if (!ISDOpcode) | ||||
4008 | return true; | ||||
4009 | // Otherwise, check if the promoted instruction is legal or not. | ||||
4010 | return TLI.isOperationLegalOrCustom( | ||||
4011 | ISDOpcode, TLI.getValueType(DL, PromotedInst->getType())); | ||||
4012 | } | ||||
4013 | |||||
4014 | namespace { | ||||
4015 | |||||
4016 | /// Hepler class to perform type promotion. | ||||
4017 | class TypePromotionHelper { | ||||
4018 | /// Utility function to add a promoted instruction \p ExtOpnd to | ||||
4019 | /// \p PromotedInsts and record the type of extension we have seen. | ||||
4020 | static void addPromotedInst(InstrToOrigTy &PromotedInsts, | ||||
4021 | Instruction *ExtOpnd, | ||||
4022 | bool IsSExt) { | ||||
4023 | ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension; | ||||
4024 | InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd); | ||||
4025 | if (It != PromotedInsts.end()) { | ||||
4026 | // If the new extension is same as original, the information in | ||||
4027 | // PromotedInsts[ExtOpnd] is still correct. | ||||
4028 | if (It->second.getInt() == ExtTy) | ||||
4029 | return; | ||||
4030 | |||||
4031 | // Now the new extension is different from old extension, we make | ||||
4032 | // the type information invalid by setting extension type to | ||||
4033 | // BothExtension. | ||||
4034 | ExtTy = BothExtension; | ||||
4035 | } | ||||
4036 | PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy); | ||||
4037 | } | ||||
4038 | |||||
4039 | /// Utility function to query the original type of instruction \p Opnd | ||||
4040 | /// with a matched extension type. If the extension doesn't match, we | ||||
4041 | /// cannot use the information we had on the original type. | ||||
4042 | /// BothExtension doesn't match any extension type. | ||||
4043 | static const Type *getOrigType(const InstrToOrigTy &PromotedInsts, | ||||
4044 | Instruction *Opnd, | ||||
4045 | bool IsSExt) { | ||||
4046 | ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension; | ||||
4047 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); | ||||
4048 | if (It != PromotedInsts.end() && It->second.getInt() == ExtTy) | ||||
4049 | return It->second.getPointer(); | ||||
4050 | return nullptr; | ||||
4051 | } | ||||
4052 | |||||
4053 | /// Utility function to check whether or not a sign or zero extension | ||||
4054 | /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by | ||||
4055 | /// either using the operands of \p Inst or promoting \p Inst. | ||||
4056 | /// The type of the extension is defined by \p IsSExt. | ||||
4057 | /// In other words, check if: | ||||
4058 | /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. | ||||
4059 | /// #1 Promotion applies: | ||||
4060 | /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). | ||||
4061 | /// #2 Operand reuses: | ||||
4062 | /// ext opnd1 to ConsideredExtType. | ||||
4063 | /// \p PromotedInsts maps the instructions to their type before promotion. | ||||
4064 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, | ||||
4065 | const InstrToOrigTy &PromotedInsts, bool IsSExt); | ||||
4066 | |||||
4067 | /// Utility function to determine if \p OpIdx should be promoted when | ||||
4068 | /// promoting \p Inst. | ||||
4069 | static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { | ||||
4070 | return !(isa<SelectInst>(Inst) && OpIdx == 0); | ||||
4071 | } | ||||
4072 | |||||
4073 | /// Utility function to promote the operand of \p Ext when this | ||||
4074 | /// operand is a promotable trunc or sext or zext. | ||||
4075 | /// \p PromotedInsts maps the instructions to their type before promotion. | ||||
4076 | /// \p CreatedInstsCost[out] contains the cost of all instructions | ||||
4077 | /// created to promote the operand of Ext. | ||||
4078 | /// Newly added extensions are inserted in \p Exts. | ||||
4079 | /// Newly added truncates are inserted in \p Truncs. | ||||
4080 | /// Should never be called directly. | ||||
4081 | /// \return The promoted value which is used instead of Ext. | ||||
4082 | static Value *promoteOperandForTruncAndAnyExt( | ||||
4083 | Instruction *Ext, TypePromotionTransaction &TPT, | ||||
4084 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, | ||||
4085 | SmallVectorImpl<Instruction *> *Exts, | ||||
4086 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI); | ||||
4087 | |||||
4088 | /// Utility function to promote the operand of \p Ext when this | ||||
4089 | /// operand is promotable and is not a supported trunc or sext. | ||||
4090 | /// \p PromotedInsts maps the instructions to their type before promotion. | ||||
4091 | /// \p CreatedInstsCost[out] contains the cost of all the instructions | ||||
4092 | /// created to promote the operand of Ext. | ||||
4093 | /// Newly added extensions are inserted in \p Exts. | ||||
4094 | /// Newly added truncates are inserted in \p Truncs. | ||||
4095 | /// Should never be called directly. | ||||
4096 | /// \return The promoted value which is used instead of Ext. | ||||
4097 | static Value *promoteOperandForOther(Instruction *Ext, | ||||
4098 | TypePromotionTransaction &TPT, | ||||
4099 | InstrToOrigTy &PromotedInsts, | ||||
4100 | unsigned &CreatedInstsCost, | ||||
4101 | SmallVectorImpl<Instruction *> *Exts, | ||||
4102 | SmallVectorImpl<Instruction *> *Truncs, | ||||
4103 | const TargetLowering &TLI, bool IsSExt); | ||||
4104 | |||||
4105 | /// \see promoteOperandForOther. | ||||
4106 | static Value *signExtendOperandForOther( | ||||
4107 | Instruction *Ext, TypePromotionTransaction &TPT, | ||||
4108 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, | ||||
4109 | SmallVectorImpl<Instruction *> *Exts, | ||||
4110 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { | ||||
4111 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, | ||||
4112 | Exts, Truncs, TLI, true); | ||||
4113 | } | ||||
4114 | |||||
4115 | /// \see promoteOperandForOther. | ||||
4116 | static Value *zeroExtendOperandForOther( | ||||
4117 | Instruction *Ext, TypePromotionTransaction &TPT, | ||||
4118 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, | ||||
4119 | SmallVectorImpl<Instruction *> *Exts, | ||||
4120 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { | ||||
4121 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, | ||||
4122 | Exts, Truncs, TLI, false); | ||||
4123 | } | ||||
4124 | |||||
4125 | public: | ||||
4126 | /// Type for the utility function that promotes the operand of Ext. | ||||
4127 | using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT, | ||||
4128 | InstrToOrigTy &PromotedInsts, | ||||
4129 | unsigned &CreatedInstsCost, | ||||
4130 | SmallVectorImpl<Instruction *> *Exts, | ||||
4131 | SmallVectorImpl<Instruction *> *Truncs, | ||||
4132 | const TargetLowering &TLI); | ||||
4133 | |||||
4134 | /// Given a sign/zero extend instruction \p Ext, return the appropriate | ||||
4135 | /// action to promote the operand of \p Ext instead of using Ext. | ||||
4136 | /// \return NULL if no promotable action is possible with the current | ||||
4137 | /// sign extension. | ||||
4138 | /// \p InsertedInsts keeps track of all the instructions inserted by the | ||||
4139 | /// other CodeGenPrepare optimizations. This information is important | ||||
4140 | /// because we do not want to promote these instructions as CodeGenPrepare | ||||
4141 | /// will reinsert them later. Thus creating an infinite loop: create/remove. | ||||
4142 | /// \p PromotedInsts maps the instructions to their type before promotion. | ||||
4143 | static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts, | ||||
4144 | const TargetLowering &TLI, | ||||
4145 | const InstrToOrigTy &PromotedInsts); | ||||
4146 | }; | ||||
4147 | |||||
4148 | } // end anonymous namespace | ||||
4149 | |||||
4150 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, | ||||
4151 | Type *ConsideredExtType, | ||||
4152 | const InstrToOrigTy &PromotedInsts, | ||||
4153 | bool IsSExt) { | ||||
4154 | // The promotion helper does not know how to deal with vector types yet. | ||||
4155 | // To be able to fix that, we would need to fix the places where we | ||||
4156 | // statically extend, e.g., constants and such. | ||||
4157 | if (Inst->getType()->isVectorTy()) | ||||
4158 | return false; | ||||
4159 | |||||
4160 | // We can always get through zext. | ||||
4161 | if (isa<ZExtInst>(Inst)) | ||||
4162 | return true; | ||||
4163 | |||||
4164 | // sext(sext) is ok too. | ||||
4165 | if (IsSExt && isa<SExtInst>(Inst)) | ||||
4166 | return true; | ||||
4167 | |||||
4168 | // We can get through binary operator, if it is legal. In other words, the | ||||
4169 | // binary operator must have a nuw or nsw flag. | ||||
4170 | if (const auto *BinOp = dyn_cast<BinaryOperator>(Inst)) | ||||
4171 | if (isa<OverflowingBinaryOperator>(BinOp) && | ||||
4172 | ((!IsSExt && BinOp->hasNoUnsignedWrap()) || | ||||
4173 | (IsSExt && BinOp->hasNoSignedWrap()))) | ||||
4174 | return true; | ||||
4175 | |||||
4176 | // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst)) | ||||
4177 | if ((Inst->getOpcode() == Instruction::And || | ||||
4178 | Inst->getOpcode() == Instruction::Or)) | ||||
4179 | return true; | ||||
4180 | |||||
4181 | // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst)) | ||||
4182 | if (Inst->getOpcode() == Instruction::Xor) { | ||||
4183 | // Make sure it is not a NOT. | ||||
4184 | if (const auto *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1))) | ||||
4185 | if (!Cst->getValue().isAllOnes()) | ||||
4186 | return true; | ||||
4187 | } | ||||
4188 | |||||
4189 | // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst)) | ||||
4190 | // It may change a poisoned value into a regular value, like | ||||
4191 | // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12 | ||||
4192 | // poisoned value regular value | ||||
4193 | // It should be OK since undef covers valid value. | ||||
4194 | if (Inst->getOpcode() == Instruction::LShr && !IsSExt) | ||||
4195 | return true; | ||||
4196 | |||||
4197 | // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst) | ||||
4198 | // It may change a poisoned value into a regular value, like | ||||
4199 | // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12 | ||||
4200 | // poisoned value regular value | ||||
4201 | // It should be OK since undef covers valid value. | ||||
4202 | if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) { | ||||
4203 | const auto *ExtInst = cast<const Instruction>(*Inst->user_begin()); | ||||
4204 | if (ExtInst->hasOneUse()) { | ||||
4205 | const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin()); | ||||
4206 | if (AndInst && AndInst->getOpcode() == Instruction::And) { | ||||
4207 | const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1)); | ||||
4208 | if (Cst && | ||||
4209 | Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth())) | ||||
4210 | return true; | ||||
4211 | } | ||||
4212 | } | ||||
4213 | } | ||||
4214 | |||||
4215 | // Check if we can do the following simplification. | ||||
4216 | // ext(trunc(opnd)) --> ext(opnd) | ||||
4217 | if (!isa<TruncInst>(Inst)) | ||||
4218 | return false; | ||||
4219 | |||||
4220 | Value *OpndVal = Inst->getOperand(0); | ||||
4221 | // Check if we can use this operand in the extension. | ||||
4222 | // If the type is larger than the result type of the extension, we cannot. | ||||
4223 | if (!OpndVal->getType()->isIntegerTy() || | ||||
4224 | OpndVal->getType()->getIntegerBitWidth() > | ||||
4225 | ConsideredExtType->getIntegerBitWidth()) | ||||
4226 | return false; | ||||
4227 | |||||
4228 | // If the operand of the truncate is not an instruction, we will not have | ||||
4229 | // any information on the dropped bits. | ||||
4230 | // (Actually we could for constant but it is not worth the extra logic). | ||||
4231 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); | ||||
4232 | if (!Opnd) | ||||
4233 | return false; | ||||
4234 | |||||
4235 | // Check if the source of the type is narrow enough. | ||||
4236 | // I.e., check that trunc just drops extended bits of the same kind of | ||||
4237 | // the extension. | ||||
4238 | // #1 get the type of the operand and check the kind of the extended bits. | ||||
4239 | const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt); | ||||
4240 | if (OpndType) | ||||
4241 | ; | ||||
4242 | else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) | ||||
4243 | OpndType = Opnd->getOperand(0)->getType(); | ||||
4244 | else | ||||
4245 | return false; | ||||
4246 | |||||
4247 | // #2 check that the truncate just drops extended bits. | ||||
4248 | return Inst->getType()->getIntegerBitWidth() >= | ||||
4249 | OpndType->getIntegerBitWidth(); | ||||
4250 | } | ||||
4251 | |||||
4252 | TypePromotionHelper::Action TypePromotionHelper::getAction( | ||||
4253 | Instruction *Ext, const SetOfInstrs &InsertedInsts, | ||||
4254 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { | ||||
4255 | assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&(static_cast <bool> ((isa<SExtInst>(Ext) || isa< ZExtInst>(Ext)) && "Unexpected instruction type") ? void (0) : __assert_fail ("(isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && \"Unexpected instruction type\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 4256, __extension__ __PRETTY_FUNCTION__ )) | ||||
4256 | "Unexpected instruction type")(static_cast <bool> ((isa<SExtInst>(Ext) || isa< ZExtInst>(Ext)) && "Unexpected instruction type") ? void (0) : __assert_fail ("(isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && \"Unexpected instruction type\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 4256, __extension__ __PRETTY_FUNCTION__ )); | ||||
4257 | Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); | ||||
4258 | Type *ExtTy = Ext->getType(); | ||||
4259 | bool IsSExt = isa<SExtInst>(Ext); | ||||
4260 | // If the operand of the extension is not an instruction, we cannot | ||||
4261 | // get through. | ||||
4262 | // If it, check we can get through. | ||||
4263 | if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) | ||||
4264 | return nullptr; | ||||
4265 | |||||
4266 | // Do not promote if the operand has been added by codegenprepare. | ||||
4267 | // Otherwise, it means we are undoing an optimization that is likely to be | ||||
4268 | // redone, thus causing potential infinite loop. | ||||
4269 | if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd)) | ||||
4270 | return nullptr; | ||||
4271 | |||||
4272 | // SExt or Trunc instructions. | ||||
4273 | // Return the related handler. | ||||
4274 | if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || | ||||
4275 | isa<ZExtInst>(ExtOpnd)) | ||||
4276 | return promoteOperandForTruncAndAnyExt; | ||||
4277 | |||||
4278 | // Regular instruction. | ||||
4279 | // Abort early if we will have to insert non-free instructions. | ||||
4280 | if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) | ||||
4281 | return nullptr; | ||||
4282 | return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; | ||||
4283 | } | ||||
4284 | |||||
4285 | Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( | ||||
4286 | Instruction *SExt, TypePromotionTransaction &TPT, | ||||
4287 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, | ||||
4288 | SmallVectorImpl<Instruction *> *Exts, | ||||
4289 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { | ||||
4290 | // By construction, the operand of SExt is an instruction. Otherwise we cannot | ||||
4291 | // get through it and this method should not be called. | ||||
4292 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); | ||||
4293 | Value *ExtVal = SExt; | ||||
4294 | bool HasMergedNonFreeExt = false; | ||||
4295 | if (isa<ZExtInst>(SExtOpnd)) { | ||||
4296 | // Replace s|zext(zext(opnd)) | ||||
4297 | // => zext(opnd). | ||||
4298 | HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd); | ||||
4299 | Value *ZExt = | ||||
4300 | TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); | ||||
4301 | TPT.replaceAllUsesWith(SExt, ZExt); | ||||
4302 | TPT.eraseInstruction(SExt); | ||||
4303 | ExtVal = ZExt; | ||||
4304 | } else { | ||||
4305 | // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) | ||||
4306 | // => z|sext(opnd). | ||||
4307 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); | ||||
4308 | } | ||||
4309 | CreatedInstsCost = 0; | ||||
4310 | |||||
4311 | // Remove dead code. | ||||
4312 | if (SExtOpnd->use_empty()) | ||||
4313 | TPT.eraseInstruction(SExtOpnd); | ||||
4314 | |||||
4315 | // Check if the extension is still needed. | ||||
4316 | Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); | ||||
4317 | if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) { | ||||
4318 | if (ExtInst) { | ||||
4319 | if (Exts) | ||||
4320 | Exts->push_back(ExtInst); | ||||
4321 | CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt; | ||||
4322 | } | ||||
4323 | return ExtVal; | ||||
4324 | } | ||||
4325 | |||||
4326 | // At this point we have: ext ty opnd to ty. | ||||
4327 | // Reassign the uses of ExtInst to the opnd and remove ExtInst. | ||||
4328 | Value *NextVal = ExtInst->getOperand(0); | ||||
4329 | TPT.eraseInstruction(ExtInst, NextVal); | ||||
4330 | return NextVal; | ||||
4331 | } | ||||
4332 | |||||
4333 | Value *TypePromotionHelper::promoteOperandForOther( | ||||
4334 | Instruction *Ext, TypePromotionTransaction &TPT, | ||||
4335 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, | ||||
4336 | SmallVectorImpl<Instruction *> *Exts, | ||||
4337 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI, | ||||
4338 | bool IsSExt) { | ||||
4339 | // By construction, the operand of Ext is an instruction. Otherwise we cannot | ||||
4340 | // get through it and this method should not be called. | ||||
4341 | Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); | ||||
4342 | CreatedInstsCost = 0; | ||||
4343 | if (!ExtOpnd->hasOneUse()) { | ||||
4344 | // ExtOpnd will be promoted. | ||||
4345 | // All its uses, but Ext, will need to use a truncated value of the | ||||
4346 | // promoted version. | ||||
4347 | // Create the truncate now. | ||||
4348 | Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); | ||||
4349 | if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { | ||||
4350 | // Insert it just after the definition. | ||||
4351 | ITrunc->moveAfter(ExtOpnd); | ||||
4352 | if (Truncs) | ||||
4353 | Truncs->push_back(ITrunc); | ||||
4354 | } | ||||
4355 | |||||
4356 | TPT.replaceAllUsesWith(ExtOpnd, Trunc); | ||||
4357 | // Restore the operand of Ext (which has been replaced by the previous call | ||||
4358 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. | ||||
4359 | TPT.setOperand(Ext, 0, ExtOpnd); | ||||
4360 | } | ||||
4361 | |||||
4362 | // Get through the Instruction: | ||||
4363 | // 1. Update its type. | ||||
4364 | // 2. Replace the uses of Ext by Inst. | ||||
4365 | // 3. Extend each operand that needs to be extended. | ||||
4366 | |||||
4367 | // Remember the original type of the instruction before promotion. | ||||
4368 | // This is useful to know that the high bits are sign extended bits. | ||||
4369 | addPromotedInst(PromotedInsts, ExtOpnd, IsSExt); | ||||
4370 | // Step #1. | ||||
4371 | TPT.mutateType(ExtOpnd, Ext->getType()); | ||||
4372 | // Step #2. | ||||
4373 | TPT.replaceAllUsesWith(Ext, ExtOpnd); | ||||
4374 | // Step #3. | ||||
4375 | Instruction *ExtForOpnd = Ext; | ||||
4376 | |||||
4377 | LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Propagate Ext to operands\n" ; } } while (false); | ||||
4378 | for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; | ||||
4379 | ++OpIdx) { | ||||
4380 | LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Operand:\n" << * (ExtOpnd->getOperand(OpIdx)) << '\n'; } } while (false ); | ||||
4381 | if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || | ||||
4382 | !shouldExtOperand(ExtOpnd, OpIdx)) { | ||||
4383 | LLVM_DEBUG(dbgs() << "No need to propagate\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "No need to propagate\n" ; } } while (false); | ||||
4384 | continue; | ||||
4385 | } | ||||
4386 | // Check if we can statically extend the operand. | ||||
4387 | Value *Opnd = ExtOpnd->getOperand(OpIdx); | ||||
4388 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { | ||||
4389 | LLVM_DEBUG(dbgs() << "Statically extend\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Statically extend\n"; } } while (false); | ||||
4390 | unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); | ||||
4391 | APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) | ||||
4392 | : Cst->getValue().zext(BitWidth); | ||||
4393 | TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); | ||||
4394 | continue; | ||||
4395 | } | ||||
4396 | // UndefValue are typed, so we have to statically sign extend them. | ||||
4397 | if (isa<UndefValue>(Opnd)) { | ||||
4398 | LLVM_DEBUG(dbgs() << "Statically extend\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Statically extend\n"; } } while (false); | ||||
4399 | TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); | ||||
4400 | continue; | ||||
4401 | } | ||||
4402 | |||||
4403 | // Otherwise we have to explicitly sign extend the operand. | ||||
4404 | // Check if Ext was reused to extend an operand. | ||||
4405 | if (!ExtForOpnd) { | ||||
4406 | // If yes, create a new one. | ||||
4407 | LLVM_DEBUG(dbgs() << "More operands to ext\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "More operands to ext\n" ; } } while (false); | ||||
4408 | Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) | ||||
4409 | : TPT.createZExt(Ext, Opnd, Ext->getType()); | ||||
4410 | if (!isa<Instruction>(ValForExtOpnd)) { | ||||
4411 | TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd); | ||||
4412 | continue; | ||||
4413 | } | ||||
4414 | ExtForOpnd = cast<Instruction>(ValForExtOpnd); | ||||
4415 | } | ||||
4416 | if (Exts) | ||||
4417 | Exts->push_back(ExtForOpnd); | ||||
4418 | TPT.setOperand(ExtForOpnd, 0, Opnd); | ||||
4419 | |||||
4420 | // Move the sign extension before the insertion point. | ||||
4421 | TPT.moveBefore(ExtForOpnd, ExtOpnd); | ||||
4422 | TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); | ||||
4423 | CreatedInstsCost += !TLI.isExtFree(ExtForOpnd); | ||||
4424 | // If more sext are required, new instructions will have to be created. | ||||
4425 | ExtForOpnd = nullptr; | ||||
4426 | } | ||||
4427 | if (ExtForOpnd == Ext) { | ||||
4428 | LLVM_DEBUG(dbgs() << "Extension is useless now\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Extension is useless now\n" ; } } while (false); | ||||
4429 | TPT.eraseInstruction(Ext); | ||||
4430 | } | ||||
4431 | return ExtOpnd; | ||||
4432 | } | ||||
4433 | |||||
4434 | /// Check whether or not promoting an instruction to a wider type is profitable. | ||||
4435 | /// \p NewCost gives the cost of extension instructions created by the | ||||
4436 | /// promotion. | ||||
4437 | /// \p OldCost gives the cost of extension instructions before the promotion | ||||
4438 | /// plus the number of instructions that have been | ||||
4439 | /// matched in the addressing mode the promotion. | ||||
4440 | /// \p PromotedOperand is the value that has been promoted. | ||||
4441 | /// \return True if the promotion is profitable, false otherwise. | ||||
4442 | bool AddressingModeMatcher::isPromotionProfitable( | ||||
4443 | unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const { | ||||
4444 | LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCostdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n'; } } while (false) | ||||
4445 | << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n'; } } while (false); | ||||
4446 | // The cost of the new extensions is greater than the cost of the | ||||
4447 | // old extension plus what we folded. | ||||
4448 | // This is not profitable. | ||||
4449 | if (NewCost > OldCost) | ||||
4450 | return false; | ||||
4451 | if (NewCost < OldCost) | ||||
4452 | return true; | ||||
4453 | // The promotion is neutral but it may help folding the sign extension in | ||||
4454 | // loads for instance. | ||||
4455 | // Check that we did not create an illegal instruction. | ||||
4456 | return isPromotedInstructionLegal(TLI, DL, PromotedOperand); | ||||
4457 | } | ||||
4458 | |||||
4459 | /// Given an instruction or constant expr, see if we can fold the operation | ||||
4460 | /// into the addressing mode. If so, update the addressing mode and return | ||||
4461 | /// true, otherwise return false without modifying AddrMode. | ||||
4462 | /// If \p MovedAway is not NULL, it contains the information of whether or | ||||
4463 | /// not AddrInst has to be folded into the addressing mode on success. | ||||
4464 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing | ||||
4465 | /// because it has been moved away. | ||||
4466 | /// Thus AddrInst must not be added in the matched instructions. | ||||
4467 | /// This state can happen when AddrInst is a sext, since it may be moved away. | ||||
4468 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must | ||||
4469 | /// not be referenced anymore. | ||||
4470 | bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode, | ||||
4471 | unsigned Depth, | ||||
4472 | bool *MovedAway) { | ||||
4473 | // Avoid exponential behavior on extremely deep expression trees. | ||||
4474 | if (Depth >= 5) return false; | ||||
4475 | |||||
4476 | // By default, all matched instructions stay in place. | ||||
4477 | if (MovedAway) | ||||
4478 | *MovedAway = false; | ||||
4479 | |||||
4480 | switch (Opcode) { | ||||
4481 | case Instruction::PtrToInt: | ||||
4482 | // PtrToInt is always a noop, as we know that the int type is pointer sized. | ||||
4483 | return matchAddr(AddrInst->getOperand(0), Depth); | ||||
4484 | case Instruction::IntToPtr: { | ||||
4485 | auto AS = AddrInst->getType()->getPointerAddressSpace(); | ||||
4486 | auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS)); | ||||
4487 | // This inttoptr is a no-op if the integer type is pointer sized. | ||||
4488 | if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy) | ||||
4489 | return matchAddr(AddrInst->getOperand(0), Depth); | ||||
4490 | return false; | ||||
4491 | } | ||||
4492 | case Instruction::BitCast: | ||||
4493 | // BitCast is always a noop, and we can handle it as long as it is | ||||
4494 | // int->int or pointer->pointer (we don't want int<->fp or something). | ||||
4495 | if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() && | ||||
4496 | // Don't touch identity bitcasts. These were probably put here by LSR, | ||||
4497 | // and we don't want to mess around with them. Assume it knows what it | ||||
4498 | // is doing. | ||||
4499 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) | ||||
4500 | return matchAddr(AddrInst->getOperand(0), Depth); | ||||
4501 | return false; | ||||
4502 | case Instruction::AddrSpaceCast: { | ||||
4503 | unsigned SrcAS | ||||
4504 | = AddrInst->getOperand(0)->getType()->getPointerAddressSpace(); | ||||
4505 | unsigned DestAS = AddrInst->getType()->getPointerAddressSpace(); | ||||
4506 | if (TLI.getTargetMachine().isNoopAddrSpaceCast(SrcAS, DestAS)) | ||||
4507 | return matchAddr(AddrInst->getOperand(0), Depth); | ||||
4508 | return false; | ||||
4509 | } | ||||
4510 | case Instruction::Add: { | ||||
4511 | // Check to see if we can merge in the RHS then the LHS. If so, we win. | ||||
4512 | ExtAddrMode BackupAddrMode = AddrMode; | ||||
4513 | unsigned OldSize = AddrModeInsts.size(); | ||||
4514 | // Start a transaction at this point. | ||||
4515 | // The LHS may match but not the RHS. | ||||
4516 | // Therefore, we need a higher level restoration point to undo partially | ||||
4517 | // matched operation. | ||||
4518 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = | ||||
4519 | TPT.getRestorationPoint(); | ||||
4520 | |||||
4521 | AddrMode.InBounds = false; | ||||
4522 | if (matchAddr(AddrInst->getOperand(1), Depth+1) && | ||||
4523 | matchAddr(AddrInst->getOperand(0), Depth+1)) | ||||
4524 | return true; | ||||
4525 | |||||
4526 | // Restore the old addr mode info. | ||||
4527 | AddrMode = BackupAddrMode; | ||||
4528 | AddrModeInsts.resize(OldSize); | ||||
4529 | TPT.rollback(LastKnownGood); | ||||
4530 | |||||
4531 | // Otherwise this was over-aggressive. Try merging in the LHS then the RHS. | ||||
4532 | if (matchAddr(AddrInst->getOperand(0), Depth+1) && | ||||
4533 | matchAddr(AddrInst->getOperand(1), Depth+1)) | ||||
4534 | return true; | ||||
4535 | |||||
4536 | // Otherwise we definitely can't merge the ADD in. | ||||
4537 | AddrMode = BackupAddrMode; | ||||
4538 | AddrModeInsts.resize(OldSize); | ||||
4539 | TPT.rollback(LastKnownGood); | ||||
4540 | break; | ||||
4541 | } | ||||
4542 | //case Instruction::Or: | ||||
4543 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. | ||||
4544 | //break; | ||||
4545 | case Instruction::Mul: | ||||
4546 | case Instruction::Shl: { | ||||
4547 | // Can only handle X*C and X << C. | ||||
4548 | AddrMode.InBounds = false; | ||||
4549 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); | ||||
4550 | if (!RHS || RHS->getBitWidth() > 64) | ||||
4551 | return false; | ||||
4552 | int64_t Scale = Opcode == Instruction::Shl | ||||
4553 | ? 1LL << RHS->getLimitedValue(RHS->getBitWidth() - 1) | ||||
4554 | : RHS->getSExtValue(); | ||||
4555 | |||||
4556 | return matchScaledValue(AddrInst->getOperand(0), Scale, Depth); | ||||
4557 | } | ||||
4558 | case Instruction::GetElementPtr: { | ||||
4559 | // Scan the GEP. We check it if it contains constant offsets and at most | ||||
4560 | // one variable offset. | ||||
4561 | int VariableOperand = -1; | ||||
4562 | unsigned VariableScale = 0; | ||||
4563 | |||||
4564 | int64_t ConstantOffset = 0; | ||||
4565 | gep_type_iterator GTI = gep_type_begin(AddrInst); | ||||
4566 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { | ||||
4567 | if (StructType *STy = GTI.getStructTypeOrNull()) { | ||||
4568 | const StructLayout *SL = DL.getStructLayout(STy); | ||||
4569 | unsigned Idx = | ||||
4570 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); | ||||
4571 | ConstantOffset += SL->getElementOffset(Idx); | ||||
4572 | } else { | ||||
4573 | TypeSize TS = DL.getTypeAllocSize(GTI.getIndexedType()); | ||||
4574 | if (TS.isNonZero()) { | ||||
4575 | // The optimisations below currently only work for fixed offsets. | ||||
4576 | if (TS.isScalable()) | ||||
4577 | return false; | ||||
4578 | int64_t TypeSize = TS.getFixedSize(); | ||||
4579 | if (ConstantInt *CI = | ||||
4580 | dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { | ||||
4581 | const APInt &CVal = CI->getValue(); | ||||
4582 | if (CVal.getMinSignedBits() <= 64) { | ||||
4583 | ConstantOffset += CVal.getSExtValue() * TypeSize; | ||||
4584 | continue; | ||||
4585 | } | ||||
4586 | } | ||||
4587 | // We only allow one variable index at the moment. | ||||
4588 | if (VariableOperand != -1) | ||||
4589 | return false; | ||||
4590 | |||||
4591 | // Remember the variable index. | ||||
4592 | VariableOperand = i; | ||||
4593 | VariableScale = TypeSize; | ||||
4594 | } | ||||
4595 | } | ||||
4596 | } | ||||
4597 | |||||
4598 | // A common case is for the GEP to only do a constant offset. In this case, | ||||
4599 | // just add it to the disp field and check validity. | ||||
4600 | if (VariableOperand == -1) { | ||||
4601 | AddrMode.BaseOffs += ConstantOffset; | ||||
4602 | if (ConstantOffset == 0 || | ||||
4603 | TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) { | ||||
4604 | // Check to see if we can fold the base pointer in too. | ||||
4605 | if (matchAddr(AddrInst->getOperand(0), Depth+1)) { | ||||
4606 | if (!cast<GEPOperator>(AddrInst)->isInBounds()) | ||||
4607 | AddrMode.InBounds = false; | ||||
4608 | return true; | ||||
4609 | } | ||||
4610 | } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) && | ||||
4611 | TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 && | ||||
4612 | ConstantOffset > 0) { | ||||
4613 | // Record GEPs with non-zero offsets as candidates for splitting in the | ||||
4614 | // event that the offset cannot fit into the r+i addressing mode. | ||||
4615 | // Simple and common case that only one GEP is used in calculating the | ||||
4616 | // address for the memory access. | ||||
4617 | Value *Base = AddrInst->getOperand(0); | ||||
4618 | auto *BaseI = dyn_cast<Instruction>(Base); | ||||
4619 | auto *GEP = cast<GetElementPtrInst>(AddrInst); | ||||
4620 | if (isa<Argument>(Base) || isa<GlobalValue>(Base) || | ||||
4621 | (BaseI && !isa<CastInst>(BaseI) && | ||||
4622 | !isa<GetElementPtrInst>(BaseI))) { | ||||
4623 | // Make sure the parent block allows inserting non-PHI instructions | ||||
4624 | // before the terminator. | ||||
4625 | BasicBlock *Parent = | ||||
4626 | BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock(); | ||||
4627 | if (!Parent->getTerminator()->isEHPad()) | ||||
4628 | LargeOffsetGEP = std::make_pair(GEP, ConstantOffset); | ||||
4629 | } | ||||
4630 | } | ||||
4631 | AddrMode.BaseOffs -= ConstantOffset; | ||||
4632 | return false; | ||||
4633 | } | ||||
4634 | |||||
4635 | // Save the valid addressing mode in case we can't match. | ||||
4636 | ExtAddrMode BackupAddrMode = AddrMode; | ||||
4637 | unsigned OldSize = AddrModeInsts.size(); | ||||
4638 | |||||
4639 | // See if the scale and offset amount is valid for this target. | ||||
4640 | AddrMode.BaseOffs += ConstantOffset; | ||||
4641 | if (!cast<GEPOperator>(AddrInst)->isInBounds()) | ||||
4642 | AddrMode.InBounds = false; | ||||
4643 | |||||
4644 | // Match the base operand of the GEP. | ||||
4645 | if (!matchAddr(AddrInst->getOperand(0), Depth+1)) { | ||||
4646 | // If it couldn't be matched, just stuff the value in a register. | ||||
4647 | if (AddrMode.HasBaseReg) { | ||||
4648 | AddrMode = BackupAddrMode; | ||||
4649 | AddrModeInsts.resize(OldSize); | ||||
4650 | return false; | ||||
4651 | } | ||||
4652 | AddrMode.HasBaseReg = true; | ||||
4653 | AddrMode.BaseReg = AddrInst->getOperand(0); | ||||
4654 | } | ||||
4655 | |||||
4656 | // Match the remaining variable portion of the GEP. | ||||
4657 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, | ||||
4658 | Depth)) { | ||||
4659 | // If it couldn't be matched, try stuffing the base into a register | ||||
4660 | // instead of matching it, and retrying the match of the scale. | ||||
4661 | AddrMode = BackupAddrMode; | ||||
4662 | AddrModeInsts.resize(OldSize); | ||||
4663 | if (AddrMode.HasBaseReg) | ||||
4664 | return false; | ||||
4665 | AddrMode.HasBaseReg = true; | ||||
4666 | AddrMode.BaseReg = AddrInst->getOperand(0); | ||||
4667 | AddrMode.BaseOffs += ConstantOffset; | ||||
4668 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), | ||||
4669 | VariableScale, Depth)) { | ||||
4670 | // If even that didn't work, bail. | ||||
4671 | AddrMode = BackupAddrMode; | ||||
4672 | AddrModeInsts.resize(OldSize); | ||||
4673 | return false; | ||||
4674 | } | ||||
4675 | } | ||||
4676 | |||||
4677 | return true; | ||||
4678 | } | ||||
4679 | case Instruction::SExt: | ||||
4680 | case Instruction::ZExt: { | ||||
4681 | Instruction *Ext = dyn_cast<Instruction>(AddrInst); | ||||
4682 | if (!Ext) | ||||
4683 | return false; | ||||
4684 | |||||
4685 | // Try to move this ext out of the way of the addressing mode. | ||||
4686 | // Ask for a method for doing so. | ||||
4687 | TypePromotionHelper::Action TPH = | ||||
4688 | TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts); | ||||
4689 | if (!TPH) | ||||
4690 | return false; | ||||
4691 | |||||
4692 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = | ||||
4693 | TPT.getRestorationPoint(); | ||||
4694 | unsigned CreatedInstsCost = 0; | ||||
4695 | unsigned ExtCost = !TLI.isExtFree(Ext); | ||||
4696 | Value *PromotedOperand = | ||||
4697 | TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI); | ||||
4698 | // SExt has been moved away. | ||||
4699 | // Thus either it will be rematched later in the recursive calls or it is | ||||
4700 | // gone. Anyway, we must not fold it into the addressing mode at this point. | ||||
4701 | // E.g., | ||||
4702 | // op = add opnd, 1 | ||||
4703 | // idx = ext op | ||||
4704 | // addr = gep base, idx | ||||
4705 | // is now: | ||||
4706 | // promotedOpnd = ext opnd <- no match here | ||||
4707 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) | ||||
4708 | // addr = gep base, op <- match | ||||
4709 | if (MovedAway) | ||||
4710 | *MovedAway = true; | ||||
4711 | |||||
4712 | assert(PromotedOperand &&(static_cast <bool> (PromotedOperand && "TypePromotionHelper should have filtered out those cases" ) ? void (0) : __assert_fail ("PromotedOperand && \"TypePromotionHelper should have filtered out those cases\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 4713, __extension__ __PRETTY_FUNCTION__ )) | ||||
4713 | "TypePromotionHelper should have filtered out those cases")(static_cast <bool> (PromotedOperand && "TypePromotionHelper should have filtered out those cases" ) ? void (0) : __assert_fail ("PromotedOperand && \"TypePromotionHelper should have filtered out those cases\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 4713, __extension__ __PRETTY_FUNCTION__ )); | ||||
4714 | |||||
4715 | ExtAddrMode BackupAddrMode = AddrMode; | ||||
4716 | unsigned OldSize = AddrModeInsts.size(); | ||||
4717 | |||||
4718 | if (!matchAddr(PromotedOperand, Depth) || | ||||
4719 | // The total of the new cost is equal to the cost of the created | ||||
4720 | // instructions. | ||||
4721 | // The total of the old cost is equal to the cost of the extension plus | ||||
4722 | // what we have saved in the addressing mode. | ||||
4723 | !isPromotionProfitable(CreatedInstsCost, | ||||
4724 | ExtCost + (AddrModeInsts.size() - OldSize), | ||||
4725 | PromotedOperand)) { | ||||
4726 | AddrMode = BackupAddrMode; | ||||
4727 | AddrModeInsts.resize(OldSize); | ||||
4728 | LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Sign extension does not pay off: rollback\n" ; } } while (false); | ||||
4729 | TPT.rollback(LastKnownGood); | ||||
4730 | return false; | ||||
4731 | } | ||||
4732 | return true; | ||||
4733 | } | ||||
4734 | } | ||||
4735 | return false; | ||||
4736 | } | ||||
4737 | |||||
4738 | /// If we can, try to add the value of 'Addr' into the current addressing mode. | ||||
4739 | /// If Addr can't be added to AddrMode this returns false and leaves AddrMode | ||||
4740 | /// unmodified. This assumes that Addr is either a pointer type or intptr_t | ||||
4741 | /// for the target. | ||||
4742 | /// | ||||
4743 | bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) { | ||||
4744 | // Start a transaction at this point that we will rollback if the matching | ||||
4745 | // fails. | ||||
4746 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = | ||||
4747 | TPT.getRestorationPoint(); | ||||
4748 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { | ||||
4749 | if (CI->getValue().isSignedIntN(64)) { | ||||
4750 | // Fold in immediates if legal for the target. | ||||
4751 | AddrMode.BaseOffs += CI->getSExtValue(); | ||||
4752 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) | ||||
4753 | return true; | ||||
4754 | AddrMode.BaseOffs -= CI->getSExtValue(); | ||||
4755 | } | ||||
4756 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { | ||||
4757 | // If this is a global variable, try to fold it into the addressing mode. | ||||
4758 | if (!AddrMode.BaseGV) { | ||||
4759 | AddrMode.BaseGV = GV; | ||||
4760 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) | ||||
4761 | return true; | ||||
4762 | AddrMode.BaseGV = nullptr; | ||||
4763 | } | ||||
4764 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { | ||||
4765 | ExtAddrMode BackupAddrMode = AddrMode; | ||||
4766 | unsigned OldSize = AddrModeInsts.size(); | ||||
4767 | |||||
4768 | // Check to see if it is possible to fold this operation. | ||||
4769 | bool MovedAway = false; | ||||
4770 | if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { | ||||
4771 | // This instruction may have been moved away. If so, there is nothing | ||||
4772 | // to check here. | ||||
4773 | if (MovedAway) | ||||
4774 | return true; | ||||
4775 | // Okay, it's possible to fold this. Check to see if it is actually | ||||
4776 | // *profitable* to do so. We use a simple cost model to avoid increasing | ||||
4777 | // register pressure too much. | ||||
4778 | if (I->hasOneUse() || | ||||
4779 | isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { | ||||
4780 | AddrModeInsts.push_back(I); | ||||
4781 | return true; | ||||
4782 | } | ||||
4783 | |||||
4784 | // It isn't profitable to do this, roll back. | ||||
4785 | //cerr << "NOT FOLDING: " << *I; | ||||
4786 | AddrMode = BackupAddrMode; | ||||
4787 | AddrModeInsts.resize(OldSize); | ||||
4788 | TPT.rollback(LastKnownGood); | ||||
4789 | } | ||||
4790 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { | ||||
4791 | if (matchOperationAddr(CE, CE->getOpcode(), Depth)) | ||||
4792 | return true; | ||||
4793 | TPT.rollback(LastKnownGood); | ||||
4794 | } else if (isa<ConstantPointerNull>(Addr)) { | ||||
4795 | // Null pointer gets folded without affecting the addressing mode. | ||||
4796 | return true; | ||||
4797 | } | ||||
4798 | |||||
4799 | // Worse case, the target should support [reg] addressing modes. :) | ||||
4800 | if (!AddrMode.HasBaseReg) { | ||||
4801 | AddrMode.HasBaseReg = true; | ||||
4802 | AddrMode.BaseReg = Addr; | ||||
4803 | // Still check for legality in case the target supports [imm] but not [i+r]. | ||||
4804 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) | ||||
4805 | return true; | ||||
4806 | AddrMode.HasBaseReg = false; | ||||
4807 | AddrMode.BaseReg = nullptr; | ||||
4808 | } | ||||
4809 | |||||
4810 | // If the base register is already taken, see if we can do [r+r]. | ||||
4811 | if (AddrMode.Scale == 0) { | ||||
4812 | AddrMode.Scale = 1; | ||||
4813 | AddrMode.ScaledReg = Addr; | ||||
4814 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) | ||||
4815 | return true; | ||||
4816 | AddrMode.Scale = 0; | ||||
4817 | AddrMode.ScaledReg = nullptr; | ||||
4818 | } | ||||
4819 | // Couldn't match. | ||||
4820 | TPT.rollback(LastKnownGood); | ||||
4821 | return false; | ||||
4822 | } | ||||
4823 | |||||
4824 | /// Check to see if all uses of OpVal by the specified inline asm call are due | ||||
4825 | /// to memory operands. If so, return true, otherwise return false. | ||||
4826 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, | ||||
4827 | const TargetLowering &TLI, | ||||
4828 | const TargetRegisterInfo &TRI) { | ||||
4829 | const Function *F = CI->getFunction(); | ||||
4830 | TargetLowering::AsmOperandInfoVector TargetConstraints = | ||||
4831 | TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, *CI); | ||||
4832 | |||||
4833 | for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) { | ||||
4834 | // Compute the constraint code and ConstraintType to use. | ||||
4835 | TLI.ComputeConstraintToUse(OpInfo, SDValue()); | ||||
4836 | |||||
4837 | // If this asm operand is our Value*, and if it isn't an indirect memory | ||||
4838 | // operand, we can't fold it! TODO: Also handle C_Address? | ||||
4839 | if (OpInfo.CallOperandVal == OpVal && | ||||
4840 | (OpInfo.ConstraintType != TargetLowering::C_Memory || | ||||
4841 | !OpInfo.isIndirect)) | ||||
4842 | return false; | ||||
4843 | } | ||||
4844 | |||||
4845 | return true; | ||||
4846 | } | ||||
4847 | |||||
4848 | // Max number of memory uses to look at before aborting the search to conserve | ||||
4849 | // compile time. | ||||
4850 | static constexpr int MaxMemoryUsesToScan = 20; | ||||
4851 | |||||
4852 | /// Recursively walk all the uses of I until we find a memory use. | ||||
4853 | /// If we find an obviously non-foldable instruction, return true. | ||||
4854 | /// Add accessed addresses and types to MemoryUses. | ||||
4855 | static bool FindAllMemoryUses( | ||||
4856 | Instruction *I, SmallVectorImpl<std::pair<Value *, Type *>> &MemoryUses, | ||||
4857 | SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI, | ||||
4858 | const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI, | ||||
4859 | BlockFrequencyInfo *BFI, int SeenInsts = 0) { | ||||
4860 | // If we already considered this instruction, we're done. | ||||
4861 | if (!ConsideredInsts.insert(I).second) | ||||
4862 | return false; | ||||
4863 | |||||
4864 | // If this is an obviously unfoldable instruction, bail out. | ||||
4865 | if (!MightBeFoldableInst(I)) | ||||
4866 | return true; | ||||
4867 | |||||
4868 | // Loop over all the uses, recursively processing them. | ||||
4869 | for (Use &U : I->uses()) { | ||||
4870 | // Conservatively return true if we're seeing a large number or a deep chain | ||||
4871 | // of users. This avoids excessive compilation times in pathological cases. | ||||
4872 | if (SeenInsts++ >= MaxMemoryUsesToScan) | ||||
4873 | return true; | ||||
4874 | |||||
4875 | Instruction *UserI = cast<Instruction>(U.getUser()); | ||||
4876 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { | ||||
4877 | MemoryUses.push_back({U.get(), LI->getType()}); | ||||
4878 | continue; | ||||
4879 | } | ||||
4880 | |||||
4881 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { | ||||
4882 | if (U.getOperandNo() != StoreInst::getPointerOperandIndex()) | ||||
4883 | return true; // Storing addr, not into addr. | ||||
4884 | MemoryUses.push_back({U.get(), SI->getValueOperand()->getType()}); | ||||
4885 | continue; | ||||
4886 | } | ||||
4887 | |||||
4888 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) { | ||||
4889 | if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex()) | ||||
4890 | return true; // Storing addr, not into addr. | ||||
4891 | MemoryUses.push_back({U.get(), RMW->getValOperand()->getType()}); | ||||
4892 | continue; | ||||
4893 | } | ||||
4894 | |||||
4895 | if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) { | ||||
4896 | if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex()) | ||||
4897 | return true; // Storing addr, not into addr. | ||||
4898 | MemoryUses.push_back({U.get(), CmpX->getCompareOperand()->getType()}); | ||||
4899 | continue; | ||||
4900 | } | ||||
4901 | |||||
4902 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { | ||||
4903 | if (CI->hasFnAttr(Attribute::Cold)) { | ||||
4904 | // If this is a cold call, we can sink the addressing calculation into | ||||
4905 | // the cold path. See optimizeCallInst | ||||
4906 | bool OptForSize = OptSize || | ||||
4907 | llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI); | ||||
4908 | if (!OptForSize) | ||||
4909 | continue; | ||||
4910 | } | ||||
4911 | |||||
4912 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand()); | ||||
4913 | if (!IA) return true; | ||||
4914 | |||||
4915 | // If this is a memory operand, we're cool, otherwise bail out. | ||||
4916 | if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI)) | ||||
4917 | return true; | ||||
4918 | continue; | ||||
4919 | } | ||||
4920 | |||||
4921 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize, | ||||
4922 | PSI, BFI, SeenInsts)) | ||||
4923 | return true; | ||||
4924 | } | ||||
4925 | |||||
4926 | return false; | ||||
4927 | } | ||||
4928 | |||||
4929 | /// Return true if Val is already known to be live at the use site that we're | ||||
4930 | /// folding it into. If so, there is no cost to include it in the addressing | ||||
4931 | /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the | ||||
4932 | /// instruction already. | ||||
4933 | bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, | ||||
4934 | Value *KnownLive2) { | ||||
4935 | // If Val is either of the known-live values, we know it is live! | ||||
4936 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) | ||||
4937 | return true; | ||||
4938 | |||||
4939 | // All values other than instructions and arguments (e.g. constants) are live. | ||||
4940 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; | ||||
4941 | |||||
4942 | // If Val is a constant sized alloca in the entry block, it is live, this is | ||||
4943 | // true because it is just a reference to the stack/frame pointer, which is | ||||
4944 | // live for the whole function. | ||||
4945 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) | ||||
4946 | if (AI->isStaticAlloca()) | ||||
4947 | return true; | ||||
4948 | |||||
4949 | // Check to see if this value is already used in the memory instruction's | ||||
4950 | // block. If so, it's already live into the block at the very least, so we | ||||
4951 | // can reasonably fold it. | ||||
4952 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); | ||||
4953 | } | ||||
4954 | |||||
4955 | /// It is possible for the addressing mode of the machine to fold the specified | ||||
4956 | /// instruction into a load or store that ultimately uses it. | ||||
4957 | /// However, the specified instruction has multiple uses. | ||||
4958 | /// Given this, it may actually increase register pressure to fold it | ||||
4959 | /// into the load. For example, consider this code: | ||||
4960 | /// | ||||
4961 | /// X = ... | ||||
4962 | /// Y = X+1 | ||||
4963 | /// use(Y) -> nonload/store | ||||
4964 | /// Z = Y+1 | ||||
4965 | /// load Z | ||||
4966 | /// | ||||
4967 | /// In this case, Y has multiple uses, and can be folded into the load of Z | ||||
4968 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to | ||||
4969 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one | ||||
4970 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the | ||||
4971 | /// number of computations either. | ||||
4972 | /// | ||||
4973 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If | ||||
4974 | /// X was live across 'load Z' for other reasons, we actually *would* want to | ||||
4975 | /// fold the addressing mode in the Z case. This would make Y die earlier. | ||||
4976 | bool AddressingModeMatcher:: | ||||
4977 | isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, | ||||
4978 | ExtAddrMode &AMAfter) { | ||||
4979 | if (IgnoreProfitability) return true; | ||||
4980 | |||||
4981 | // AMBefore is the addressing mode before this instruction was folded into it, | ||||
4982 | // and AMAfter is the addressing mode after the instruction was folded. Get | ||||
4983 | // the set of registers referenced by AMAfter and subtract out those | ||||
4984 | // referenced by AMBefore: this is the set of values which folding in this | ||||
4985 | // address extends the lifetime of. | ||||
4986 | // | ||||
4987 | // Note that there are only two potential values being referenced here, | ||||
4988 | // BaseReg and ScaleReg (global addresses are always available, as are any | ||||
4989 | // folded immediates). | ||||
4990 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; | ||||
4991 | |||||
4992 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their | ||||
4993 | // lifetime wasn't extended by adding this instruction. | ||||
4994 | if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) | ||||
4995 | BaseReg = nullptr; | ||||
4996 | if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) | ||||
4997 | ScaledReg = nullptr; | ||||
4998 | |||||
4999 | // If folding this instruction (and it's subexprs) didn't extend any live | ||||
5000 | // ranges, we're ok with it. | ||||
5001 | if (!BaseReg && !ScaledReg) | ||||
5002 | return true; | ||||
5003 | |||||
5004 | // If all uses of this instruction can have the address mode sunk into them, | ||||
5005 | // we can remove the addressing mode and effectively trade one live register | ||||
5006 | // for another (at worst.) In this context, folding an addressing mode into | ||||
5007 | // the use is just a particularly nice way of sinking it. | ||||
5008 | SmallVector<std::pair<Value *, Type *>, 16> MemoryUses; | ||||
5009 | SmallPtrSet<Instruction*, 16> ConsideredInsts; | ||||
5010 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize, | ||||
5011 | PSI, BFI)) | ||||
5012 | return false; // Has a non-memory, non-foldable use! | ||||
5013 | |||||
5014 | // Now that we know that all uses of this instruction are part of a chain of | ||||
5015 | // computation involving only operations that could theoretically be folded | ||||
5016 | // into a memory use, loop over each of these memory operation uses and see | ||||
5017 | // if they could *actually* fold the instruction. The assumption is that | ||||
5018 | // addressing modes are cheap and that duplicating the computation involved | ||||
5019 | // many times is worthwhile, even on a fastpath. For sinking candidates | ||||
5020 | // (i.e. cold call sites), this serves as a way to prevent excessive code | ||||
5021 | // growth since most architectures have some reasonable small and fast way to | ||||
5022 | // compute an effective address. (i.e LEA on x86) | ||||
5023 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; | ||||
5024 | for (const std::pair<Value *, Type *> &Pair : MemoryUses) { | ||||
5025 | Value *Address = Pair.first; | ||||
5026 | Type *AddressAccessTy = Pair.second; | ||||
5027 | unsigned AS = Address->getType()->getPointerAddressSpace(); | ||||
5028 | |||||
5029 | // Do a match against the root of this address, ignoring profitability. This | ||||
5030 | // will tell us if the addressing mode for the memory operation will | ||||
5031 | // *actually* cover the shared instruction. | ||||
5032 | ExtAddrMode Result; | ||||
5033 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr, | ||||
5034 | 0); | ||||
5035 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = | ||||
5036 | TPT.getRestorationPoint(); | ||||
5037 | AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn, | ||||
5038 | AddressAccessTy, AS, MemoryInst, Result, | ||||
5039 | InsertedInsts, PromotedInsts, TPT, | ||||
5040 | LargeOffsetGEP, OptSize, PSI, BFI); | ||||
5041 | Matcher.IgnoreProfitability = true; | ||||
5042 | bool Success = Matcher.matchAddr(Address, 0); | ||||
5043 | (void)Success; assert(Success && "Couldn't select *anything*?")(static_cast <bool> (Success && "Couldn't select *anything*?" ) ? void (0) : __assert_fail ("Success && \"Couldn't select *anything*?\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5043, __extension__ __PRETTY_FUNCTION__ )); | ||||
5044 | |||||
5045 | // The match was to check the profitability, the changes made are not | ||||
5046 | // part of the original matcher. Therefore, they should be dropped | ||||
5047 | // otherwise the original matcher will not present the right state. | ||||
5048 | TPT.rollback(LastKnownGood); | ||||
5049 | |||||
5050 | // If the match didn't cover I, then it won't be shared by it. | ||||
5051 | if (!is_contained(MatchedAddrModeInsts, I)) | ||||
5052 | return false; | ||||
5053 | |||||
5054 | MatchedAddrModeInsts.clear(); | ||||
5055 | } | ||||
5056 | |||||
5057 | return true; | ||||
5058 | } | ||||
5059 | |||||
5060 | /// Return true if the specified values are defined in a | ||||
5061 | /// different basic block than BB. | ||||
5062 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { | ||||
5063 | if (Instruction *I = dyn_cast<Instruction>(V)) | ||||
5064 | return I->getParent() != BB; | ||||
5065 | return false; | ||||
5066 | } | ||||
5067 | |||||
5068 | /// Sink addressing mode computation immediate before MemoryInst if doing so | ||||
5069 | /// can be done without increasing register pressure. The need for the | ||||
5070 | /// register pressure constraint means this can end up being an all or nothing | ||||
5071 | /// decision for all uses of the same addressing computation. | ||||
5072 | /// | ||||
5073 | /// Load and Store Instructions often have addressing modes that can do | ||||
5074 | /// significant amounts of computation. As such, instruction selection will try | ||||
5075 | /// to get the load or store to do as much computation as possible for the | ||||
5076 | /// program. The problem is that isel can only see within a single block. As | ||||
5077 | /// such, we sink as much legal addressing mode work into the block as possible. | ||||
5078 | /// | ||||
5079 | /// This method is used to optimize both load/store and inline asms with memory | ||||
5080 | /// operands. It's also used to sink addressing computations feeding into cold | ||||
5081 | /// call sites into their (cold) basic block. | ||||
5082 | /// | ||||
5083 | /// The motivation for handling sinking into cold blocks is that doing so can | ||||
5084 | /// both enable other address mode sinking (by satisfying the register pressure | ||||
5085 | /// constraint above), and reduce register pressure globally (by removing the | ||||
5086 | /// addressing mode computation from the fast path entirely.). | ||||
5087 | bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, | ||||
5088 | Type *AccessTy, unsigned AddrSpace) { | ||||
5089 | Value *Repl = Addr; | ||||
5090 | |||||
5091 | // Try to collapse single-value PHI nodes. This is necessary to undo | ||||
5092 | // unprofitable PRE transformations. | ||||
5093 | SmallVector<Value*, 8> worklist; | ||||
5094 | SmallPtrSet<Value*, 16> Visited; | ||||
5095 | worklist.push_back(Addr); | ||||
5096 | |||||
5097 | // Use a worklist to iteratively look through PHI and select nodes, and | ||||
5098 | // ensure that the addressing mode obtained from the non-PHI/select roots of | ||||
5099 | // the graph are compatible. | ||||
5100 | bool PhiOrSelectSeen = false; | ||||
5101 | SmallVector<Instruction*, 16> AddrModeInsts; | ||||
5102 | const SimplifyQuery SQ(*DL, TLInfo); | ||||
5103 | AddressingModeCombiner AddrModes(SQ, Addr); | ||||
5104 | TypePromotionTransaction TPT(RemovedInsts); | ||||
5105 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = | ||||
5106 | TPT.getRestorationPoint(); | ||||
5107 | while (!worklist.empty()) { | ||||
5108 | Value *V = worklist.pop_back_val(); | ||||
5109 | |||||
5110 | // We allow traversing cyclic Phi nodes. | ||||
5111 | // In case of success after this loop we ensure that traversing through | ||||
5112 | // Phi nodes ends up with all cases to compute address of the form | ||||
5113 | // BaseGV + Base + Scale * Index + Offset | ||||
5114 | // where Scale and Offset are constans and BaseGV, Base and Index | ||||
5115 | // are exactly the same Values in all cases. | ||||
5116 | // It means that BaseGV, Scale and Offset dominate our memory instruction | ||||
5117 | // and have the same value as they had in address computation represented | ||||
5118 | // as Phi. So we can safely sink address computation to memory instruction. | ||||
5119 | if (!Visited.insert(V).second) | ||||
5120 | continue; | ||||
5121 | |||||
5122 | // For a PHI node, push all of its incoming values. | ||||
5123 | if (PHINode *P = dyn_cast<PHINode>(V)) { | ||||
5124 | append_range(worklist, P->incoming_values()); | ||||
5125 | PhiOrSelectSeen = true; | ||||
5126 | continue; | ||||
5127 | } | ||||
5128 | // Similar for select. | ||||
5129 | if (SelectInst *SI = dyn_cast<SelectInst>(V)) { | ||||
5130 | worklist.push_back(SI->getFalseValue()); | ||||
5131 | worklist.push_back(SI->getTrueValue()); | ||||
5132 | PhiOrSelectSeen = true; | ||||
5133 | continue; | ||||
5134 | } | ||||
5135 | |||||
5136 | // For non-PHIs, determine the addressing mode being computed. Note that | ||||
5137 | // the result may differ depending on what other uses our candidate | ||||
5138 | // addressing instructions might have. | ||||
5139 | AddrModeInsts.clear(); | ||||
5140 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr, | ||||
5141 | 0); | ||||
5142 | // Defer the query (and possible computation of) the dom tree to point of | ||||
5143 | // actual use. It's expected that most address matches don't actually need | ||||
5144 | // the domtree. | ||||
5145 | auto getDTFn = [MemoryInst, this]() -> const DominatorTree & { | ||||
5146 | Function *F = MemoryInst->getParent()->getParent(); | ||||
5147 | return this->getDT(*F); | ||||
5148 | }; | ||||
5149 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( | ||||
5150 | V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *LI, getDTFn, | ||||
5151 | *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI, | ||||
5152 | BFI.get()); | ||||
5153 | |||||
5154 | GetElementPtrInst *GEP = LargeOffsetGEP.first; | ||||
5155 | if (GEP && !NewGEPBases.count(GEP)) { | ||||
5156 | // If splitting the underlying data structure can reduce the offset of a | ||||
5157 | // GEP, collect the GEP. Skip the GEPs that are the new bases of | ||||
5158 | // previously split data structures. | ||||
5159 | LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP); | ||||
5160 | if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end()) | ||||
5161 | LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size(); | ||||
5162 | } | ||||
5163 | |||||
5164 | NewAddrMode.OriginalValue = V; | ||||
5165 | if (!AddrModes.addNewAddrMode(NewAddrMode)) | ||||
5166 | break; | ||||
5167 | } | ||||
5168 | |||||
5169 | // Try to combine the AddrModes we've collected. If we couldn't collect any, | ||||
5170 | // or we have multiple but either couldn't combine them or combining them | ||||
5171 | // wouldn't do anything useful, bail out now. | ||||
5172 | if (!AddrModes.combineAddrModes()) { | ||||
5173 | TPT.rollback(LastKnownGood); | ||||
5174 | return false; | ||||
5175 | } | ||||
5176 | bool Modified = TPT.commit(); | ||||
5177 | |||||
5178 | // Get the combined AddrMode (or the only AddrMode, if we only had one). | ||||
5179 | ExtAddrMode AddrMode = AddrModes.getAddrMode(); | ||||
5180 | |||||
5181 | // If all the instructions matched are already in this BB, don't do anything. | ||||
5182 | // If we saw a Phi node then it is not local definitely, and if we saw a select | ||||
5183 | // then we want to push the address calculation past it even if it's already | ||||
5184 | // in this BB. | ||||
5185 | if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) { | ||||
5186 | return IsNonLocalValue(V, MemoryInst->getParent()); | ||||
5187 | })) { | ||||
5188 | LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrModedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n"; } } while (false) | ||||
5189 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n"; } } while (false); | ||||
5190 | return Modified; | ||||
5191 | } | ||||
5192 | |||||
5193 | // Insert this computation right after this user. Since our caller is | ||||
5194 | // scanning from the top of the BB to the bottom, reuse of the expr are | ||||
5195 | // guaranteed to happen later. | ||||
5196 | IRBuilder<> Builder(MemoryInst); | ||||
5197 | |||||
5198 | // Now that we determined the addressing expression we want to use and know | ||||
5199 | // that we have to sink it into this block. Check to see if we have already | ||||
5200 | // done this for some other load/store instr in this block. If so, reuse | ||||
5201 | // the computation. Before attempting reuse, check if the address is valid | ||||
5202 | // as it may have been erased. | ||||
5203 | |||||
5204 | WeakTrackingVH SunkAddrVH = SunkAddrs[Addr]; | ||||
5205 | |||||
5206 | Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr; | ||||
5207 | if (SunkAddr) { | ||||
5208 | LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrModedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for " << *MemoryInst << "\n"; } } while (false) | ||||
5209 | << " for " << *MemoryInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for " << *MemoryInst << "\n"; } } while (false); | ||||
5210 | if (SunkAddr->getType() != Addr->getType()) | ||||
5211 | SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); | ||||
5212 | } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() && | ||||
5213 | SubtargetInfo->addrSinkUsingGEPs())) { | ||||
5214 | // By default, we use the GEP-based method when AA is used later. This | ||||
5215 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. | ||||
5216 | LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrModedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " << *MemoryInst << "\n"; } } while (false) | ||||
5217 | << " for " << *MemoryInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " << *MemoryInst << "\n"; } } while (false); | ||||
5218 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); | ||||
5219 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; | ||||
5220 | |||||
5221 | // First, find the pointer. | ||||
5222 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { | ||||
5223 | ResultPtr = AddrMode.BaseReg; | ||||
5224 | AddrMode.BaseReg = nullptr; | ||||
5225 | } | ||||
5226 | |||||
5227 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { | ||||
5228 | // We can't add more than one pointer together, nor can we scale a | ||||
5229 | // pointer (both of which seem meaningless). | ||||
5230 | if (ResultPtr || AddrMode.Scale != 1) | ||||
5231 | return Modified; | ||||
5232 | |||||
5233 | ResultPtr = AddrMode.ScaledReg; | ||||
5234 | AddrMode.Scale = 0; | ||||
5235 | } | ||||
5236 | |||||
5237 | // It is only safe to sign extend the BaseReg if we know that the math | ||||
5238 | // required to create it did not overflow before we extend it. Since | ||||
5239 | // the original IR value was tossed in favor of a constant back when | ||||
5240 | // the AddrMode was created we need to bail out gracefully if widths | ||||
5241 | // do not match instead of extending it. | ||||
5242 | // | ||||
5243 | // (See below for code to add the scale.) | ||||
5244 | if (AddrMode.Scale) { | ||||
5245 | Type *ScaledRegTy = AddrMode.ScaledReg->getType(); | ||||
5246 | if (cast<IntegerType>(IntPtrTy)->getBitWidth() > | ||||
5247 | cast<IntegerType>(ScaledRegTy)->getBitWidth()) | ||||
5248 | return Modified; | ||||
5249 | } | ||||
5250 | |||||
5251 | if (AddrMode.BaseGV) { | ||||
5252 | if (ResultPtr) | ||||
5253 | return Modified; | ||||
5254 | |||||
5255 | ResultPtr = AddrMode.BaseGV; | ||||
5256 | } | ||||
5257 | |||||
5258 | // If the real base value actually came from an inttoptr, then the matcher | ||||
5259 | // will look through it and provide only the integer value. In that case, | ||||
5260 | // use it here. | ||||
5261 | if (!DL->isNonIntegralPointerType(Addr->getType())) { | ||||
5262 | if (!ResultPtr && AddrMode.BaseReg) { | ||||
5263 | ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), | ||||
5264 | "sunkaddr"); | ||||
5265 | AddrMode.BaseReg = nullptr; | ||||
5266 | } else if (!ResultPtr && AddrMode.Scale == 1) { | ||||
5267 | ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), | ||||
5268 | "sunkaddr"); | ||||
5269 | AddrMode.Scale = 0; | ||||
5270 | } | ||||
5271 | } | ||||
5272 | |||||
5273 | if (!ResultPtr && | ||||
5274 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { | ||||
5275 | SunkAddr = Constant::getNullValue(Addr->getType()); | ||||
5276 | } else if (!ResultPtr) { | ||||
5277 | return Modified; | ||||
5278 | } else { | ||||
5279 | Type *I8PtrTy = | ||||
5280 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); | ||||
5281 | Type *I8Ty = Builder.getInt8Ty(); | ||||
5282 | |||||
5283 | // Start with the base register. Do this first so that subsequent address | ||||
5284 | // matching finds it last, which will prevent it from trying to match it | ||||
5285 | // as the scaled value in case it happens to be a mul. That would be | ||||
5286 | // problematic if we've sunk a different mul for the scale, because then | ||||
5287 | // we'd end up sinking both muls. | ||||
5288 | if (AddrMode.BaseReg) { | ||||
5289 | Value *V = AddrMode.BaseReg; | ||||
5290 | if (V->getType() != IntPtrTy) | ||||
5291 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); | ||||
5292 | |||||
5293 | ResultIndex = V; | ||||
5294 | } | ||||
5295 | |||||
5296 | // Add the scale value. | ||||
5297 | if (AddrMode.Scale) { | ||||
5298 | Value *V = AddrMode.ScaledReg; | ||||
5299 | if (V->getType() == IntPtrTy) { | ||||
5300 | // done. | ||||
5301 | } else { | ||||
5302 | assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <(static_cast <bool> (cast<IntegerType>(IntPtrTy)-> getBitWidth() < cast<IntegerType>(V->getType())-> getBitWidth() && "We can't transform if ScaledReg is too narrow" ) ? void (0) : __assert_fail ("cast<IntegerType>(IntPtrTy)->getBitWidth() < cast<IntegerType>(V->getType())->getBitWidth() && \"We can't transform if ScaledReg is too narrow\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5304, __extension__ __PRETTY_FUNCTION__ )) | ||||
5303 | cast<IntegerType>(V->getType())->getBitWidth() &&(static_cast <bool> (cast<IntegerType>(IntPtrTy)-> getBitWidth() < cast<IntegerType>(V->getType())-> getBitWidth() && "We can't transform if ScaledReg is too narrow" ) ? void (0) : __assert_fail ("cast<IntegerType>(IntPtrTy)->getBitWidth() < cast<IntegerType>(V->getType())->getBitWidth() && \"We can't transform if ScaledReg is too narrow\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5304, __extension__ __PRETTY_FUNCTION__ )) | ||||
5304 | "We can't transform if ScaledReg is too narrow")(static_cast <bool> (cast<IntegerType>(IntPtrTy)-> getBitWidth() < cast<IntegerType>(V->getType())-> getBitWidth() && "We can't transform if ScaledReg is too narrow" ) ? void (0) : __assert_fail ("cast<IntegerType>(IntPtrTy)->getBitWidth() < cast<IntegerType>(V->getType())->getBitWidth() && \"We can't transform if ScaledReg is too narrow\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5304, __extension__ __PRETTY_FUNCTION__ )); | ||||
5305 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); | ||||
5306 | } | ||||
5307 | |||||
5308 | if (AddrMode.Scale != 1) | ||||
5309 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), | ||||
5310 | "sunkaddr"); | ||||
5311 | if (ResultIndex) | ||||
5312 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); | ||||
5313 | else | ||||
5314 | ResultIndex = V; | ||||
5315 | } | ||||
5316 | |||||
5317 | // Add in the Base Offset if present. | ||||
5318 | if (AddrMode.BaseOffs) { | ||||
5319 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); | ||||
5320 | if (ResultIndex) { | ||||
5321 | // We need to add this separately from the scale above to help with | ||||
5322 | // SDAG consecutive load/store merging. | ||||
5323 | if (ResultPtr->getType() != I8PtrTy) | ||||
5324 | ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); | ||||
5325 | ResultPtr = | ||||
5326 | AddrMode.InBounds | ||||
5327 | ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex, | ||||
5328 | "sunkaddr") | ||||
5329 | : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); | ||||
5330 | } | ||||
5331 | |||||
5332 | ResultIndex = V; | ||||
5333 | } | ||||
5334 | |||||
5335 | if (!ResultIndex) { | ||||
5336 | SunkAddr = ResultPtr; | ||||
5337 | } else { | ||||
5338 | if (ResultPtr->getType() != I8PtrTy) | ||||
5339 | ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); | ||||
5340 | SunkAddr = | ||||
5341 | AddrMode.InBounds | ||||
5342 | ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex, | ||||
5343 | "sunkaddr") | ||||
5344 | : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); | ||||
5345 | } | ||||
5346 | |||||
5347 | if (SunkAddr->getType() != Addr->getType()) | ||||
5348 | SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); | ||||
5349 | } | ||||
5350 | } else { | ||||
5351 | // We'd require a ptrtoint/inttoptr down the line, which we can't do for | ||||
5352 | // non-integral pointers, so in that case bail out now. | ||||
5353 | Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr; | ||||
5354 | Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr; | ||||
5355 | PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy); | ||||
5356 | PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy); | ||||
5357 | if (DL->isNonIntegralPointerType(Addr->getType()) || | ||||
5358 | (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) || | ||||
5359 | (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) || | ||||
5360 | (AddrMode.BaseGV && | ||||
5361 | DL->isNonIntegralPointerType(AddrMode.BaseGV->getType()))) | ||||
5362 | return Modified; | ||||
5363 | |||||
5364 | LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrModedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " << *MemoryInst << "\n"; } } while (false) | ||||
5365 | << " for " << *MemoryInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " << *MemoryInst << "\n"; } } while (false); | ||||
5366 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); | ||||
5367 | Value *Result = nullptr; | ||||
5368 | |||||
5369 | // Start with the base register. Do this first so that subsequent address | ||||
5370 | // matching finds it last, which will prevent it from trying to match it | ||||
5371 | // as the scaled value in case it happens to be a mul. That would be | ||||
5372 | // problematic if we've sunk a different mul for the scale, because then | ||||
5373 | // we'd end up sinking both muls. | ||||
5374 | if (AddrMode.BaseReg) { | ||||
5375 | Value *V = AddrMode.BaseReg; | ||||
5376 | if (V->getType()->isPointerTy()) | ||||
5377 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); | ||||
5378 | if (V->getType() != IntPtrTy) | ||||
5379 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); | ||||
5380 | Result = V; | ||||
5381 | } | ||||
5382 | |||||
5383 | // Add the scale value. | ||||
5384 | if (AddrMode.Scale) { | ||||
5385 | Value *V = AddrMode.ScaledReg; | ||||
5386 | if (V->getType() == IntPtrTy) { | ||||
5387 | // done. | ||||
5388 | } else if (V->getType()->isPointerTy()) { | ||||
5389 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); | ||||
5390 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < | ||||
5391 | cast<IntegerType>(V->getType())->getBitWidth()) { | ||||
5392 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); | ||||
5393 | } else { | ||||
5394 | // It is only safe to sign extend the BaseReg if we know that the math | ||||
5395 | // required to create it did not overflow before we extend it. Since | ||||
5396 | // the original IR value was tossed in favor of a constant back when | ||||
5397 | // the AddrMode was created we need to bail out gracefully if widths | ||||
5398 | // do not match instead of extending it. | ||||
5399 | Instruction *I = dyn_cast_or_null<Instruction>(Result); | ||||
5400 | if (I && (Result != AddrMode.BaseReg)) | ||||
5401 | I->eraseFromParent(); | ||||
5402 | return Modified; | ||||
5403 | } | ||||
5404 | if (AddrMode.Scale != 1) | ||||
5405 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), | ||||
5406 | "sunkaddr"); | ||||
5407 | if (Result) | ||||
5408 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); | ||||
5409 | else | ||||
5410 | Result = V; | ||||
5411 | } | ||||
5412 | |||||
5413 | // Add in the BaseGV if present. | ||||
5414 | if (AddrMode.BaseGV) { | ||||
5415 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); | ||||
5416 | if (Result) | ||||
5417 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); | ||||
5418 | else | ||||
5419 | Result = V; | ||||
5420 | } | ||||
5421 | |||||
5422 | // Add in the Base Offset if present. | ||||
5423 | if (AddrMode.BaseOffs) { | ||||
5424 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); | ||||
5425 | if (Result) | ||||
5426 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); | ||||
5427 | else | ||||
5428 | Result = V; | ||||
5429 | } | ||||
5430 | |||||
5431 | if (!Result) | ||||
5432 | SunkAddr = Constant::getNullValue(Addr->getType()); | ||||
5433 | else | ||||
5434 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); | ||||
5435 | } | ||||
5436 | |||||
5437 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); | ||||
5438 | // Store the newly computed address into the cache. In the case we reused a | ||||
5439 | // value, this should be idempotent. | ||||
5440 | SunkAddrs[Addr] = WeakTrackingVH(SunkAddr); | ||||
5441 | |||||
5442 | // If we have no uses, recursively delete the value and all dead instructions | ||||
5443 | // using it. | ||||
5444 | if (Repl->use_empty()) { | ||||
5445 | resetIteratorIfInvalidatedWhileCalling(CurInstIterator->getParent(), [&]() { | ||||
5446 | RecursivelyDeleteTriviallyDeadInstructions( | ||||
5447 | Repl, TLInfo, nullptr, | ||||
5448 | [&](Value *V) { removeAllAssertingVHReferences(V); }); | ||||
5449 | }); | ||||
5450 | } | ||||
5451 | ++NumMemoryInsts; | ||||
5452 | return true; | ||||
5453 | } | ||||
5454 | |||||
5455 | /// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find | ||||
5456 | /// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can | ||||
5457 | /// only handle a 2 operand GEP in the same basic block or a splat constant | ||||
5458 | /// vector. The 2 operands to the GEP must have a scalar pointer and a vector | ||||
5459 | /// index. | ||||
5460 | /// | ||||
5461 | /// If the existing GEP has a vector base pointer that is splat, we can look | ||||
5462 | /// through the splat to find the scalar pointer. If we can't find a scalar | ||||
5463 | /// pointer there's nothing we can do. | ||||
5464 | /// | ||||
5465 | /// If we have a GEP with more than 2 indices where the middle indices are all | ||||
5466 | /// zeroes, we can replace it with 2 GEPs where the second has 2 operands. | ||||
5467 | /// | ||||
5468 | /// If the final index isn't a vector or is a splat, we can emit a scalar GEP | ||||
5469 | /// followed by a GEP with an all zeroes vector index. This will enable | ||||
5470 | /// SelectionDAGBuilder to use the scalar GEP as the uniform base and have a | ||||
5471 | /// zero index. | ||||
5472 | bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst, | ||||
5473 | Value *Ptr) { | ||||
5474 | Value *NewAddr; | ||||
5475 | |||||
5476 | if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) { | ||||
5477 | // Don't optimize GEPs that don't have indices. | ||||
5478 | if (!GEP->hasIndices()) | ||||
5479 | return false; | ||||
5480 | |||||
5481 | // If the GEP and the gather/scatter aren't in the same BB, don't optimize. | ||||
5482 | // FIXME: We should support this by sinking the GEP. | ||||
5483 | if (MemoryInst->getParent() != GEP->getParent()) | ||||
5484 | return false; | ||||
5485 | |||||
5486 | SmallVector<Value *, 2> Ops(GEP->operands()); | ||||
5487 | |||||
5488 | bool RewriteGEP = false; | ||||
5489 | |||||
5490 | if (Ops[0]->getType()->isVectorTy()) { | ||||
5491 | Ops[0] = getSplatValue(Ops[0]); | ||||
5492 | if (!Ops[0]) | ||||
5493 | return false; | ||||
5494 | RewriteGEP = true; | ||||
5495 | } | ||||
5496 | |||||
5497 | unsigned FinalIndex = Ops.size() - 1; | ||||
5498 | |||||
5499 | // Ensure all but the last index is 0. | ||||
5500 | // FIXME: This isn't strictly required. All that's required is that they are | ||||
5501 | // all scalars or splats. | ||||
5502 | for (unsigned i = 1; i < FinalIndex; ++i) { | ||||
5503 | auto *C = dyn_cast<Constant>(Ops[i]); | ||||
5504 | if (!C) | ||||
5505 | return false; | ||||
5506 | if (isa<VectorType>(C->getType())) | ||||
5507 | C = C->getSplatValue(); | ||||
5508 | auto *CI = dyn_cast_or_null<ConstantInt>(C); | ||||
5509 | if (!CI || !CI->isZero()) | ||||
5510 | return false; | ||||
5511 | // Scalarize the index if needed. | ||||
5512 | Ops[i] = CI; | ||||
5513 | } | ||||
5514 | |||||
5515 | // Try to scalarize the final index. | ||||
5516 | if (Ops[FinalIndex]->getType()->isVectorTy()) { | ||||
5517 | if (Value *V = getSplatValue(Ops[FinalIndex])) { | ||||
5518 | auto *C = dyn_cast<ConstantInt>(V); | ||||
5519 | // Don't scalarize all zeros vector. | ||||
5520 | if (!C || !C->isZero()) { | ||||
5521 | Ops[FinalIndex] = V; | ||||
5522 | RewriteGEP = true; | ||||
5523 | } | ||||
5524 | } | ||||
5525 | } | ||||
5526 | |||||
5527 | // If we made any changes or the we have extra operands, we need to generate | ||||
5528 | // new instructions. | ||||
5529 | if (!RewriteGEP && Ops.size() == 2) | ||||
5530 | return false; | ||||
5531 | |||||
5532 | auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); | ||||
5533 | |||||
5534 | IRBuilder<> Builder(MemoryInst); | ||||
5535 | |||||
5536 | Type *SourceTy = GEP->getSourceElementType(); | ||||
5537 | Type *ScalarIndexTy = DL->getIndexType(Ops[0]->getType()->getScalarType()); | ||||
5538 | |||||
5539 | // If the final index isn't a vector, emit a scalar GEP containing all ops | ||||
5540 | // and a vector GEP with all zeroes final index. | ||||
5541 | if (!Ops[FinalIndex]->getType()->isVectorTy()) { | ||||
5542 | NewAddr = Builder.CreateGEP(SourceTy, Ops[0], | ||||
5543 | makeArrayRef(Ops).drop_front()); | ||||
5544 | auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts); | ||||
5545 | auto *SecondTy = GetElementPtrInst::getIndexedType( | ||||
5546 | SourceTy, makeArrayRef(Ops).drop_front()); | ||||
5547 | NewAddr = | ||||
5548 | Builder.CreateGEP(SecondTy, NewAddr, Constant::getNullValue(IndexTy)); | ||||
5549 | } else { | ||||
5550 | Value *Base = Ops[0]; | ||||
5551 | Value *Index = Ops[FinalIndex]; | ||||
5552 | |||||
5553 | // Create a scalar GEP if there are more than 2 operands. | ||||
5554 | if (Ops.size() != 2) { | ||||
5555 | // Replace the last index with 0. | ||||
5556 | Ops[FinalIndex] = Constant::getNullValue(ScalarIndexTy); | ||||
5557 | Base = Builder.CreateGEP(SourceTy, Base, | ||||
5558 | makeArrayRef(Ops).drop_front()); | ||||
5559 | SourceTy = GetElementPtrInst::getIndexedType( | ||||
5560 | SourceTy, makeArrayRef(Ops).drop_front()); | ||||
5561 | } | ||||
5562 | |||||
5563 | // Now create the GEP with scalar pointer and vector index. | ||||
5564 | NewAddr = Builder.CreateGEP(SourceTy, Base, Index); | ||||
5565 | } | ||||
5566 | } else if (!isa<Constant>(Ptr)) { | ||||
5567 | // Not a GEP, maybe its a splat and we can create a GEP to enable | ||||
5568 | // SelectionDAGBuilder to use it as a uniform base. | ||||
5569 | Value *V = getSplatValue(Ptr); | ||||
5570 | if (!V) | ||||
5571 | return false; | ||||
5572 | |||||
5573 | auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); | ||||
5574 | |||||
5575 | IRBuilder<> Builder(MemoryInst); | ||||
5576 | |||||
5577 | // Emit a vector GEP with a scalar pointer and all 0s vector index. | ||||
5578 | Type *ScalarIndexTy = DL->getIndexType(V->getType()->getScalarType()); | ||||
5579 | auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts); | ||||
5580 | Type *ScalarTy; | ||||
5581 | if (cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() == | ||||
5582 | Intrinsic::masked_gather) { | ||||
5583 | ScalarTy = MemoryInst->getType()->getScalarType(); | ||||
5584 | } else { | ||||
5585 | assert(cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==(static_cast <bool> (cast<IntrinsicInst>(MemoryInst )->getIntrinsicID() == Intrinsic::masked_scatter) ? void ( 0) : __assert_fail ("cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() == Intrinsic::masked_scatter" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5586, __extension__ __PRETTY_FUNCTION__ )) | ||||
5586 | Intrinsic::masked_scatter)(static_cast <bool> (cast<IntrinsicInst>(MemoryInst )->getIntrinsicID() == Intrinsic::masked_scatter) ? void ( 0) : __assert_fail ("cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() == Intrinsic::masked_scatter" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5586, __extension__ __PRETTY_FUNCTION__ )); | ||||
5587 | ScalarTy = MemoryInst->getOperand(0)->getType()->getScalarType(); | ||||
5588 | } | ||||
5589 | NewAddr = Builder.CreateGEP(ScalarTy, V, Constant::getNullValue(IndexTy)); | ||||
5590 | } else { | ||||
5591 | // Constant, SelectionDAGBuilder knows to check if its a splat. | ||||
5592 | return false; | ||||
5593 | } | ||||
5594 | |||||
5595 | MemoryInst->replaceUsesOfWith(Ptr, NewAddr); | ||||
5596 | |||||
5597 | // If we have no uses, recursively delete the value and all dead instructions | ||||
5598 | // using it. | ||||
5599 | if (Ptr->use_empty()) | ||||
5600 | RecursivelyDeleteTriviallyDeadInstructions( | ||||
5601 | Ptr, TLInfo, nullptr, | ||||
5602 | [&](Value *V) { removeAllAssertingVHReferences(V); }); | ||||
5603 | |||||
5604 | return true; | ||||
5605 | } | ||||
5606 | |||||
5607 | /// If there are any memory operands, use OptimizeMemoryInst to sink their | ||||
5608 | /// address computing into the block when possible / profitable. | ||||
5609 | bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) { | ||||
5610 | bool MadeChange = false; | ||||
5611 | |||||
5612 | const TargetRegisterInfo *TRI = | ||||
5613 | TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo(); | ||||
5614 | TargetLowering::AsmOperandInfoVector TargetConstraints = | ||||
5615 | TLI->ParseConstraints(*DL, TRI, *CS); | ||||
5616 | unsigned ArgNo = 0; | ||||
5617 | for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) { | ||||
5618 | // Compute the constraint code and ConstraintType to use. | ||||
5619 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); | ||||
5620 | |||||
5621 | // TODO: Also handle C_Address? | ||||
5622 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && | ||||
5623 | OpInfo.isIndirect) { | ||||
5624 | Value *OpVal = CS->getArgOperand(ArgNo++); | ||||
5625 | MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u); | ||||
5626 | } else if (OpInfo.Type == InlineAsm::isInput) | ||||
5627 | ArgNo++; | ||||
5628 | } | ||||
5629 | |||||
5630 | return MadeChange; | ||||
5631 | } | ||||
5632 | |||||
5633 | /// Check if all the uses of \p Val are equivalent (or free) zero or | ||||
5634 | /// sign extensions. | ||||
5635 | static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) { | ||||
5636 | assert(!Val->use_empty() && "Input must have at least one use")(static_cast <bool> (!Val->use_empty() && "Input must have at least one use" ) ? void (0) : __assert_fail ("!Val->use_empty() && \"Input must have at least one use\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5636, __extension__ __PRETTY_FUNCTION__ )); | ||||
5637 | const Instruction *FirstUser = cast<Instruction>(*Val->user_begin()); | ||||
5638 | bool IsSExt = isa<SExtInst>(FirstUser); | ||||
5639 | Type *ExtTy = FirstUser->getType(); | ||||
5640 | for (const User *U : Val->users()) { | ||||
5641 | const Instruction *UI = cast<Instruction>(U); | ||||
5642 | if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI))) | ||||
5643 | return false; | ||||
5644 | Type *CurTy = UI->getType(); | ||||
5645 | // Same input and output types: Same instruction after CSE. | ||||
5646 | if (CurTy == ExtTy) | ||||
5647 | continue; | ||||
5648 | |||||
5649 | // If IsSExt is true, we are in this situation: | ||||
5650 | // a = Val | ||||
5651 | // b = sext ty1 a to ty2 | ||||
5652 | // c = sext ty1 a to ty3 | ||||
5653 | // Assuming ty2 is shorter than ty3, this could be turned into: | ||||
5654 | // a = Val | ||||
5655 | // b = sext ty1 a to ty2 | ||||
5656 | // c = sext ty2 b to ty3 | ||||
5657 | // However, the last sext is not free. | ||||
5658 | if (IsSExt) | ||||
5659 | return false; | ||||
5660 | |||||
5661 | // This is a ZExt, maybe this is free to extend from one type to another. | ||||
5662 | // In that case, we would not account for a different use. | ||||
5663 | Type *NarrowTy; | ||||
5664 | Type *LargeTy; | ||||
5665 | if (ExtTy->getScalarType()->getIntegerBitWidth() > | ||||
5666 | CurTy->getScalarType()->getIntegerBitWidth()) { | ||||
5667 | NarrowTy = CurTy; | ||||
5668 | LargeTy = ExtTy; | ||||
5669 | } else { | ||||
5670 | NarrowTy = ExtTy; | ||||
5671 | LargeTy = CurTy; | ||||
5672 | } | ||||
5673 | |||||
5674 | if (!TLI.isZExtFree(NarrowTy, LargeTy)) | ||||
5675 | return false; | ||||
5676 | } | ||||
5677 | // All uses are the same or can be derived from one another for free. | ||||
5678 | return true; | ||||
5679 | } | ||||
5680 | |||||
5681 | /// Try to speculatively promote extensions in \p Exts and continue | ||||
5682 | /// promoting through newly promoted operands recursively as far as doing so is | ||||
5683 | /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts. | ||||
5684 | /// When some promotion happened, \p TPT contains the proper state to revert | ||||
5685 | /// them. | ||||
5686 | /// | ||||
5687 | /// \return true if some promotion happened, false otherwise. | ||||
5688 | bool CodeGenPrepare::tryToPromoteExts( | ||||
5689 | TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts, | ||||
5690 | SmallVectorImpl<Instruction *> &ProfitablyMovedExts, | ||||
5691 | unsigned CreatedInstsCost) { | ||||
5692 | bool Promoted = false; | ||||
5693 | |||||
5694 | // Iterate over all the extensions to try to promote them. | ||||
5695 | for (auto *I : Exts) { | ||||
5696 | // Early check if we directly have ext(load). | ||||
5697 | if (isa<LoadInst>(I->getOperand(0))) { | ||||
5698 | ProfitablyMovedExts.push_back(I); | ||||
5699 | continue; | ||||
5700 | } | ||||
5701 | |||||
5702 | // Check whether or not we want to do any promotion. The reason we have | ||||
5703 | // this check inside the for loop is to catch the case where an extension | ||||
5704 | // is directly fed by a load because in such case the extension can be moved | ||||
5705 | // up without any promotion on its operands. | ||||
5706 | if (!TLI->enableExtLdPromotion() || DisableExtLdPromotion) | ||||
5707 | return false; | ||||
5708 | |||||
5709 | // Get the action to perform the promotion. | ||||
5710 | TypePromotionHelper::Action TPH = | ||||
5711 | TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts); | ||||
5712 | // Check if we can promote. | ||||
5713 | if (!TPH) { | ||||
5714 | // Save the current extension as we cannot move up through its operand. | ||||
5715 | ProfitablyMovedExts.push_back(I); | ||||
5716 | continue; | ||||
5717 | } | ||||
5718 | |||||
5719 | // Save the current state. | ||||
5720 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = | ||||
5721 | TPT.getRestorationPoint(); | ||||
5722 | SmallVector<Instruction *, 4> NewExts; | ||||
5723 | unsigned NewCreatedInstsCost = 0; | ||||
5724 | unsigned ExtCost = !TLI->isExtFree(I); | ||||
5725 | // Promote. | ||||
5726 | Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost, | ||||
5727 | &NewExts, nullptr, *TLI); | ||||
5728 | assert(PromotedVal &&(static_cast <bool> (PromotedVal && "TypePromotionHelper should have filtered out those cases" ) ? void (0) : __assert_fail ("PromotedVal && \"TypePromotionHelper should have filtered out those cases\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5729, __extension__ __PRETTY_FUNCTION__ )) | ||||
5729 | "TypePromotionHelper should have filtered out those cases")(static_cast <bool> (PromotedVal && "TypePromotionHelper should have filtered out those cases" ) ? void (0) : __assert_fail ("PromotedVal && \"TypePromotionHelper should have filtered out those cases\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 5729, __extension__ __PRETTY_FUNCTION__ )); | ||||
5730 | |||||
5731 | // We would be able to merge only one extension in a load. | ||||
5732 | // Therefore, if we have more than 1 new extension we heuristically | ||||
5733 | // cut this search path, because it means we degrade the code quality. | ||||
5734 | // With exactly 2, the transformation is neutral, because we will merge | ||||
5735 | // one extension but leave one. However, we optimistically keep going, | ||||
5736 | // because the new extension may be removed too. | ||||
5737 | long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost; | ||||
5738 | // FIXME: It would be possible to propagate a negative value instead of | ||||
5739 | // conservatively ceiling it to 0. | ||||
5740 | TotalCreatedInstsCost = | ||||
5741 | std::max((long long)0, (TotalCreatedInstsCost - ExtCost)); | ||||
5742 | if (!StressExtLdPromotion && | ||||
5743 | (TotalCreatedInstsCost > 1 || | ||||
5744 | !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) { | ||||
5745 | // This promotion is not profitable, rollback to the previous state, and | ||||
5746 | // save the current extension in ProfitablyMovedExts as the latest | ||||
5747 | // speculative promotion turned out to be unprofitable. | ||||
5748 | TPT.rollback(LastKnownGood); | ||||
5749 | ProfitablyMovedExts.push_back(I); | ||||
5750 | continue; | ||||
5751 | } | ||||
5752 | // Continue promoting NewExts as far as doing so is profitable. | ||||
5753 | SmallVector<Instruction *, 2> NewlyMovedExts; | ||||
5754 | (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost); | ||||
5755 | bool NewPromoted = false; | ||||
5756 | for (auto *ExtInst : NewlyMovedExts) { | ||||
5757 | Instruction *MovedExt = cast<Instruction>(ExtInst); | ||||
5758 | Value *ExtOperand = MovedExt->getOperand(0); | ||||
5759 | // If we have reached to a load, we need this extra profitability check | ||||
5760 | // as it could potentially be merged into an ext(load). | ||||
5761 | if (isa<LoadInst>(ExtOperand) && | ||||
5762 | !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost || | ||||
5763 | (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI)))) | ||||
5764 | continue; | ||||
5765 | |||||
5766 | ProfitablyMovedExts.push_back(MovedExt); | ||||
5767 | NewPromoted = true; | ||||
5768 | } | ||||
5769 | |||||
5770 | // If none of speculative promotions for NewExts is profitable, rollback | ||||
5771 | // and save the current extension (I) as the last profitable extension. | ||||
5772 | if (!NewPromoted) { | ||||
5773 | TPT.rollback(LastKnownGood); | ||||
5774 | ProfitablyMovedExts.push_back(I); | ||||
5775 | continue; | ||||
5776 | } | ||||
5777 | // The promotion is profitable. | ||||
5778 | Promoted = true; | ||||
5779 | } | ||||
5780 | return Promoted; | ||||
5781 | } | ||||
5782 | |||||
5783 | /// Merging redundant sexts when one is dominating the other. | ||||
5784 | bool CodeGenPrepare::mergeSExts(Function &F) { | ||||
5785 | bool Changed = false; | ||||
5786 | for (auto &Entry : ValToSExtendedUses) { | ||||
5787 | SExts &Insts = Entry.second; | ||||
5788 | SExts CurPts; | ||||
5789 | for (Instruction *Inst : Insts) { | ||||
5790 | if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) || | ||||
5791 | Inst->getOperand(0) != Entry.first) | ||||
5792 | continue; | ||||
5793 | bool inserted = false; | ||||
5794 | for (auto &Pt : CurPts) { | ||||
5795 | if (getDT(F).dominates(Inst, Pt)) { | ||||
5796 | Pt->replaceAllUsesWith(Inst); | ||||
5797 | RemovedInsts.insert(Pt); | ||||
5798 | Pt->removeFromParent(); | ||||
5799 | Pt = Inst; | ||||
5800 | inserted = true; | ||||
5801 | Changed = true; | ||||
5802 | break; | ||||
5803 | } | ||||
5804 | if (!getDT(F).dominates(Pt, Inst)) | ||||
5805 | // Give up if we need to merge in a common dominator as the | ||||
5806 | // experiments show it is not profitable. | ||||
5807 | continue; | ||||
5808 | Inst->replaceAllUsesWith(Pt); | ||||
5809 | RemovedInsts.insert(Inst); | ||||
5810 | Inst->removeFromParent(); | ||||
5811 | inserted = true; | ||||
5812 | Changed = true; | ||||
5813 | break; | ||||
5814 | } | ||||
5815 | if (!inserted) | ||||
5816 | CurPts.push_back(Inst); | ||||
5817 | } | ||||
5818 | } | ||||
5819 | return Changed; | ||||
5820 | } | ||||
5821 | |||||
5822 | // Splitting large data structures so that the GEPs accessing them can have | ||||
5823 | // smaller offsets so that they can be sunk to the same blocks as their users. | ||||
5824 | // For example, a large struct starting from %base is split into two parts | ||||
5825 | // where the second part starts from %new_base. | ||||
5826 | // | ||||
5827 | // Before: | ||||
5828 | // BB0: | ||||
5829 | // %base = | ||||
5830 | // | ||||
5831 | // BB1: | ||||
5832 | // %gep0 = gep %base, off0 | ||||
5833 | // %gep1 = gep %base, off1 | ||||
5834 | // %gep2 = gep %base, off2 | ||||
5835 | // | ||||
5836 | // BB2: | ||||
5837 | // %load1 = load %gep0 | ||||
5838 | // %load2 = load %gep1 | ||||
5839 | // %load3 = load %gep2 | ||||
5840 | // | ||||
5841 | // After: | ||||
5842 | // BB0: | ||||
5843 | // %base = | ||||
5844 | // %new_base = gep %base, off0 | ||||
5845 | // | ||||
5846 | // BB1: | ||||
5847 | // %new_gep0 = %new_base | ||||
5848 | // %new_gep1 = gep %new_base, off1 - off0 | ||||
5849 | // %new_gep2 = gep %new_base, off2 - off0 | ||||
5850 | // | ||||
5851 | // BB2: | ||||
5852 | // %load1 = load i32, i32* %new_gep0 | ||||
5853 | // %load2 = load i32, i32* %new_gep1 | ||||
5854 | // %load3 = load i32, i32* %new_gep2 | ||||
5855 | // | ||||
5856 | // %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because | ||||
5857 | // their offsets are smaller enough to fit into the addressing mode. | ||||
5858 | bool CodeGenPrepare::splitLargeGEPOffsets() { | ||||
5859 | bool Changed = false; | ||||
5860 | for (auto &Entry : LargeOffsetGEPMap) { | ||||
5861 | Value *OldBase = Entry.first; | ||||
5862 | SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>> | ||||
5863 | &LargeOffsetGEPs = Entry.second; | ||||
5864 | auto compareGEPOffset = | ||||
5865 | [&](const std::pair<GetElementPtrInst *, int64_t> &LHS, | ||||
5866 | const std::pair<GetElementPtrInst *, int64_t> &RHS) { | ||||
5867 | if (LHS.first == RHS.first) | ||||
5868 | return false; | ||||
5869 | if (LHS.second != RHS.second) | ||||
5870 | return LHS.second < RHS.second; | ||||
5871 | return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first]; | ||||
5872 | }; | ||||
5873 | // Sorting all the GEPs of the same data structures based on the offsets. | ||||
5874 | llvm::sort(LargeOffsetGEPs, compareGEPOffset); | ||||
5875 | LargeOffsetGEPs.erase( | ||||
5876 | std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()), | ||||
5877 | LargeOffsetGEPs.end()); | ||||
5878 | // Skip if all the GEPs have the same offsets. | ||||
5879 | if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second) | ||||
5880 | continue; | ||||
5881 | GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first; | ||||
5882 | int64_t BaseOffset = LargeOffsetGEPs.begin()->second; | ||||
5883 | Value *NewBaseGEP = nullptr; | ||||
5884 | |||||
5885 | auto *LargeOffsetGEP = LargeOffsetGEPs.begin(); | ||||
5886 | while (LargeOffsetGEP != LargeOffsetGEPs.end()) { | ||||
5887 | GetElementPtrInst *GEP = LargeOffsetGEP->first; | ||||
5888 | int64_t Offset = LargeOffsetGEP->second; | ||||
5889 | if (Offset != BaseOffset) { | ||||
5890 | TargetLowering::AddrMode AddrMode; | ||||
5891 | AddrMode.BaseOffs = Offset - BaseOffset; | ||||
5892 | // The result type of the GEP might not be the type of the memory | ||||
5893 | // access. | ||||
5894 | if (!TLI->isLegalAddressingMode(*DL, AddrMode, | ||||
5895 | GEP->getResultElementType(), | ||||
5896 | GEP->getAddressSpace())) { | ||||
5897 | // We need to create a new base if the offset to the current base is | ||||
5898 | // too large to fit into the addressing mode. So, a very large struct | ||||
5899 | // may be split into several parts. | ||||
5900 | BaseGEP = GEP; | ||||
5901 | BaseOffset = Offset; | ||||
5902 | NewBaseGEP = nullptr; | ||||
5903 | } | ||||
5904 | } | ||||
5905 | |||||
5906 | // Generate a new GEP to replace the current one. | ||||
5907 | LLVMContext &Ctx = GEP->getContext(); | ||||
5908 | Type *IntPtrTy = DL->getIntPtrType(GEP->getType()); | ||||
5909 | Type *I8PtrTy = | ||||
5910 | Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace()); | ||||
5911 | Type *I8Ty = Type::getInt8Ty(Ctx); | ||||
5912 | |||||
5913 | if (!NewBaseGEP) { | ||||
5914 | // Create a new base if we don't have one yet. Find the insertion | ||||
5915 | // pointer for the new base first. | ||||
5916 | BasicBlock::iterator NewBaseInsertPt; | ||||
5917 | BasicBlock *NewBaseInsertBB; | ||||
5918 | if (auto *BaseI = dyn_cast<Instruction>(OldBase)) { | ||||
5919 | // If the base of the struct is an instruction, the new base will be | ||||
5920 | // inserted close to it. | ||||
5921 | NewBaseInsertBB = BaseI->getParent(); | ||||
5922 | if (isa<PHINode>(BaseI)) | ||||
5923 | NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); | ||||
5924 | else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) { | ||||
5925 | NewBaseInsertBB = | ||||
5926 | SplitEdge(NewBaseInsertBB, Invoke->getNormalDest()); | ||||
5927 | NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); | ||||
5928 | } else | ||||
5929 | NewBaseInsertPt = std::next(BaseI->getIterator()); | ||||
5930 | } else { | ||||
5931 | // If the current base is an argument or global value, the new base | ||||
5932 | // will be inserted to the entry block. | ||||
5933 | NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock(); | ||||
5934 | NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); | ||||
5935 | } | ||||
5936 | IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt); | ||||
5937 | // Create a new base. | ||||
5938 | Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset); | ||||
5939 | NewBaseGEP = OldBase; | ||||
5940 | if (NewBaseGEP->getType() != I8PtrTy) | ||||
5941 | NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy); | ||||
5942 | NewBaseGEP = | ||||
5943 | NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep"); | ||||
5944 | NewGEPBases.insert(NewBaseGEP); | ||||
5945 | } | ||||
5946 | |||||
5947 | IRBuilder<> Builder(GEP); | ||||
5948 | Value *NewGEP = NewBaseGEP; | ||||
5949 | if (Offset == BaseOffset) { | ||||
5950 | if (GEP->getType() != I8PtrTy) | ||||
5951 | NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType()); | ||||
5952 | } else { | ||||
5953 | // Calculate the new offset for the new GEP. | ||||
5954 | Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset); | ||||
5955 | NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index); | ||||
5956 | |||||
5957 | if (GEP->getType() != I8PtrTy) | ||||
5958 | NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType()); | ||||
5959 | } | ||||
5960 | GEP->replaceAllUsesWith(NewGEP); | ||||
5961 | LargeOffsetGEPID.erase(GEP); | ||||
5962 | LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP); | ||||
5963 | GEP->eraseFromParent(); | ||||
5964 | Changed = true; | ||||
5965 | } | ||||
5966 | } | ||||
5967 | return Changed; | ||||
5968 | } | ||||
5969 | |||||
5970 | bool CodeGenPrepare::optimizePhiType( | ||||
5971 | PHINode *I, SmallPtrSetImpl<PHINode *> &Visited, | ||||
5972 | SmallPtrSetImpl<Instruction *> &DeletedInstrs) { | ||||
5973 | // We are looking for a collection on interconnected phi nodes that together | ||||
5974 | // only use loads/bitcasts and are used by stores/bitcasts, and the bitcasts | ||||
5975 | // are of the same type. Convert the whole set of nodes to the type of the | ||||
5976 | // bitcast. | ||||
5977 | Type *PhiTy = I->getType(); | ||||
5978 | Type *ConvertTy = nullptr; | ||||
5979 | if (Visited.count(I) || | ||||
5980 | (!I->getType()->isIntegerTy() && !I->getType()->isFloatingPointTy())) | ||||
5981 | return false; | ||||
5982 | |||||
5983 | SmallVector<Instruction *, 4> Worklist; | ||||
5984 | Worklist.push_back(cast<Instruction>(I)); | ||||
5985 | SmallPtrSet<PHINode *, 4> PhiNodes; | ||||
5986 | PhiNodes.insert(I); | ||||
5987 | Visited.insert(I); | ||||
5988 | SmallPtrSet<Instruction *, 4> Defs; | ||||
5989 | SmallPtrSet<Instruction *, 4> Uses; | ||||
5990 | // This works by adding extra bitcasts between load/stores and removing | ||||
5991 | // existing bicasts. If we have a phi(bitcast(load)) or a store(bitcast(phi)) | ||||
5992 | // we can get in the situation where we remove a bitcast in one iteration | ||||
5993 | // just to add it again in the next. We need to ensure that at least one | ||||
5994 | // bitcast we remove are anchored to something that will not change back. | ||||
5995 | bool AnyAnchored = false; | ||||
5996 | |||||
5997 | while (!Worklist.empty()) { | ||||
5998 | Instruction *II = Worklist.pop_back_val(); | ||||
5999 | |||||
6000 | if (auto *Phi = dyn_cast<PHINode>(II)) { | ||||
6001 | // Handle Defs, which might also be PHI's | ||||
6002 | for (Value *V : Phi->incoming_values()) { | ||||
6003 | if (auto *OpPhi = dyn_cast<PHINode>(V)) { | ||||
6004 | if (!PhiNodes.count(OpPhi)) { | ||||
6005 | if (Visited.count(OpPhi)) | ||||
6006 | return false; | ||||
6007 | PhiNodes.insert(OpPhi); | ||||
6008 | Visited.insert(OpPhi); | ||||
6009 | Worklist.push_back(OpPhi); | ||||
6010 | } | ||||
6011 | } else if (auto *OpLoad = dyn_cast<LoadInst>(V)) { | ||||
6012 | if (!OpLoad->isSimple()) | ||||
6013 | return false; | ||||
6014 | if (!Defs.count(OpLoad)) { | ||||
6015 | Defs.insert(OpLoad); | ||||
6016 | Worklist.push_back(OpLoad); | ||||
6017 | } | ||||
6018 | } else if (auto *OpEx = dyn_cast<ExtractElementInst>(V)) { | ||||
6019 | if (!Defs.count(OpEx)) { | ||||
6020 | Defs.insert(OpEx); | ||||
6021 | Worklist.push_back(OpEx); | ||||
6022 | } | ||||
6023 | } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) { | ||||
6024 | if (!ConvertTy) | ||||
6025 | ConvertTy = OpBC->getOperand(0)->getType(); | ||||
6026 | if (OpBC->getOperand(0)->getType() != ConvertTy) | ||||
6027 | return false; | ||||
6028 | if (!Defs.count(OpBC)) { | ||||
6029 | Defs.insert(OpBC); | ||||
6030 | Worklist.push_back(OpBC); | ||||
6031 | AnyAnchored |= !isa<LoadInst>(OpBC->getOperand(0)) && | ||||
6032 | !isa<ExtractElementInst>(OpBC->getOperand(0)); | ||||
6033 | } | ||||
6034 | } else if (!isa<UndefValue>(V)) { | ||||
6035 | return false; | ||||
6036 | } | ||||
6037 | } | ||||
6038 | } | ||||
6039 | |||||
6040 | // Handle uses which might also be phi's | ||||
6041 | for (User *V : II->users()) { | ||||
6042 | if (auto *OpPhi = dyn_cast<PHINode>(V)) { | ||||
6043 | if (!PhiNodes.count(OpPhi)) { | ||||
6044 | if (Visited.count(OpPhi)) | ||||
6045 | return false; | ||||
6046 | PhiNodes.insert(OpPhi); | ||||
6047 | Visited.insert(OpPhi); | ||||
6048 | Worklist.push_back(OpPhi); | ||||
6049 | } | ||||
6050 | } else if (auto *OpStore = dyn_cast<StoreInst>(V)) { | ||||
6051 | if (!OpStore->isSimple() || OpStore->getOperand(0) != II) | ||||
6052 | return false; | ||||
6053 | Uses.insert(OpStore); | ||||
6054 | } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) { | ||||
6055 | if (!ConvertTy) | ||||
6056 | ConvertTy = OpBC->getType(); | ||||
6057 | if (OpBC->getType() != ConvertTy) | ||||
6058 | return false; | ||||
6059 | Uses.insert(OpBC); | ||||
6060 | AnyAnchored |= | ||||
6061 | any_of(OpBC->users(), [](User *U) { return !isa<StoreInst>(U); }); | ||||
6062 | } else { | ||||
6063 | return false; | ||||
6064 | } | ||||
6065 | } | ||||
6066 | } | ||||
6067 | |||||
6068 | if (!ConvertTy || !AnyAnchored || !TLI->shouldConvertPhiType(PhiTy, ConvertTy)) | ||||
6069 | return false; | ||||
6070 | |||||
6071 | LLVM_DEBUG(dbgs() << "Converting " << *I << "\n and connected nodes to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Converting " << * I << "\n and connected nodes to " << *ConvertTy << "\n"; } } while (false) | ||||
6072 | << *ConvertTy << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Converting " << * I << "\n and connected nodes to " << *ConvertTy << "\n"; } } while (false); | ||||
6073 | |||||
6074 | // Create all the new phi nodes of the new type, and bitcast any loads to the | ||||
6075 | // correct type. | ||||
6076 | ValueToValueMap ValMap; | ||||
6077 | ValMap[UndefValue::get(PhiTy)] = UndefValue::get(ConvertTy); | ||||
6078 | for (Instruction *D : Defs) { | ||||
6079 | if (isa<BitCastInst>(D)) { | ||||
6080 | ValMap[D] = D->getOperand(0); | ||||
6081 | DeletedInstrs.insert(D); | ||||
6082 | } else { | ||||
6083 | ValMap[D] = | ||||
6084 | new BitCastInst(D, ConvertTy, D->getName() + ".bc", D->getNextNode()); | ||||
6085 | } | ||||
6086 | } | ||||
6087 | for (PHINode *Phi : PhiNodes) | ||||
6088 | ValMap[Phi] = PHINode::Create(ConvertTy, Phi->getNumIncomingValues(), | ||||
6089 | Phi->getName() + ".tc", Phi); | ||||
6090 | // Pipe together all the PhiNodes. | ||||
6091 | for (PHINode *Phi : PhiNodes) { | ||||
6092 | PHINode *NewPhi = cast<PHINode>(ValMap[Phi]); | ||||
6093 | for (int i = 0, e = Phi->getNumIncomingValues(); i < e; i++) | ||||
6094 | NewPhi->addIncoming(ValMap[Phi->getIncomingValue(i)], | ||||
6095 | Phi->getIncomingBlock(i)); | ||||
6096 | Visited.insert(NewPhi); | ||||
6097 | } | ||||
6098 | // And finally pipe up the stores and bitcasts | ||||
6099 | for (Instruction *U : Uses) { | ||||
6100 | if (isa<BitCastInst>(U)) { | ||||
6101 | DeletedInstrs.insert(U); | ||||
6102 | U->replaceAllUsesWith(ValMap[U->getOperand(0)]); | ||||
6103 | } else { | ||||
6104 | U->setOperand(0, | ||||
6105 | new BitCastInst(ValMap[U->getOperand(0)], PhiTy, "bc", U)); | ||||
6106 | } | ||||
6107 | } | ||||
6108 | |||||
6109 | // Save the removed phis to be deleted later. | ||||
6110 | for (PHINode *Phi : PhiNodes) | ||||
6111 | DeletedInstrs.insert(Phi); | ||||
6112 | return true; | ||||
6113 | } | ||||
6114 | |||||
6115 | bool CodeGenPrepare::optimizePhiTypes(Function &F) { | ||||
6116 | if (!OptimizePhiTypes) | ||||
6117 | return false; | ||||
6118 | |||||
6119 | bool Changed = false; | ||||
6120 | SmallPtrSet<PHINode *, 4> Visited; | ||||
6121 | SmallPtrSet<Instruction *, 4> DeletedInstrs; | ||||
6122 | |||||
6123 | // Attempt to optimize all the phis in the functions to the correct type. | ||||
6124 | for (auto &BB : F) | ||||
6125 | for (auto &Phi : BB.phis()) | ||||
6126 | Changed |= optimizePhiType(&Phi, Visited, DeletedInstrs); | ||||
6127 | |||||
6128 | // Remove any old phi's that have been converted. | ||||
6129 | for (auto *I : DeletedInstrs) { | ||||
6130 | I->replaceAllUsesWith(UndefValue::get(I->getType())); | ||||
6131 | I->eraseFromParent(); | ||||
6132 | } | ||||
6133 | |||||
6134 | return Changed; | ||||
6135 | } | ||||
6136 | |||||
6137 | /// Return true, if an ext(load) can be formed from an extension in | ||||
6138 | /// \p MovedExts. | ||||
6139 | bool CodeGenPrepare::canFormExtLd( | ||||
6140 | const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI, | ||||
6141 | Instruction *&Inst, bool HasPromoted) { | ||||
6142 | for (auto *MovedExtInst : MovedExts) { | ||||
6143 | if (isa<LoadInst>(MovedExtInst->getOperand(0))) { | ||||
6144 | LI = cast<LoadInst>(MovedExtInst->getOperand(0)); | ||||
6145 | Inst = MovedExtInst; | ||||
6146 | break; | ||||
6147 | } | ||||
6148 | } | ||||
6149 | if (!LI) | ||||
6150 | return false; | ||||
6151 | |||||
6152 | // If they're already in the same block, there's nothing to do. | ||||
6153 | // Make the cheap checks first if we did not promote. | ||||
6154 | // If we promoted, we need to check if it is indeed profitable. | ||||
6155 | if (!HasPromoted && LI->getParent() == Inst->getParent()) | ||||
6156 | return false; | ||||
6157 | |||||
6158 | return TLI->isExtLoad(LI, Inst, *DL); | ||||
6159 | } | ||||
6160 | |||||
6161 | /// Move a zext or sext fed by a load into the same basic block as the load, | ||||
6162 | /// unless conditions are unfavorable. This allows SelectionDAG to fold the | ||||
6163 | /// extend into the load. | ||||
6164 | /// | ||||
6165 | /// E.g., | ||||
6166 | /// \code | ||||
6167 | /// %ld = load i32* %addr | ||||
6168 | /// %add = add nuw i32 %ld, 4 | ||||
6169 | /// %zext = zext i32 %add to i64 | ||||
6170 | // \endcode | ||||
6171 | /// => | ||||
6172 | /// \code | ||||
6173 | /// %ld = load i32* %addr | ||||
6174 | /// %zext = zext i32 %ld to i64 | ||||
6175 | /// %add = add nuw i64 %zext, 4 | ||||
6176 | /// \encode | ||||
6177 | /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which | ||||
6178 | /// allow us to match zext(load i32*) to i64. | ||||
6179 | /// | ||||
6180 | /// Also, try to promote the computations used to obtain a sign extended | ||||
6181 | /// value used into memory accesses. | ||||
6182 | /// E.g., | ||||
6183 | /// \code | ||||
6184 | /// a = add nsw i32 b, 3 | ||||
6185 | /// d = sext i32 a to i64 | ||||
6186 | /// e = getelementptr ..., i64 d | ||||
6187 | /// \endcode | ||||
6188 | /// => | ||||
6189 | /// \code | ||||
6190 | /// f = sext i32 b to i64 | ||||
6191 | /// a = add nsw i64 f, 3 | ||||
6192 | /// e = getelementptr ..., i64 a | ||||
6193 | /// \endcode | ||||
6194 | /// | ||||
6195 | /// \p Inst[in/out] the extension may be modified during the process if some | ||||
6196 | /// promotions apply. | ||||
6197 | bool CodeGenPrepare::optimizeExt(Instruction *&Inst) { | ||||
6198 | bool AllowPromotionWithoutCommonHeader = false; | ||||
6199 | /// See if it is an interesting sext operations for the address type | ||||
6200 | /// promotion before trying to promote it, e.g., the ones with the right | ||||
6201 | /// type and used in memory accesses. | ||||
6202 | bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion( | ||||
6203 | *Inst, AllowPromotionWithoutCommonHeader); | ||||
6204 | TypePromotionTransaction TPT(RemovedInsts); | ||||
6205 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = | ||||
6206 | TPT.getRestorationPoint(); | ||||
6207 | SmallVector<Instruction *, 1> Exts; | ||||
6208 | SmallVector<Instruction *, 2> SpeculativelyMovedExts; | ||||
6209 | Exts.push_back(Inst); | ||||
6210 | |||||
6211 | bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts); | ||||
6212 | |||||
6213 | // Look for a load being extended. | ||||
6214 | LoadInst *LI = nullptr; | ||||
6215 | Instruction *ExtFedByLoad; | ||||
6216 | |||||
6217 | // Try to promote a chain of computation if it allows to form an extended | ||||
6218 | // load. | ||||
6219 | if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) { | ||||
6220 | assert(LI && ExtFedByLoad && "Expect a valid load and extension")(static_cast <bool> (LI && ExtFedByLoad && "Expect a valid load and extension") ? void (0) : __assert_fail ("LI && ExtFedByLoad && \"Expect a valid load and extension\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6220, __extension__ __PRETTY_FUNCTION__ )); | ||||
6221 | TPT.commit(); | ||||
6222 | // Move the extend into the same block as the load. | ||||
6223 | ExtFedByLoad->moveAfter(LI); | ||||
6224 | ++NumExtsMoved; | ||||
6225 | Inst = ExtFedByLoad; | ||||
6226 | return true; | ||||
6227 | } | ||||
6228 | |||||
6229 | // Continue promoting SExts if known as considerable depending on targets. | ||||
6230 | if (ATPConsiderable && | ||||
6231 | performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader, | ||||
6232 | HasPromoted, TPT, SpeculativelyMovedExts)) | ||||
6233 | return true; | ||||
6234 | |||||
6235 | TPT.rollback(LastKnownGood); | ||||
6236 | return false; | ||||
6237 | } | ||||
6238 | |||||
6239 | // Perform address type promotion if doing so is profitable. | ||||
6240 | // If AllowPromotionWithoutCommonHeader == false, we should find other sext | ||||
6241 | // instructions that sign extended the same initial value. However, if | ||||
6242 | // AllowPromotionWithoutCommonHeader == true, we expect promoting the | ||||
6243 | // extension is just profitable. | ||||
6244 | bool CodeGenPrepare::performAddressTypePromotion( | ||||
6245 | Instruction *&Inst, bool AllowPromotionWithoutCommonHeader, | ||||
6246 | bool HasPromoted, TypePromotionTransaction &TPT, | ||||
6247 | SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) { | ||||
6248 | bool Promoted = false; | ||||
6249 | SmallPtrSet<Instruction *, 1> UnhandledExts; | ||||
6250 | bool AllSeenFirst = true; | ||||
6251 | for (auto *I : SpeculativelyMovedExts) { | ||||
6252 | Value *HeadOfChain = I->getOperand(0); | ||||
6253 | DenseMap<Value *, Instruction *>::iterator AlreadySeen = | ||||
6254 | SeenChainsForSExt.find(HeadOfChain); | ||||
6255 | // If there is an unhandled SExt which has the same header, try to promote | ||||
6256 | // it as well. | ||||
6257 | if (AlreadySeen != SeenChainsForSExt.end()) { | ||||
6258 | if (AlreadySeen->second != nullptr) | ||||
6259 | UnhandledExts.insert(AlreadySeen->second); | ||||
6260 | AllSeenFirst = false; | ||||
6261 | } | ||||
6262 | } | ||||
6263 | |||||
6264 | if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader && | ||||
6265 | SpeculativelyMovedExts.size() == 1)) { | ||||
6266 | TPT.commit(); | ||||
6267 | if (HasPromoted) | ||||
6268 | Promoted = true; | ||||
6269 | for (auto *I : SpeculativelyMovedExts) { | ||||
6270 | Value *HeadOfChain = I->getOperand(0); | ||||
6271 | SeenChainsForSExt[HeadOfChain] = nullptr; | ||||
6272 | ValToSExtendedUses[HeadOfChain].push_back(I); | ||||
6273 | } | ||||
6274 | // Update Inst as promotion happen. | ||||
6275 | Inst = SpeculativelyMovedExts.pop_back_val(); | ||||
6276 | } else { | ||||
6277 | // This is the first chain visited from the header, keep the current chain | ||||
6278 | // as unhandled. Defer to promote this until we encounter another SExt | ||||
6279 | // chain derived from the same header. | ||||
6280 | for (auto *I : SpeculativelyMovedExts) { | ||||
6281 | Value *HeadOfChain = I->getOperand(0); | ||||
6282 | SeenChainsForSExt[HeadOfChain] = Inst; | ||||
6283 | } | ||||
6284 | return false; | ||||
6285 | } | ||||
6286 | |||||
6287 | if (!AllSeenFirst && !UnhandledExts.empty()) | ||||
6288 | for (auto *VisitedSExt : UnhandledExts) { | ||||
6289 | if (RemovedInsts.count(VisitedSExt)) | ||||
6290 | continue; | ||||
6291 | TypePromotionTransaction TPT(RemovedInsts); | ||||
6292 | SmallVector<Instruction *, 1> Exts; | ||||
6293 | SmallVector<Instruction *, 2> Chains; | ||||
6294 | Exts.push_back(VisitedSExt); | ||||
6295 | bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains); | ||||
6296 | TPT.commit(); | ||||
6297 | if (HasPromoted) | ||||
6298 | Promoted = true; | ||||
6299 | for (auto *I : Chains) { | ||||
6300 | Value *HeadOfChain = I->getOperand(0); | ||||
6301 | // Mark this as handled. | ||||
6302 | SeenChainsForSExt[HeadOfChain] = nullptr; | ||||
6303 | ValToSExtendedUses[HeadOfChain].push_back(I); | ||||
6304 | } | ||||
6305 | } | ||||
6306 | return Promoted; | ||||
6307 | } | ||||
6308 | |||||
6309 | bool CodeGenPrepare::optimizeExtUses(Instruction *I) { | ||||
6310 | BasicBlock *DefBB = I->getParent(); | ||||
6311 | |||||
6312 | // If the result of a {s|z}ext and its source are both live out, rewrite all | ||||
6313 | // other uses of the source with result of extension. | ||||
6314 | Value *Src = I->getOperand(0); | ||||
6315 | if (Src->hasOneUse()) | ||||
6316 | return false; | ||||
6317 | |||||
6318 | // Only do this xform if truncating is free. | ||||
6319 | if (!TLI->isTruncateFree(I->getType(), Src->getType())) | ||||
6320 | return false; | ||||
6321 | |||||
6322 | // Only safe to perform the optimization if the source is also defined in | ||||
6323 | // this block. | ||||
6324 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) | ||||
6325 | return false; | ||||
6326 | |||||
6327 | bool DefIsLiveOut = false; | ||||
6328 | for (User *U : I->users()) { | ||||
6329 | Instruction *UI = cast<Instruction>(U); | ||||
6330 | |||||
6331 | // Figure out which BB this ext is used in. | ||||
6332 | BasicBlock *UserBB = UI->getParent(); | ||||
6333 | if (UserBB == DefBB) continue; | ||||
6334 | DefIsLiveOut = true; | ||||
6335 | break; | ||||
6336 | } | ||||
6337 | if (!DefIsLiveOut) | ||||
6338 | return false; | ||||
6339 | |||||
6340 | // Make sure none of the uses are PHI nodes. | ||||
6341 | for (User *U : Src->users()) { | ||||
6342 | Instruction *UI = cast<Instruction>(U); | ||||
6343 | BasicBlock *UserBB = UI->getParent(); | ||||
6344 | if (UserBB == DefBB) continue; | ||||
6345 | // Be conservative. We don't want this xform to end up introducing | ||||
6346 | // reloads just before load / store instructions. | ||||
6347 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) | ||||
6348 | return false; | ||||
6349 | } | ||||
6350 | |||||
6351 | // InsertedTruncs - Only insert one trunc in each block once. | ||||
6352 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; | ||||
6353 | |||||
6354 | bool MadeChange = false; | ||||
6355 | for (Use &U : Src->uses()) { | ||||
6356 | Instruction *User = cast<Instruction>(U.getUser()); | ||||
6357 | |||||
6358 | // Figure out which BB this ext is used in. | ||||
6359 | BasicBlock *UserBB = User->getParent(); | ||||
6360 | if (UserBB == DefBB) continue; | ||||
6361 | |||||
6362 | // Both src and def are live in this block. Rewrite the use. | ||||
6363 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; | ||||
6364 | |||||
6365 | if (!InsertedTrunc) { | ||||
6366 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); | ||||
6367 | assert(InsertPt != UserBB->end())(static_cast <bool> (InsertPt != UserBB->end()) ? void (0) : __assert_fail ("InsertPt != UserBB->end()", "llvm/lib/CodeGen/CodeGenPrepare.cpp" , 6367, __extension__ __PRETTY_FUNCTION__)); | ||||
6368 | InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt); | ||||
6369 | InsertedInsts.insert(InsertedTrunc); | ||||
6370 | } | ||||
6371 | |||||
6372 | // Replace a use of the {s|z}ext source with a use of the result. | ||||
6373 | U = InsertedTrunc; | ||||
6374 | ++NumExtUses; | ||||
6375 | MadeChange = true; | ||||
6376 | } | ||||
6377 | |||||
6378 | return MadeChange; | ||||
6379 | } | ||||
6380 | |||||
6381 | // Find loads whose uses only use some of the loaded value's bits. Add an "and" | ||||
6382 | // just after the load if the target can fold this into one extload instruction, | ||||
6383 | // with the hope of eliminating some of the other later "and" instructions using | ||||
6384 | // the loaded value. "and"s that are made trivially redundant by the insertion | ||||
6385 | // of the new "and" are removed by this function, while others (e.g. those whose | ||||
6386 | // path from the load goes through a phi) are left for isel to potentially | ||||
6387 | // remove. | ||||
6388 | // | ||||
6389 | // For example: | ||||
6390 | // | ||||
6391 | // b0: | ||||
6392 | // x = load i32 | ||||
6393 | // ... | ||||
6394 | // b1: | ||||
6395 | // y = and x, 0xff | ||||
6396 | // z = use y | ||||
6397 | // | ||||
6398 | // becomes: | ||||
6399 | // | ||||
6400 | // b0: | ||||
6401 | // x = load i32 | ||||
6402 | // x' = and x, 0xff | ||||
6403 | // ... | ||||
6404 | // b1: | ||||
6405 | // z = use x' | ||||
6406 | // | ||||
6407 | // whereas: | ||||
6408 | // | ||||
6409 | // b0: | ||||
6410 | // x1 = load i32 | ||||
6411 | // ... | ||||
6412 | // b1: | ||||
6413 | // x2 = load i32 | ||||
6414 | // ... | ||||
6415 | // b2: | ||||
6416 | // x = phi x1, x2 | ||||
6417 | // y = and x, 0xff | ||||
6418 | // | ||||
6419 | // becomes (after a call to optimizeLoadExt for each load): | ||||
6420 | // | ||||
6421 | // b0: | ||||
6422 | // x1 = load i32 | ||||
6423 | // x1' = and x1, 0xff | ||||
6424 | // ... | ||||
6425 | // b1: | ||||
6426 | // x2 = load i32 | ||||
6427 | // x2' = and x2, 0xff | ||||
6428 | // ... | ||||
6429 | // b2: | ||||
6430 | // x = phi x1', x2' | ||||
6431 | // y = and x, 0xff | ||||
6432 | bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) { | ||||
6433 | if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy()) | ||||
6434 | return false; | ||||
6435 | |||||
6436 | // Skip loads we've already transformed. | ||||
6437 | if (Load->hasOneUse() && | ||||
6438 | InsertedInsts.count(cast<Instruction>(*Load->user_begin()))) | ||||
6439 | return false; | ||||
6440 | |||||
6441 | // Look at all uses of Load, looking through phis, to determine how many bits | ||||
6442 | // of the loaded value are needed. | ||||
6443 | SmallVector<Instruction *, 8> WorkList; | ||||
6444 | SmallPtrSet<Instruction *, 16> Visited; | ||||
6445 | SmallVector<Instruction *, 8> AndsToMaybeRemove; | ||||
6446 | for (auto *U : Load->users()) | ||||
6447 | WorkList.push_back(cast<Instruction>(U)); | ||||
6448 | |||||
6449 | EVT LoadResultVT = TLI->getValueType(*DL, Load->getType()); | ||||
6450 | unsigned BitWidth = LoadResultVT.getSizeInBits(); | ||||
6451 | // If the BitWidth is 0, do not try to optimize the type | ||||
6452 | if (BitWidth == 0) | ||||
6453 | return false; | ||||
6454 | |||||
6455 | APInt DemandBits(BitWidth, 0); | ||||
6456 | APInt WidestAndBits(BitWidth, 0); | ||||
6457 | |||||
6458 | while (!WorkList.empty()) { | ||||
6459 | Instruction *I = WorkList.pop_back_val(); | ||||
6460 | |||||
6461 | // Break use-def graph loops. | ||||
6462 | if (!Visited.insert(I).second) | ||||
6463 | continue; | ||||
6464 | |||||
6465 | // For a PHI node, push all of its users. | ||||
6466 | if (auto *Phi = dyn_cast<PHINode>(I)) { | ||||
6467 | for (auto *U : Phi->users()) | ||||
6468 | WorkList.push_back(cast<Instruction>(U)); | ||||
6469 | continue; | ||||
6470 | } | ||||
6471 | |||||
6472 | switch (I->getOpcode()) { | ||||
6473 | case Instruction::And: { | ||||
6474 | auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1)); | ||||
6475 | if (!AndC) | ||||
6476 | return false; | ||||
6477 | APInt AndBits = AndC->getValue(); | ||||
6478 | DemandBits |= AndBits; | ||||
6479 | // Keep track of the widest and mask we see. | ||||
6480 | if (AndBits.ugt(WidestAndBits)) | ||||
6481 | WidestAndBits = AndBits; | ||||
6482 | if (AndBits == WidestAndBits && I->getOperand(0) == Load) | ||||
6483 | AndsToMaybeRemove.push_back(I); | ||||
6484 | break; | ||||
6485 | } | ||||
6486 | |||||
6487 | case Instruction::Shl: { | ||||
6488 | auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1)); | ||||
6489 | if (!ShlC) | ||||
6490 | return false; | ||||
6491 | uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1); | ||||
6492 | DemandBits.setLowBits(BitWidth - ShiftAmt); | ||||
6493 | break; | ||||
6494 | } | ||||
6495 | |||||
6496 | case Instruction::Trunc: { | ||||
6497 | EVT TruncVT = TLI->getValueType(*DL, I->getType()); | ||||
6498 | unsigned TruncBitWidth = TruncVT.getSizeInBits(); | ||||
6499 | DemandBits.setLowBits(TruncBitWidth); | ||||
6500 | break; | ||||
6501 | } | ||||
6502 | |||||
6503 | default: | ||||
6504 | return false; | ||||
6505 | } | ||||
6506 | } | ||||
6507 | |||||
6508 | uint32_t ActiveBits = DemandBits.getActiveBits(); | ||||
6509 | // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the | ||||
6510 | // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example, | ||||
6511 | // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but | ||||
6512 | // (and (load x) 1) is not matched as a single instruction, rather as a LDR | ||||
6513 | // followed by an AND. | ||||
6514 | // TODO: Look into removing this restriction by fixing backends to either | ||||
6515 | // return false for isLoadExtLegal for i1 or have them select this pattern to | ||||
6516 | // a single instruction. | ||||
6517 | // | ||||
6518 | // Also avoid hoisting if we didn't see any ands with the exact DemandBits | ||||
6519 | // mask, since these are the only ands that will be removed by isel. | ||||
6520 | if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) || | ||||
6521 | WidestAndBits != DemandBits) | ||||
6522 | return false; | ||||
6523 | |||||
6524 | LLVMContext &Ctx = Load->getType()->getContext(); | ||||
6525 | Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits); | ||||
6526 | EVT TruncVT = TLI->getValueType(*DL, TruncTy); | ||||
6527 | |||||
6528 | // Reject cases that won't be matched as extloads. | ||||
6529 | if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() || | ||||
6530 | !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT)) | ||||
6531 | return false; | ||||
6532 | |||||
6533 | IRBuilder<> Builder(Load->getNextNode()); | ||||
6534 | auto *NewAnd = cast<Instruction>( | ||||
6535 | Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits))); | ||||
6536 | // Mark this instruction as "inserted by CGP", so that other | ||||
6537 | // optimizations don't touch it. | ||||
6538 | InsertedInsts.insert(NewAnd); | ||||
6539 | |||||
6540 | // Replace all uses of load with new and (except for the use of load in the | ||||
6541 | // new and itself). | ||||
6542 | Load->replaceAllUsesWith(NewAnd); | ||||
6543 | NewAnd->setOperand(0, Load); | ||||
6544 | |||||
6545 | // Remove any and instructions that are now redundant. | ||||
6546 | for (auto *And : AndsToMaybeRemove) | ||||
6547 | // Check that the and mask is the same as the one we decided to put on the | ||||
6548 | // new and. | ||||
6549 | if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) { | ||||
6550 | And->replaceAllUsesWith(NewAnd); | ||||
6551 | if (&*CurInstIterator == And) | ||||
6552 | CurInstIterator = std::next(And->getIterator()); | ||||
6553 | And->eraseFromParent(); | ||||
6554 | ++NumAndUses; | ||||
6555 | } | ||||
6556 | |||||
6557 | ++NumAndsAdded; | ||||
6558 | return true; | ||||
6559 | } | ||||
6560 | |||||
6561 | /// Check if V (an operand of a select instruction) is an expensive instruction | ||||
6562 | /// that is only used once. | ||||
6563 | static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) { | ||||
6564 | auto *I = dyn_cast<Instruction>(V); | ||||
6565 | // If it's safe to speculatively execute, then it should not have side | ||||
6566 | // effects; therefore, it's safe to sink and possibly *not* execute. | ||||
6567 | return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) && | ||||
6568 | TTI->getUserCost(I, TargetTransformInfo::TCK_SizeAndLatency) >= | ||||
6569 | TargetTransformInfo::TCC_Expensive; | ||||
6570 | } | ||||
6571 | |||||
6572 | /// Returns true if a SelectInst should be turned into an explicit branch. | ||||
6573 | static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, | ||||
6574 | const TargetLowering *TLI, | ||||
6575 | SelectInst *SI) { | ||||
6576 | // If even a predictable select is cheap, then a branch can't be cheaper. | ||||
6577 | if (!TLI->isPredictableSelectExpensive()) | ||||
6578 | return false; | ||||
6579 | |||||
6580 | // FIXME: This should use the same heuristics as IfConversion to determine | ||||
6581 | // whether a select is better represented as a branch. | ||||
6582 | |||||
6583 | // If metadata tells us that the select condition is obviously predictable, | ||||
6584 | // then we want to replace the select with a branch. | ||||
6585 | uint64_t TrueWeight, FalseWeight; | ||||
6586 | if (SI->extractProfMetadata(TrueWeight, FalseWeight)) { | ||||
6587 | uint64_t Max = std::max(TrueWeight, FalseWeight); | ||||
6588 | uint64_t Sum = TrueWeight + FalseWeight; | ||||
6589 | if (Sum != 0) { | ||||
6590 | auto Probability = BranchProbability::getBranchProbability(Max, Sum); | ||||
6591 | if (Probability > TTI->getPredictableBranchThreshold()) | ||||
6592 | return true; | ||||
6593 | } | ||||
6594 | } | ||||
6595 | |||||
6596 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); | ||||
6597 | |||||
6598 | // If a branch is predictable, an out-of-order CPU can avoid blocking on its | ||||
6599 | // comparison condition. If the compare has more than one use, there's | ||||
6600 | // probably another cmov or setcc around, so it's not worth emitting a branch. | ||||
6601 | if (!Cmp || !Cmp->hasOneUse()) | ||||
6602 | return false; | ||||
6603 | |||||
6604 | // If either operand of the select is expensive and only needed on one side | ||||
6605 | // of the select, we should form a branch. | ||||
6606 | if (sinkSelectOperand(TTI, SI->getTrueValue()) || | ||||
6607 | sinkSelectOperand(TTI, SI->getFalseValue())) | ||||
6608 | return true; | ||||
6609 | |||||
6610 | return false; | ||||
6611 | } | ||||
6612 | |||||
6613 | /// If \p isTrue is true, return the true value of \p SI, otherwise return | ||||
6614 | /// false value of \p SI. If the true/false value of \p SI is defined by any | ||||
6615 | /// select instructions in \p Selects, look through the defining select | ||||
6616 | /// instruction until the true/false value is not defined in \p Selects. | ||||
6617 | static Value *getTrueOrFalseValue( | ||||
6618 | SelectInst *SI, bool isTrue, | ||||
6619 | const SmallPtrSet<const Instruction *, 2> &Selects) { | ||||
6620 | Value *V = nullptr; | ||||
6621 | |||||
6622 | for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI); | ||||
6623 | DefSI = dyn_cast<SelectInst>(V)) { | ||||
6624 | assert(DefSI->getCondition() == SI->getCondition() &&(static_cast <bool> (DefSI->getCondition() == SI-> getCondition() && "The condition of DefSI does not match with SI" ) ? void (0) : __assert_fail ("DefSI->getCondition() == SI->getCondition() && \"The condition of DefSI does not match with SI\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6625, __extension__ __PRETTY_FUNCTION__ )) | ||||
6625 | "The condition of DefSI does not match with SI")(static_cast <bool> (DefSI->getCondition() == SI-> getCondition() && "The condition of DefSI does not match with SI" ) ? void (0) : __assert_fail ("DefSI->getCondition() == SI->getCondition() && \"The condition of DefSI does not match with SI\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6625, __extension__ __PRETTY_FUNCTION__ )); | ||||
6626 | V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue()); | ||||
6627 | } | ||||
6628 | |||||
6629 | assert(V && "Failed to get select true/false value")(static_cast <bool> (V && "Failed to get select true/false value" ) ? void (0) : __assert_fail ("V && \"Failed to get select true/false value\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6629, __extension__ __PRETTY_FUNCTION__ )); | ||||
6630 | return V; | ||||
6631 | } | ||||
6632 | |||||
6633 | bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) { | ||||
6634 | assert(Shift->isShift() && "Expected a shift")(static_cast <bool> (Shift->isShift() && "Expected a shift" ) ? void (0) : __assert_fail ("Shift->isShift() && \"Expected a shift\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6634, __extension__ __PRETTY_FUNCTION__ )); | ||||
6635 | |||||
6636 | // If this is (1) a vector shift, (2) shifts by scalars are cheaper than | ||||
6637 | // general vector shifts, and (3) the shift amount is a select-of-splatted | ||||
6638 | // values, hoist the shifts before the select: | ||||
6639 | // shift Op0, (select Cond, TVal, FVal) --> | ||||
6640 | // select Cond, (shift Op0, TVal), (shift Op0, FVal) | ||||
6641 | // | ||||
6642 | // This is inverting a generic IR transform when we know that the cost of a | ||||
6643 | // general vector shift is more than the cost of 2 shift-by-scalars. | ||||
6644 | // We can't do this effectively in SDAG because we may not be able to | ||||
6645 | // determine if the select operands are splats from within a basic block. | ||||
6646 | Type *Ty = Shift->getType(); | ||||
6647 | if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty)) | ||||
6648 | return false; | ||||
6649 | Value *Cond, *TVal, *FVal; | ||||
6650 | if (!match(Shift->getOperand(1), | ||||
6651 | m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal))))) | ||||
6652 | return false; | ||||
6653 | if (!isSplatValue(TVal) || !isSplatValue(FVal)) | ||||
6654 | return false; | ||||
6655 | |||||
6656 | IRBuilder<> Builder(Shift); | ||||
6657 | BinaryOperator::BinaryOps Opcode = Shift->getOpcode(); | ||||
6658 | Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal); | ||||
6659 | Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal); | ||||
6660 | Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal); | ||||
6661 | Shift->replaceAllUsesWith(NewSel); | ||||
6662 | Shift->eraseFromParent(); | ||||
6663 | return true; | ||||
6664 | } | ||||
6665 | |||||
6666 | bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) { | ||||
6667 | Intrinsic::ID Opcode = Fsh->getIntrinsicID(); | ||||
6668 | assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) &&(static_cast <bool> ((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) && "Expected a funnel shift") ? void (0) : __assert_fail ("(Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) && \"Expected a funnel shift\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6669, __extension__ __PRETTY_FUNCTION__ )) | ||||
6669 | "Expected a funnel shift")(static_cast <bool> ((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) && "Expected a funnel shift") ? void (0) : __assert_fail ("(Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) && \"Expected a funnel shift\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6669, __extension__ __PRETTY_FUNCTION__ )); | ||||
6670 | |||||
6671 | // If this is (1) a vector funnel shift, (2) shifts by scalars are cheaper | ||||
6672 | // than general vector shifts, and (3) the shift amount is select-of-splatted | ||||
6673 | // values, hoist the funnel shifts before the select: | ||||
6674 | // fsh Op0, Op1, (select Cond, TVal, FVal) --> | ||||
6675 | // select Cond, (fsh Op0, Op1, TVal), (fsh Op0, Op1, FVal) | ||||
6676 | // | ||||
6677 | // This is inverting a generic IR transform when we know that the cost of a | ||||
6678 | // general vector shift is more than the cost of 2 shift-by-scalars. | ||||
6679 | // We can't do this effectively in SDAG because we may not be able to | ||||
6680 | // determine if the select operands are splats from within a basic block. | ||||
6681 | Type *Ty = Fsh->getType(); | ||||
6682 | if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty)) | ||||
6683 | return false; | ||||
6684 | Value *Cond, *TVal, *FVal; | ||||
6685 | if (!match(Fsh->getOperand(2), | ||||
6686 | m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal))))) | ||||
6687 | return false; | ||||
6688 | if (!isSplatValue(TVal) || !isSplatValue(FVal)) | ||||
6689 | return false; | ||||
6690 | |||||
6691 | IRBuilder<> Builder(Fsh); | ||||
6692 | Value *X = Fsh->getOperand(0), *Y = Fsh->getOperand(1); | ||||
6693 | Value *NewTVal = Builder.CreateIntrinsic(Opcode, Ty, { X, Y, TVal }); | ||||
6694 | Value *NewFVal = Builder.CreateIntrinsic(Opcode, Ty, { X, Y, FVal }); | ||||
6695 | Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal); | ||||
6696 | Fsh->replaceAllUsesWith(NewSel); | ||||
6697 | Fsh->eraseFromParent(); | ||||
6698 | return true; | ||||
6699 | } | ||||
6700 | |||||
6701 | /// If we have a SelectInst that will likely profit from branch prediction, | ||||
6702 | /// turn it into a branch. | ||||
6703 | bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) { | ||||
6704 | if (DisableSelectToBranch) | ||||
6705 | return false; | ||||
6706 | |||||
6707 | // Find all consecutive select instructions that share the same condition. | ||||
6708 | SmallVector<SelectInst *, 2> ASI; | ||||
6709 | ASI.push_back(SI); | ||||
6710 | for (BasicBlock::iterator It = ++BasicBlock::iterator(SI); | ||||
6711 | It != SI->getParent()->end(); ++It) { | ||||
6712 | SelectInst *I = dyn_cast<SelectInst>(&*It); | ||||
6713 | if (I && SI->getCondition() == I->getCondition()) { | ||||
6714 | ASI.push_back(I); | ||||
6715 | } else { | ||||
6716 | break; | ||||
6717 | } | ||||
6718 | } | ||||
6719 | |||||
6720 | SelectInst *LastSI = ASI.back(); | ||||
6721 | // Increment the current iterator to skip all the rest of select instructions | ||||
6722 | // because they will be either "not lowered" or "all lowered" to branch. | ||||
6723 | CurInstIterator = std::next(LastSI->getIterator()); | ||||
6724 | |||||
6725 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); | ||||
6726 | |||||
6727 | // Can we convert the 'select' to CF ? | ||||
6728 | if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable)) | ||||
6729 | return false; | ||||
6730 | |||||
6731 | TargetLowering::SelectSupportKind SelectKind; | ||||
6732 | if (VectorCond) | ||||
6733 | SelectKind = TargetLowering::VectorMaskSelect; | ||||
6734 | else if (SI->getType()->isVectorTy()) | ||||
6735 | SelectKind = TargetLowering::ScalarCondVectorVal; | ||||
6736 | else | ||||
6737 | SelectKind = TargetLowering::ScalarValSelect; | ||||
6738 | |||||
6739 | if (TLI->isSelectSupported(SelectKind) && | ||||
6740 | (!isFormingBranchFromSelectProfitable(TTI, TLI, SI) || OptSize || | ||||
6741 | llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI.get()))) | ||||
6742 | return false; | ||||
6743 | |||||
6744 | // The DominatorTree needs to be rebuilt by any consumers after this | ||||
6745 | // transformation. We simply reset here rather than setting the ModifiedDT | ||||
6746 | // flag to avoid restarting the function walk in runOnFunction for each | ||||
6747 | // select optimized. | ||||
6748 | DT.reset(); | ||||
6749 | |||||
6750 | // Transform a sequence like this: | ||||
6751 | // start: | ||||
6752 | // %cmp = cmp uge i32 %a, %b | ||||
6753 | // %sel = select i1 %cmp, i32 %c, i32 %d | ||||
6754 | // | ||||
6755 | // Into: | ||||
6756 | // start: | ||||
6757 | // %cmp = cmp uge i32 %a, %b | ||||
6758 | // %cmp.frozen = freeze %cmp | ||||
6759 | // br i1 %cmp.frozen, label %select.true, label %select.false | ||||
6760 | // select.true: | ||||
6761 | // br label %select.end | ||||
6762 | // select.false: | ||||
6763 | // br label %select.end | ||||
6764 | // select.end: | ||||
6765 | // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ] | ||||
6766 | // | ||||
6767 | // %cmp should be frozen, otherwise it may introduce undefined behavior. | ||||
6768 | // In addition, we may sink instructions that produce %c or %d from | ||||
6769 | // the entry block into the destination(s) of the new branch. | ||||
6770 | // If the true or false blocks do not contain a sunken instruction, that | ||||
6771 | // block and its branch may be optimized away. In that case, one side of the | ||||
6772 | // first branch will point directly to select.end, and the corresponding PHI | ||||
6773 | // predecessor block will be the start block. | ||||
6774 | |||||
6775 | // First, we split the block containing the select into 2 blocks. | ||||
6776 | BasicBlock *StartBlock = SI->getParent(); | ||||
6777 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI)); | ||||
6778 | BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); | ||||
6779 | BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock).getFrequency()); | ||||
6780 | |||||
6781 | // Delete the unconditional branch that was just created by the split. | ||||
6782 | StartBlock->getTerminator()->eraseFromParent(); | ||||
6783 | |||||
6784 | // These are the new basic blocks for the conditional branch. | ||||
6785 | // At least one will become an actual new basic block. | ||||
6786 | BasicBlock *TrueBlock = nullptr; | ||||
6787 | BasicBlock *FalseBlock = nullptr; | ||||
6788 | BranchInst *TrueBranch = nullptr; | ||||
6789 | BranchInst *FalseBranch = nullptr; | ||||
6790 | |||||
6791 | // Sink expensive instructions into the conditional blocks to avoid executing | ||||
6792 | // them speculatively. | ||||
6793 | for (SelectInst *SI : ASI) { | ||||
6794 | if (sinkSelectOperand(TTI, SI->getTrueValue())) { | ||||
6795 | if (TrueBlock == nullptr) { | ||||
6796 | TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink", | ||||
6797 | EndBlock->getParent(), EndBlock); | ||||
6798 | TrueBranch = BranchInst::Create(EndBlock, TrueBlock); | ||||
6799 | TrueBranch->setDebugLoc(SI->getDebugLoc()); | ||||
6800 | } | ||||
6801 | auto *TrueInst = cast<Instruction>(SI->getTrueValue()); | ||||
6802 | TrueInst->moveBefore(TrueBranch); | ||||
6803 | } | ||||
6804 | if (sinkSelectOperand(TTI, SI->getFalseValue())) { | ||||
6805 | if (FalseBlock == nullptr) { | ||||
6806 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink", | ||||
6807 | EndBlock->getParent(), EndBlock); | ||||
6808 | FalseBranch = BranchInst::Create(EndBlock, FalseBlock); | ||||
6809 | FalseBranch->setDebugLoc(SI->getDebugLoc()); | ||||
6810 | } | ||||
6811 | auto *FalseInst = cast<Instruction>(SI->getFalseValue()); | ||||
6812 | FalseInst->moveBefore(FalseBranch); | ||||
6813 | } | ||||
6814 | } | ||||
6815 | |||||
6816 | // If there was nothing to sink, then arbitrarily choose the 'false' side | ||||
6817 | // for a new input value to the PHI. | ||||
6818 | if (TrueBlock == FalseBlock) { | ||||
6819 | assert(TrueBlock == nullptr &&(static_cast <bool> (TrueBlock == nullptr && "Unexpected basic block transform while optimizing select" ) ? void (0) : __assert_fail ("TrueBlock == nullptr && \"Unexpected basic block transform while optimizing select\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6820, __extension__ __PRETTY_FUNCTION__ )) | ||||
6820 | "Unexpected basic block transform while optimizing select")(static_cast <bool> (TrueBlock == nullptr && "Unexpected basic block transform while optimizing select" ) ? void (0) : __assert_fail ("TrueBlock == nullptr && \"Unexpected basic block transform while optimizing select\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6820, __extension__ __PRETTY_FUNCTION__ )); | ||||
6821 | |||||
6822 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false", | ||||
6823 | EndBlock->getParent(), EndBlock); | ||||
6824 | auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock); | ||||
6825 | FalseBranch->setDebugLoc(SI->getDebugLoc()); | ||||
6826 | } | ||||
6827 | |||||
6828 | // Insert the real conditional branch based on the original condition. | ||||
6829 | // If we did not create a new block for one of the 'true' or 'false' paths | ||||
6830 | // of the condition, it means that side of the branch goes to the end block | ||||
6831 | // directly and the path originates from the start block from the point of | ||||
6832 | // view of the new PHI. | ||||
6833 | BasicBlock *TT, *FT; | ||||
6834 | if (TrueBlock == nullptr) { | ||||
6835 | TT = EndBlock; | ||||
6836 | FT = FalseBlock; | ||||
6837 | TrueBlock = StartBlock; | ||||
6838 | } else if (FalseBlock == nullptr) { | ||||
6839 | TT = TrueBlock; | ||||
6840 | FT = EndBlock; | ||||
6841 | FalseBlock = StartBlock; | ||||
6842 | } else { | ||||
6843 | TT = TrueBlock; | ||||
6844 | FT = FalseBlock; | ||||
6845 | } | ||||
6846 | IRBuilder<> IB(SI); | ||||
6847 | auto *CondFr = IB.CreateFreeze(SI->getCondition(), SI->getName() + ".frozen"); | ||||
6848 | IB.CreateCondBr(CondFr, TT, FT, SI); | ||||
6849 | |||||
6850 | SmallPtrSet<const Instruction *, 2> INS; | ||||
6851 | INS.insert(ASI.begin(), ASI.end()); | ||||
6852 | // Use reverse iterator because later select may use the value of the | ||||
6853 | // earlier select, and we need to propagate value through earlier select | ||||
6854 | // to get the PHI operand. | ||||
6855 | for (SelectInst *SI : llvm::reverse(ASI)) { | ||||
6856 | // The select itself is replaced with a PHI Node. | ||||
6857 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front()); | ||||
6858 | PN->takeName(SI); | ||||
6859 | PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock); | ||||
6860 | PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock); | ||||
6861 | PN->setDebugLoc(SI->getDebugLoc()); | ||||
6862 | |||||
6863 | SI->replaceAllUsesWith(PN); | ||||
6864 | SI->eraseFromParent(); | ||||
6865 | INS.erase(SI); | ||||
6866 | ++NumSelectsExpanded; | ||||
6867 | } | ||||
6868 | |||||
6869 | // Instruct OptimizeBlock to skip to the next block. | ||||
6870 | CurInstIterator = StartBlock->end(); | ||||
6871 | return true; | ||||
6872 | } | ||||
6873 | |||||
6874 | /// Some targets only accept certain types for splat inputs. For example a VDUP | ||||
6875 | /// in MVE takes a GPR (integer) register, and the instruction that incorporate | ||||
6876 | /// a VDUP (such as a VADD qd, qm, rm) also require a gpr register. | ||||
6877 | bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) { | ||||
6878 | // Accept shuf(insertelem(undef/poison, val, 0), undef/poison, <0,0,..>) only | ||||
6879 | if (!match(SVI, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), | ||||
6880 | m_Undef(), m_ZeroMask()))) | ||||
6881 | return false; | ||||
6882 | Type *NewType = TLI->shouldConvertSplatType(SVI); | ||||
6883 | if (!NewType) | ||||
6884 | return false; | ||||
6885 | |||||
6886 | auto *SVIVecType = cast<FixedVectorType>(SVI->getType()); | ||||
6887 | assert(!NewType->isVectorTy() && "Expected a scalar type!")(static_cast <bool> (!NewType->isVectorTy() && "Expected a scalar type!") ? void (0) : __assert_fail ("!NewType->isVectorTy() && \"Expected a scalar type!\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6887, __extension__ __PRETTY_FUNCTION__ )); | ||||
6888 | assert(NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() &&(static_cast <bool> (NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() && "Expected a type of the same size!" ) ? void (0) : __assert_fail ("NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() && \"Expected a type of the same size!\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6889, __extension__ __PRETTY_FUNCTION__ )) | ||||
6889 | "Expected a type of the same size!")(static_cast <bool> (NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() && "Expected a type of the same size!" ) ? void (0) : __assert_fail ("NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() && \"Expected a type of the same size!\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 6889, __extension__ __PRETTY_FUNCTION__ )); | ||||
6890 | auto *NewVecType = | ||||
6891 | FixedVectorType::get(NewType, SVIVecType->getNumElements()); | ||||
6892 | |||||
6893 | // Create a bitcast (shuffle (insert (bitcast(..)))) | ||||
6894 | IRBuilder<> Builder(SVI->getContext()); | ||||
6895 | Builder.SetInsertPoint(SVI); | ||||
6896 | Value *BC1 = Builder.CreateBitCast( | ||||
6897 | cast<Instruction>(SVI->getOperand(0))->getOperand(1), NewType); | ||||
6898 | Value *Shuffle = Builder.CreateVectorSplat(NewVecType->getNumElements(), BC1); | ||||
6899 | Value *BC2 = Builder.CreateBitCast(Shuffle, SVIVecType); | ||||
6900 | |||||
6901 | SVI->replaceAllUsesWith(BC2); | ||||
6902 | RecursivelyDeleteTriviallyDeadInstructions( | ||||
6903 | SVI, TLInfo, nullptr, [&](Value *V) { removeAllAssertingVHReferences(V); }); | ||||
6904 | |||||
6905 | // Also hoist the bitcast up to its operand if it they are not in the same | ||||
6906 | // block. | ||||
6907 | if (auto *BCI = dyn_cast<Instruction>(BC1)) | ||||
6908 | if (auto *Op = dyn_cast<Instruction>(BCI->getOperand(0))) | ||||
6909 | if (BCI->getParent() != Op->getParent() && !isa<PHINode>(Op) && | ||||
6910 | !Op->isTerminator() && !Op->isEHPad()) | ||||
6911 | BCI->moveAfter(Op); | ||||
6912 | |||||
6913 | return true; | ||||
6914 | } | ||||
6915 | |||||
6916 | bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) { | ||||
6917 | // If the operands of I can be folded into a target instruction together with | ||||
6918 | // I, duplicate and sink them. | ||||
6919 | SmallVector<Use *, 4> OpsToSink; | ||||
6920 | if (!TLI->shouldSinkOperands(I, OpsToSink)) | ||||
6921 | return false; | ||||
6922 | |||||
6923 | // OpsToSink can contain multiple uses in a use chain (e.g. | ||||
6924 | // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating | ||||
6925 | // uses must come first, so we process the ops in reverse order so as to not | ||||
6926 | // create invalid IR. | ||||
6927 | BasicBlock *TargetBB = I->getParent(); | ||||
6928 | bool Changed = false; | ||||
6929 | SmallVector<Use *, 4> ToReplace; | ||||
6930 | Instruction *InsertPoint = I; | ||||
6931 | DenseMap<const Instruction *, unsigned long> InstOrdering; | ||||
6932 | unsigned long InstNumber = 0; | ||||
6933 | for (const auto &I : *TargetBB) | ||||
6934 | InstOrdering[&I] = InstNumber++; | ||||
6935 | |||||
6936 | for (Use *U : reverse(OpsToSink)) { | ||||
6937 | auto *UI = cast<Instruction>(U->get()); | ||||
6938 | if (isa<PHINode>(UI)) | ||||
6939 | continue; | ||||
6940 | if (UI->getParent() == TargetBB) { | ||||
6941 | if (InstOrdering[UI] < InstOrdering[InsertPoint]) | ||||
6942 | InsertPoint = UI; | ||||
6943 | continue; | ||||
6944 | } | ||||
6945 | ToReplace.push_back(U); | ||||
6946 | } | ||||
6947 | |||||
6948 | SetVector<Instruction *> MaybeDead; | ||||
6949 | DenseMap<Instruction *, Instruction *> NewInstructions; | ||||
6950 | for (Use *U : ToReplace) { | ||||
6951 | auto *UI = cast<Instruction>(U->get()); | ||||
6952 | Instruction *NI = UI->clone(); | ||||
6953 | NewInstructions[UI] = NI; | ||||
6954 | MaybeDead.insert(UI); | ||||
6955 | LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Sinking " << *UI << " to user " << *I << "\n"; } } while (false ); | ||||
6956 | NI->insertBefore(InsertPoint); | ||||
6957 | InsertPoint = NI; | ||||
6958 | InsertedInsts.insert(NI); | ||||
6959 | |||||
6960 | // Update the use for the new instruction, making sure that we update the | ||||
6961 | // sunk instruction uses, if it is part of a chain that has already been | ||||
6962 | // sunk. | ||||
6963 | Instruction *OldI = cast<Instruction>(U->getUser()); | ||||
6964 | if (NewInstructions.count(OldI)) | ||||
6965 | NewInstructions[OldI]->setOperand(U->getOperandNo(), NI); | ||||
6966 | else | ||||
6967 | U->set(NI); | ||||
6968 | Changed = true; | ||||
6969 | } | ||||
6970 | |||||
6971 | // Remove instructions that are dead after sinking. | ||||
6972 | for (auto *I : MaybeDead) { | ||||
6973 | if (!I->hasNUsesOrMore(1)) { | ||||
6974 | LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Removing dead instruction: " << *I << "\n"; } } while (false); | ||||
6975 | I->eraseFromParent(); | ||||
6976 | } | ||||
6977 | } | ||||
6978 | |||||
6979 | return Changed; | ||||
6980 | } | ||||
6981 | |||||
6982 | bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) { | ||||
6983 | Value *Cond = SI->getCondition(); | ||||
6984 | Type *OldType = Cond->getType(); | ||||
6985 | LLVMContext &Context = Cond->getContext(); | ||||
6986 | EVT OldVT = TLI->getValueType(*DL, OldType); | ||||
6987 | MVT RegType = TLI->getRegisterType(Context, OldVT); | ||||
6988 | unsigned RegWidth = RegType.getSizeInBits(); | ||||
6989 | |||||
6990 | if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth()) | ||||
6991 | return false; | ||||
6992 | |||||
6993 | // If the register width is greater than the type width, expand the condition | ||||
6994 | // of the switch instruction and each case constant to the width of the | ||||
6995 | // register. By widening the type of the switch condition, subsequent | ||||
6996 | // comparisons (for case comparisons) will not need to be extended to the | ||||
6997 | // preferred register width, so we will potentially eliminate N-1 extends, | ||||
6998 | // where N is the number of cases in the switch. | ||||
6999 | auto *NewType = Type::getIntNTy(Context, RegWidth); | ||||
7000 | |||||
7001 | // Extend the switch condition and case constants using the target preferred | ||||
7002 | // extend unless the switch condition is a function argument with an extend | ||||
7003 | // attribute. In that case, we can avoid an unnecessary mask/extension by | ||||
7004 | // matching the argument extension instead. | ||||
7005 | Instruction::CastOps ExtType = Instruction::ZExt; | ||||
7006 | // Some targets prefer SExt over ZExt. | ||||
7007 | if (TLI->isSExtCheaperThanZExt(OldVT, RegType)) | ||||
7008 | ExtType = Instruction::SExt; | ||||
7009 | |||||
7010 | if (auto *Arg = dyn_cast<Argument>(Cond)) { | ||||
7011 | if (Arg->hasSExtAttr()) | ||||
7012 | ExtType = Instruction::SExt; | ||||
7013 | if (Arg->hasZExtAttr()) | ||||
7014 | ExtType = Instruction::ZExt; | ||||
7015 | } | ||||
7016 | |||||
7017 | auto *ExtInst = CastInst::Create(ExtType, Cond, NewType); | ||||
7018 | ExtInst->insertBefore(SI); | ||||
7019 | ExtInst->setDebugLoc(SI->getDebugLoc()); | ||||
7020 | SI->setCondition(ExtInst); | ||||
7021 | for (auto Case : SI->cases()) { | ||||
7022 | APInt NarrowConst = Case.getCaseValue()->getValue(); | ||||
7023 | APInt WideConst = (ExtType == Instruction::ZExt) ? | ||||
7024 | NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth); | ||||
7025 | Case.setValue(ConstantInt::get(Context, WideConst)); | ||||
7026 | } | ||||
7027 | |||||
7028 | return true; | ||||
7029 | } | ||||
7030 | |||||
7031 | |||||
7032 | namespace { | ||||
7033 | |||||
7034 | /// Helper class to promote a scalar operation to a vector one. | ||||
7035 | /// This class is used to move downward extractelement transition. | ||||
7036 | /// E.g., | ||||
7037 | /// a = vector_op <2 x i32> | ||||
7038 | /// b = extractelement <2 x i32> a, i32 0 | ||||
7039 | /// c = scalar_op b | ||||
7040 | /// store c | ||||
7041 | /// | ||||
7042 | /// => | ||||
7043 | /// a = vector_op <2 x i32> | ||||
7044 | /// c = vector_op a (equivalent to scalar_op on the related lane) | ||||
7045 | /// * d = extractelement <2 x i32> c, i32 0 | ||||
7046 | /// * store d | ||||
7047 | /// Assuming both extractelement and store can be combine, we get rid of the | ||||
7048 | /// transition. | ||||
7049 | class VectorPromoteHelper { | ||||
7050 | /// DataLayout associated with the current module. | ||||
7051 | const DataLayout &DL; | ||||
7052 | |||||
7053 | /// Used to perform some checks on the legality of vector operations. | ||||
7054 | const TargetLowering &TLI; | ||||
7055 | |||||
7056 | /// Used to estimated the cost of the promoted chain. | ||||
7057 | const TargetTransformInfo &TTI; | ||||
7058 | |||||
7059 | /// The transition being moved downwards. | ||||
7060 | Instruction *Transition; | ||||
7061 | |||||
7062 | /// The sequence of instructions to be promoted. | ||||
7063 | SmallVector<Instruction *, 4> InstsToBePromoted; | ||||
7064 | |||||
7065 | /// Cost of combining a store and an extract. | ||||
7066 | unsigned StoreExtractCombineCost; | ||||
7067 | |||||
7068 | /// Instruction that will be combined with the transition. | ||||
7069 | Instruction *CombineInst = nullptr; | ||||
7070 | |||||
7071 | /// The instruction that represents the current end of the transition. | ||||
7072 | /// Since we are faking the promotion until we reach the end of the chain | ||||
7073 | /// of computation, we need a way to get the current end of the transition. | ||||
7074 | Instruction *getEndOfTransition() const { | ||||
7075 | if (InstsToBePromoted.empty()) | ||||
7076 | return Transition; | ||||
7077 | return InstsToBePromoted.back(); | ||||
7078 | } | ||||
7079 | |||||
7080 | /// Return the index of the original value in the transition. | ||||
7081 | /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, | ||||
7082 | /// c, is at index 0. | ||||
7083 | unsigned getTransitionOriginalValueIdx() const { | ||||
7084 | assert(isa<ExtractElementInst>(Transition) &&(static_cast <bool> (isa<ExtractElementInst>(Transition ) && "Other kind of transitions are not supported yet" ) ? void (0) : __assert_fail ("isa<ExtractElementInst>(Transition) && \"Other kind of transitions are not supported yet\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7085, __extension__ __PRETTY_FUNCTION__ )) | ||||
7085 | "Other kind of transitions are not supported yet")(static_cast <bool> (isa<ExtractElementInst>(Transition ) && "Other kind of transitions are not supported yet" ) ? void (0) : __assert_fail ("isa<ExtractElementInst>(Transition) && \"Other kind of transitions are not supported yet\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7085, __extension__ __PRETTY_FUNCTION__ )); | ||||
7086 | return 0; | ||||
7087 | } | ||||
7088 | |||||
7089 | /// Return the index of the index in the transition. | ||||
7090 | /// E.g., for "extractelement <2 x i32> c, i32 0" the index | ||||
7091 | /// is at index 1. | ||||
7092 | unsigned getTransitionIdx() const { | ||||
7093 | assert(isa<ExtractElementInst>(Transition) &&(static_cast <bool> (isa<ExtractElementInst>(Transition ) && "Other kind of transitions are not supported yet" ) ? void (0) : __assert_fail ("isa<ExtractElementInst>(Transition) && \"Other kind of transitions are not supported yet\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7094, __extension__ __PRETTY_FUNCTION__ )) | ||||
7094 | "Other kind of transitions are not supported yet")(static_cast <bool> (isa<ExtractElementInst>(Transition ) && "Other kind of transitions are not supported yet" ) ? void (0) : __assert_fail ("isa<ExtractElementInst>(Transition) && \"Other kind of transitions are not supported yet\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7094, __extension__ __PRETTY_FUNCTION__ )); | ||||
7095 | return 1; | ||||
7096 | } | ||||
7097 | |||||
7098 | /// Get the type of the transition. | ||||
7099 | /// This is the type of the original value. | ||||
7100 | /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the | ||||
7101 | /// transition is <2 x i32>. | ||||
7102 | Type *getTransitionType() const { | ||||
7103 | return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); | ||||
7104 | } | ||||
7105 | |||||
7106 | /// Promote \p ToBePromoted by moving \p Def downward through. | ||||
7107 | /// I.e., we have the following sequence: | ||||
7108 | /// Def = Transition <ty1> a to <ty2> | ||||
7109 | /// b = ToBePromoted <ty2> Def, ... | ||||
7110 | /// => | ||||
7111 | /// b = ToBePromoted <ty1> a, ... | ||||
7112 | /// Def = Transition <ty1> ToBePromoted to <ty2> | ||||
7113 | void promoteImpl(Instruction *ToBePromoted); | ||||
7114 | |||||
7115 | /// Check whether or not it is profitable to promote all the | ||||
7116 | /// instructions enqueued to be promoted. | ||||
7117 | bool isProfitableToPromote() { | ||||
7118 | Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); | ||||
7119 | unsigned Index = isa<ConstantInt>(ValIdx) | ||||
7120 | ? cast<ConstantInt>(ValIdx)->getZExtValue() | ||||
7121 | : -1; | ||||
7122 | Type *PromotedType = getTransitionType(); | ||||
7123 | |||||
7124 | StoreInst *ST = cast<StoreInst>(CombineInst); | ||||
7125 | unsigned AS = ST->getPointerAddressSpace(); | ||||
7126 | // Check if this store is supported. | ||||
7127 | if (!TLI.allowsMisalignedMemoryAccesses( | ||||
7128 | TLI.getValueType(DL, ST->getValueOperand()->getType()), AS, | ||||
7129 | ST->getAlign())) { | ||||
7130 | // If this is not supported, there is no way we can combine | ||||
7131 | // the extract with the store. | ||||
7132 | return false; | ||||
7133 | } | ||||
7134 | |||||
7135 | // The scalar chain of computation has to pay for the transition | ||||
7136 | // scalar to vector. | ||||
7137 | // The vector chain has to account for the combining cost. | ||||
7138 | InstructionCost ScalarCost = | ||||
7139 | TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); | ||||
7140 | InstructionCost VectorCost = StoreExtractCombineCost; | ||||
7141 | enum TargetTransformInfo::TargetCostKind CostKind = | ||||
7142 | TargetTransformInfo::TCK_RecipThroughput; | ||||
7143 | for (const auto &Inst : InstsToBePromoted) { | ||||
7144 | // Compute the cost. | ||||
7145 | // By construction, all instructions being promoted are arithmetic ones. | ||||
7146 | // Moreover, one argument is a constant that can be viewed as a splat | ||||
7147 | // constant. | ||||
7148 | Value *Arg0 = Inst->getOperand(0); | ||||
7149 | bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || | ||||
7150 | isa<ConstantFP>(Arg0); | ||||
7151 | TargetTransformInfo::OperandValueKind Arg0OVK = | ||||
7152 | IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue | ||||
7153 | : TargetTransformInfo::OK_AnyValue; | ||||
7154 | TargetTransformInfo::OperandValueKind Arg1OVK = | ||||
7155 | !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue | ||||
7156 | : TargetTransformInfo::OK_AnyValue; | ||||
7157 | ScalarCost += TTI.getArithmeticInstrCost( | ||||
7158 | Inst->getOpcode(), Inst->getType(), CostKind, Arg0OVK, Arg1OVK); | ||||
7159 | VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, | ||||
7160 | CostKind, | ||||
7161 | Arg0OVK, Arg1OVK); | ||||
7162 | } | ||||
7163 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Estimated cost of computation to be promoted:\nScalar: " << ScalarCost << "\nVector: " << VectorCost << '\n'; } } while (false) | ||||
7164 | dbgs() << "Estimated cost of computation to be promoted:\nScalar: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Estimated cost of computation to be promoted:\nScalar: " << ScalarCost << "\nVector: " << VectorCost << '\n'; } } while (false) | ||||
7165 | << ScalarCost << "\nVector: " << VectorCost << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Estimated cost of computation to be promoted:\nScalar: " << ScalarCost << "\nVector: " << VectorCost << '\n'; } } while (false); | ||||
7166 | return ScalarCost > VectorCost; | ||||
7167 | } | ||||
7168 | |||||
7169 | /// Generate a constant vector with \p Val with the same | ||||
7170 | /// number of elements as the transition. | ||||
7171 | /// \p UseSplat defines whether or not \p Val should be replicated | ||||
7172 | /// across the whole vector. | ||||
7173 | /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, | ||||
7174 | /// otherwise we generate a vector with as many undef as possible: | ||||
7175 | /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only | ||||
7176 | /// used at the index of the extract. | ||||
7177 | Value *getConstantVector(Constant *Val, bool UseSplat) const { | ||||
7178 | unsigned ExtractIdx = std::numeric_limits<unsigned>::max(); | ||||
7179 | if (!UseSplat) { | ||||
7180 | // If we cannot determine where the constant must be, we have to | ||||
7181 | // use a splat constant. | ||||
7182 | Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); | ||||
7183 | if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) | ||||
7184 | ExtractIdx = CstVal->getSExtValue(); | ||||
7185 | else | ||||
7186 | UseSplat = true; | ||||
7187 | } | ||||
7188 | |||||
7189 | ElementCount EC = cast<VectorType>(getTransitionType())->getElementCount(); | ||||
7190 | if (UseSplat) | ||||
7191 | return ConstantVector::getSplat(EC, Val); | ||||
7192 | |||||
7193 | if (!EC.isScalable()) { | ||||
7194 | SmallVector<Constant *, 4> ConstVec; | ||||
7195 | UndefValue *UndefVal = UndefValue::get(Val->getType()); | ||||
7196 | for (unsigned Idx = 0; Idx != EC.getKnownMinValue(); ++Idx) { | ||||
7197 | if (Idx == ExtractIdx) | ||||
7198 | ConstVec.push_back(Val); | ||||
7199 | else | ||||
7200 | ConstVec.push_back(UndefVal); | ||||
7201 | } | ||||
7202 | return ConstantVector::get(ConstVec); | ||||
7203 | } else | ||||
7204 | llvm_unreachable(::llvm::llvm_unreachable_internal("Generate scalable vector for non-splat is unimplemented" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7205) | ||||
7205 | "Generate scalable vector for non-splat is unimplemented")::llvm::llvm_unreachable_internal("Generate scalable vector for non-splat is unimplemented" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7205); | ||||
7206 | } | ||||
7207 | |||||
7208 | /// Check if promoting to a vector type an operand at \p OperandIdx | ||||
7209 | /// in \p Use can trigger undefined behavior. | ||||
7210 | static bool canCauseUndefinedBehavior(const Instruction *Use, | ||||
7211 | unsigned OperandIdx) { | ||||
7212 | // This is not safe to introduce undef when the operand is on | ||||
7213 | // the right hand side of a division-like instruction. | ||||
7214 | if (OperandIdx != 1) | ||||
7215 | return false; | ||||
7216 | switch (Use->getOpcode()) { | ||||
7217 | default: | ||||
7218 | return false; | ||||
7219 | case Instruction::SDiv: | ||||
7220 | case Instruction::UDiv: | ||||
7221 | case Instruction::SRem: | ||||
7222 | case Instruction::URem: | ||||
7223 | return true; | ||||
7224 | case Instruction::FDiv: | ||||
7225 | case Instruction::FRem: | ||||
7226 | return !Use->hasNoNaNs(); | ||||
7227 | } | ||||
7228 | llvm_unreachable(nullptr)::llvm::llvm_unreachable_internal(nullptr, "llvm/lib/CodeGen/CodeGenPrepare.cpp" , 7228); | ||||
7229 | } | ||||
7230 | |||||
7231 | public: | ||||
7232 | VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI, | ||||
7233 | const TargetTransformInfo &TTI, Instruction *Transition, | ||||
7234 | unsigned CombineCost) | ||||
7235 | : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition), | ||||
7236 | StoreExtractCombineCost(CombineCost) { | ||||
7237 | assert(Transition && "Do not know how to promote null")(static_cast <bool> (Transition && "Do not know how to promote null" ) ? void (0) : __assert_fail ("Transition && \"Do not know how to promote null\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7237, __extension__ __PRETTY_FUNCTION__ )); | ||||
7238 | } | ||||
7239 | |||||
7240 | /// Check if we can promote \p ToBePromoted to \p Type. | ||||
7241 | bool canPromote(const Instruction *ToBePromoted) const { | ||||
7242 | // We could support CastInst too. | ||||
7243 | return isa<BinaryOperator>(ToBePromoted); | ||||
7244 | } | ||||
7245 | |||||
7246 | /// Check if it is profitable to promote \p ToBePromoted | ||||
7247 | /// by moving downward the transition through. | ||||
7248 | bool shouldPromote(const Instruction *ToBePromoted) const { | ||||
7249 | // Promote only if all the operands can be statically expanded. | ||||
7250 | // Indeed, we do not want to introduce any new kind of transitions. | ||||
7251 | for (const Use &U : ToBePromoted->operands()) { | ||||
7252 | const Value *Val = U.get(); | ||||
7253 | if (Val == getEndOfTransition()) { | ||||
7254 | // If the use is a division and the transition is on the rhs, | ||||
7255 | // we cannot promote the operation, otherwise we may create a | ||||
7256 | // division by zero. | ||||
7257 | if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) | ||||
7258 | return false; | ||||
7259 | continue; | ||||
7260 | } | ||||
7261 | if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && | ||||
7262 | !isa<ConstantFP>(Val)) | ||||
7263 | return false; | ||||
7264 | } | ||||
7265 | // Check that the resulting operation is legal. | ||||
7266 | int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); | ||||
7267 | if (!ISDOpcode) | ||||
7268 | return false; | ||||
7269 | return StressStoreExtract || | ||||
7270 | TLI.isOperationLegalOrCustom( | ||||
7271 | ISDOpcode, TLI.getValueType(DL, getTransitionType(), true)); | ||||
7272 | } | ||||
7273 | |||||
7274 | /// Check whether or not \p Use can be combined | ||||
7275 | /// with the transition. | ||||
7276 | /// I.e., is it possible to do Use(Transition) => AnotherUse? | ||||
7277 | bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } | ||||
7278 | |||||
7279 | /// Record \p ToBePromoted as part of the chain to be promoted. | ||||
7280 | void enqueueForPromotion(Instruction *ToBePromoted) { | ||||
7281 | InstsToBePromoted.push_back(ToBePromoted); | ||||
7282 | } | ||||
7283 | |||||
7284 | /// Set the instruction that will be combined with the transition. | ||||
7285 | void recordCombineInstruction(Instruction *ToBeCombined) { | ||||
7286 | assert(canCombine(ToBeCombined) && "Unsupported instruction to combine")(static_cast <bool> (canCombine(ToBeCombined) && "Unsupported instruction to combine") ? void (0) : __assert_fail ("canCombine(ToBeCombined) && \"Unsupported instruction to combine\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7286, __extension__ __PRETTY_FUNCTION__ )); | ||||
7287 | CombineInst = ToBeCombined; | ||||
7288 | } | ||||
7289 | |||||
7290 | /// Promote all the instructions enqueued for promotion if it is | ||||
7291 | /// is profitable. | ||||
7292 | /// \return True if the promotion happened, false otherwise. | ||||
7293 | bool promote() { | ||||
7294 | // Check if there is something to promote. | ||||
7295 | // Right now, if we do not have anything to combine with, | ||||
7296 | // we assume the promotion is not profitable. | ||||
7297 | if (InstsToBePromoted.empty() || !CombineInst) | ||||
7298 | return false; | ||||
7299 | |||||
7300 | // Check cost. | ||||
7301 | if (!StressStoreExtract && !isProfitableToPromote()) | ||||
7302 | return false; | ||||
7303 | |||||
7304 | // Promote. | ||||
7305 | for (auto &ToBePromoted : InstsToBePromoted) | ||||
7306 | promoteImpl(ToBePromoted); | ||||
7307 | InstsToBePromoted.clear(); | ||||
7308 | return true; | ||||
7309 | } | ||||
7310 | }; | ||||
7311 | |||||
7312 | } // end anonymous namespace | ||||
7313 | |||||
7314 | void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { | ||||
7315 | // At this point, we know that all the operands of ToBePromoted but Def | ||||
7316 | // can be statically promoted. | ||||
7317 | // For Def, we need to use its parameter in ToBePromoted: | ||||
7318 | // b = ToBePromoted ty1 a | ||||
7319 | // Def = Transition ty1 b to ty2 | ||||
7320 | // Move the transition down. | ||||
7321 | // 1. Replace all uses of the promoted operation by the transition. | ||||
7322 | // = ... b => = ... Def. | ||||
7323 | assert(ToBePromoted->getType() == Transition->getType() &&(static_cast <bool> (ToBePromoted->getType() == Transition ->getType() && "The type of the result of the transition does not match " "the final type") ? void (0) : __assert_fail ("ToBePromoted->getType() == Transition->getType() && \"The type of the result of the transition does not match \" \"the final type\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7325, __extension__ __PRETTY_FUNCTION__ )) | ||||
7324 | "The type of the result of the transition does not match "(static_cast <bool> (ToBePromoted->getType() == Transition ->getType() && "The type of the result of the transition does not match " "the final type") ? void (0) : __assert_fail ("ToBePromoted->getType() == Transition->getType() && \"The type of the result of the transition does not match \" \"the final type\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7325, __extension__ __PRETTY_FUNCTION__ )) | ||||
7325 | "the final type")(static_cast <bool> (ToBePromoted->getType() == Transition ->getType() && "The type of the result of the transition does not match " "the final type") ? void (0) : __assert_fail ("ToBePromoted->getType() == Transition->getType() && \"The type of the result of the transition does not match \" \"the final type\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7325, __extension__ __PRETTY_FUNCTION__ )); | ||||
7326 | ToBePromoted->replaceAllUsesWith(Transition); | ||||
7327 | // 2. Update the type of the uses. | ||||
7328 | // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. | ||||
7329 | Type *TransitionTy = getTransitionType(); | ||||
7330 | ToBePromoted->mutateType(TransitionTy); | ||||
7331 | // 3. Update all the operands of the promoted operation with promoted | ||||
7332 | // operands. | ||||
7333 | // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. | ||||
7334 | for (Use &U : ToBePromoted->operands()) { | ||||
7335 | Value *Val = U.get(); | ||||
7336 | Value *NewVal = nullptr; | ||||
7337 | if (Val == Transition) | ||||
7338 | NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); | ||||
7339 | else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || | ||||
7340 | isa<ConstantFP>(Val)) { | ||||
7341 | // Use a splat constant if it is not safe to use undef. | ||||
7342 | NewVal = getConstantVector( | ||||
7343 | cast<Constant>(Val), | ||||
7344 | isa<UndefValue>(Val) || | ||||
7345 | canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); | ||||
7346 | } else | ||||
7347 | llvm_unreachable("Did you modified shouldPromote and forgot to update "::llvm::llvm_unreachable_internal("Did you modified shouldPromote and forgot to update " "this?", "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7348) | ||||
7348 | "this?")::llvm::llvm_unreachable_internal("Did you modified shouldPromote and forgot to update " "this?", "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7348); | ||||
7349 | ToBePromoted->setOperand(U.getOperandNo(), NewVal); | ||||
7350 | } | ||||
7351 | Transition->moveAfter(ToBePromoted); | ||||
7352 | Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); | ||||
7353 | } | ||||
7354 | |||||
7355 | /// Some targets can do store(extractelement) with one instruction. | ||||
7356 | /// Try to push the extractelement towards the stores when the target | ||||
7357 | /// has this feature and this is profitable. | ||||
7358 | bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) { | ||||
7359 | unsigned CombineCost = std::numeric_limits<unsigned>::max(); | ||||
7360 | if (DisableStoreExtract || | ||||
7361 | (!StressStoreExtract && | ||||
7362 | !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), | ||||
7363 | Inst->getOperand(1), CombineCost))) | ||||
7364 | return false; | ||||
7365 | |||||
7366 | // At this point we know that Inst is a vector to scalar transition. | ||||
7367 | // Try to move it down the def-use chain, until: | ||||
7368 | // - We can combine the transition with its single use | ||||
7369 | // => we got rid of the transition. | ||||
7370 | // - We escape the current basic block | ||||
7371 | // => we would need to check that we are moving it at a cheaper place and | ||||
7372 | // we do not do that for now. | ||||
7373 | BasicBlock *Parent = Inst->getParent(); | ||||
7374 | LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Found an interesting transition: " << *Inst << '\n'; } } while (false); | ||||
7375 | VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost); | ||||
7376 | // If the transition has more than one use, assume this is not going to be | ||||
7377 | // beneficial. | ||||
7378 | while (Inst->hasOneUse()) { | ||||
7379 | Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); | ||||
7380 | LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Use: " << *ToBePromoted << '\n'; } } while (false); | ||||
7381 | |||||
7382 | if (ToBePromoted->getParent() != Parent) { | ||||
7383 | LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Instruction to promote is in a different block (" << ToBePromoted->getParent()->getName() << ") than the transition (" << Parent->getName() << ").\n"; } } while (false) | ||||
7384 | << ToBePromoted->getParent()->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Instruction to promote is in a different block (" << ToBePromoted->getParent()->getName() << ") than the transition (" << Parent->getName() << ").\n"; } } while (false) | ||||
7385 | << ") than the transition (" << Parent->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Instruction to promote is in a different block (" << ToBePromoted->getParent()->getName() << ") than the transition (" << Parent->getName() << ").\n"; } } while (false) | ||||
7386 | << ").\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Instruction to promote is in a different block (" << ToBePromoted->getParent()->getName() << ") than the transition (" << Parent->getName() << ").\n"; } } while (false); | ||||
7387 | return false; | ||||
7388 | } | ||||
7389 | |||||
7390 | if (VPH.canCombine(ToBePromoted)) { | ||||
7391 | LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Assume " << *Inst << '\n' << "will be combined with: " << *ToBePromoted << '\n'; } } while (false) | ||||
7392 | << "will be combined with: " << *ToBePromoted << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Assume " << *Inst << '\n' << "will be combined with: " << *ToBePromoted << '\n'; } } while (false); | ||||
7393 | VPH.recordCombineInstruction(ToBePromoted); | ||||
7394 | bool Changed = VPH.promote(); | ||||
7395 | NumStoreExtractExposed += Changed; | ||||
7396 | return Changed; | ||||
7397 | } | ||||
7398 | |||||
7399 | LLVM_DEBUG(dbgs() << "Try promoting.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Try promoting.\n"; } } while (false); | ||||
7400 | if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) | ||||
7401 | return false; | ||||
7402 | |||||
7403 | LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Promoting is possible... Enqueue for promotion!\n" ; } } while (false); | ||||
7404 | |||||
7405 | VPH.enqueueForPromotion(ToBePromoted); | ||||
7406 | Inst = ToBePromoted; | ||||
7407 | } | ||||
7408 | return false; | ||||
7409 | } | ||||
7410 | |||||
7411 | /// For the instruction sequence of store below, F and I values | ||||
7412 | /// are bundled together as an i64 value before being stored into memory. | ||||
7413 | /// Sometimes it is more efficient to generate separate stores for F and I, | ||||
7414 | /// which can remove the bitwise instructions or sink them to colder places. | ||||
7415 | /// | ||||
7416 | /// (store (or (zext (bitcast F to i32) to i64), | ||||
7417 | /// (shl (zext I to i64), 32)), addr) --> | ||||
7418 | /// (store F, addr) and (store I, addr+4) | ||||
7419 | /// | ||||
7420 | /// Similarly, splitting for other merged store can also be beneficial, like: | ||||
7421 | /// For pair of {i32, i32}, i64 store --> two i32 stores. | ||||
7422 | /// For pair of {i32, i16}, i64 store --> two i32 stores. | ||||
7423 | /// For pair of {i16, i16}, i32 store --> two i16 stores. | ||||
7424 | /// For pair of {i16, i8}, i32 store --> two i16 stores. | ||||
7425 | /// For pair of {i8, i8}, i16 store --> two i8 stores. | ||||
7426 | /// | ||||
7427 | /// We allow each target to determine specifically which kind of splitting is | ||||
7428 | /// supported. | ||||
7429 | /// | ||||
7430 | /// The store patterns are commonly seen from the simple code snippet below | ||||
7431 | /// if only std::make_pair(...) is sroa transformed before inlined into hoo. | ||||
7432 | /// void goo(const std::pair<int, float> &); | ||||
7433 | /// hoo() { | ||||
7434 | /// ... | ||||
7435 | /// goo(std::make_pair(tmp, ftmp)); | ||||
7436 | /// ... | ||||
7437 | /// } | ||||
7438 | /// | ||||
7439 | /// Although we already have similar splitting in DAG Combine, we duplicate | ||||
7440 | /// it in CodeGenPrepare to catch the case in which pattern is across | ||||
7441 | /// multiple BBs. The logic in DAG Combine is kept to catch case generated | ||||
7442 | /// during code expansion. | ||||
7443 | static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, | ||||
7444 | const TargetLowering &TLI) { | ||||
7445 | // Handle simple but common cases only. | ||||
7446 | Type *StoreType = SI.getValueOperand()->getType(); | ||||
7447 | |||||
7448 | // The code below assumes shifting a value by <number of bits>, | ||||
7449 | // whereas scalable vectors would have to be shifted by | ||||
7450 | // <2log(vscale) + number of bits> in order to store the | ||||
7451 | // low/high parts. Bailing out for now. | ||||
7452 | if (isa<ScalableVectorType>(StoreType)) | ||||
7453 | return false; | ||||
7454 | |||||
7455 | if (!DL.typeSizeEqualsStoreSize(StoreType) || | ||||
7456 | DL.getTypeSizeInBits(StoreType) == 0) | ||||
7457 | return false; | ||||
7458 | |||||
7459 | unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2; | ||||
7460 | Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize); | ||||
7461 | if (!DL.typeSizeEqualsStoreSize(SplitStoreType)) | ||||
7462 | return false; | ||||
7463 | |||||
7464 | // Don't split the store if it is volatile. | ||||
7465 | if (SI.isVolatile()) | ||||
7466 | return false; | ||||
7467 | |||||
7468 | // Match the following patterns: | ||||
7469 | // (store (or (zext LValue to i64), | ||||
7470 | // (shl (zext HValue to i64), 32)), HalfValBitSize) | ||||
7471 | // or | ||||
7472 | // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize) | ||||
7473 | // (zext LValue to i64), | ||||
7474 | // Expect both operands of OR and the first operand of SHL have only | ||||
7475 | // one use. | ||||
7476 | Value *LValue, *HValue; | ||||
7477 | if (!match(SI.getValueOperand(), | ||||
7478 | m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))), | ||||
7479 | m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))), | ||||
7480 | m_SpecificInt(HalfValBitSize)))))) | ||||
7481 | return false; | ||||
7482 | |||||
7483 | // Check LValue and HValue are int with size less or equal than 32. | ||||
7484 | if (!LValue->getType()->isIntegerTy() || | ||||
7485 | DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize || | ||||
7486 | !HValue->getType()->isIntegerTy() || | ||||
7487 | DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize) | ||||
7488 | return false; | ||||
7489 | |||||
7490 | // If LValue/HValue is a bitcast instruction, use the EVT before bitcast | ||||
7491 | // as the input of target query. | ||||
7492 | auto *LBC = dyn_cast<BitCastInst>(LValue); | ||||
7493 | auto *HBC = dyn_cast<BitCastInst>(HValue); | ||||
7494 | EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType()) | ||||
7495 | : EVT::getEVT(LValue->getType()); | ||||
7496 | EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType()) | ||||
7497 | : EVT::getEVT(HValue->getType()); | ||||
7498 | if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) | ||||
7499 | return false; | ||||
7500 | |||||
7501 | // Start to split store. | ||||
7502 | IRBuilder<> Builder(SI.getContext()); | ||||
7503 | Builder.SetInsertPoint(&SI); | ||||
7504 | |||||
7505 | // If LValue/HValue is a bitcast in another BB, create a new one in current | ||||
7506 | // BB so it may be merged with the splitted stores by dag combiner. | ||||
7507 | if (LBC && LBC->getParent() != SI.getParent()) | ||||
7508 | LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType()); | ||||
7509 | if (HBC && HBC->getParent() != SI.getParent()) | ||||
7510 | HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType()); | ||||
7511 | |||||
7512 | bool IsLE = SI.getModule()->getDataLayout().isLittleEndian(); | ||||
7513 | auto CreateSplitStore = [&](Value *V, bool Upper) { | ||||
7514 | V = Builder.CreateZExtOrBitCast(V, SplitStoreType); | ||||
7515 | Value *Addr = Builder.CreateBitCast( | ||||
7516 | SI.getOperand(1), | ||||
7517 | SplitStoreType->getPointerTo(SI.getPointerAddressSpace())); | ||||
7518 | Align Alignment = SI.getAlign(); | ||||
7519 | const bool IsOffsetStore = (IsLE && Upper) || (!IsLE && !Upper); | ||||
7520 | if (IsOffsetStore) { | ||||
7521 | Addr = Builder.CreateGEP( | ||||
7522 | SplitStoreType, Addr, | ||||
7523 | ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1)); | ||||
7524 | |||||
7525 | // When splitting the store in half, naturally one half will retain the | ||||
7526 | // alignment of the original wider store, regardless of whether it was | ||||
7527 | // over-aligned or not, while the other will require adjustment. | ||||
7528 | Alignment = commonAlignment(Alignment, HalfValBitSize / 8); | ||||
7529 | } | ||||
7530 | Builder.CreateAlignedStore(V, Addr, Alignment); | ||||
7531 | }; | ||||
7532 | |||||
7533 | CreateSplitStore(LValue, false); | ||||
7534 | CreateSplitStore(HValue, true); | ||||
7535 | |||||
7536 | // Delete the old store. | ||||
7537 | SI.eraseFromParent(); | ||||
7538 | return true; | ||||
7539 | } | ||||
7540 | |||||
7541 | // Return true if the GEP has two operands, the first operand is of a sequential | ||||
7542 | // type, and the second operand is a constant. | ||||
7543 | static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) { | ||||
7544 | gep_type_iterator I = gep_type_begin(*GEP); | ||||
7545 | return GEP->getNumOperands() == 2 && | ||||
7546 | I.isSequential() && | ||||
7547 | isa<ConstantInt>(GEP->getOperand(1)); | ||||
7548 | } | ||||
7549 | |||||
7550 | // Try unmerging GEPs to reduce liveness interference (register pressure) across | ||||
7551 | // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks, | ||||
7552 | // reducing liveness interference across those edges benefits global register | ||||
7553 | // allocation. Currently handles only certain cases. | ||||
7554 | // | ||||
7555 | // For example, unmerge %GEPI and %UGEPI as below. | ||||
7556 | // | ||||
7557 | // ---------- BEFORE ---------- | ||||
7558 | // SrcBlock: | ||||
7559 | // ... | ||||
7560 | // %GEPIOp = ... | ||||
7561 | // ... | ||||
7562 | // %GEPI = gep %GEPIOp, Idx | ||||
7563 | // ... | ||||
7564 | // indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ] | ||||
7565 | // (* %GEPI is alive on the indirectbr edges due to other uses ahead) | ||||
7566 | // (* %GEPIOp is alive on the indirectbr edges only because of it's used by | ||||
7567 | // %UGEPI) | ||||
7568 | // | ||||
7569 | // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged) | ||||
7570 | // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged) | ||||
7571 | // ... | ||||
7572 | // | ||||
7573 | // DstBi: | ||||
7574 | // ... | ||||
7575 | // %UGEPI = gep %GEPIOp, UIdx | ||||
7576 | // ... | ||||
7577 | // --------------------------- | ||||
7578 | // | ||||
7579 | // ---------- AFTER ---------- | ||||
7580 | // SrcBlock: | ||||
7581 | // ... (same as above) | ||||
7582 | // (* %GEPI is still alive on the indirectbr edges) | ||||
7583 | // (* %GEPIOp is no longer alive on the indirectbr edges as a result of the | ||||
7584 | // unmerging) | ||||
7585 | // ... | ||||
7586 | // | ||||
7587 | // DstBi: | ||||
7588 | // ... | ||||
7589 | // %UGEPI = gep %GEPI, (UIdx-Idx) | ||||
7590 | // ... | ||||
7591 | // --------------------------- | ||||
7592 | // | ||||
7593 | // The register pressure on the IndirectBr edges is reduced because %GEPIOp is | ||||
7594 | // no longer alive on them. | ||||
7595 | // | ||||
7596 | // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging | ||||
7597 | // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as | ||||
7598 | // not to disable further simplications and optimizations as a result of GEP | ||||
7599 | // merging. | ||||
7600 | // | ||||
7601 | // Note this unmerging may increase the length of the data flow critical path | ||||
7602 | // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff | ||||
7603 | // between the register pressure and the length of data-flow critical | ||||
7604 | // path. Restricting this to the uncommon IndirectBr case would minimize the | ||||
7605 | // impact of potentially longer critical path, if any, and the impact on compile | ||||
7606 | // time. | ||||
7607 | static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI, | ||||
7608 | const TargetTransformInfo *TTI) { | ||||
7609 | BasicBlock *SrcBlock = GEPI->getParent(); | ||||
7610 | // Check that SrcBlock ends with an IndirectBr. If not, give up. The common | ||||
7611 | // (non-IndirectBr) cases exit early here. | ||||
7612 | if (!isa<IndirectBrInst>(SrcBlock->getTerminator())) | ||||
7613 | return false; | ||||
7614 | // Check that GEPI is a simple gep with a single constant index. | ||||
7615 | if (!GEPSequentialConstIndexed(GEPI)) | ||||
7616 | return false; | ||||
7617 | ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1)); | ||||
7618 | // Check that GEPI is a cheap one. | ||||
7619 | if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType(), | ||||
7620 | TargetTransformInfo::TCK_SizeAndLatency) | ||||
7621 | > TargetTransformInfo::TCC_Basic) | ||||
7622 | return false; | ||||
7623 | Value *GEPIOp = GEPI->getOperand(0); | ||||
7624 | // Check that GEPIOp is an instruction that's also defined in SrcBlock. | ||||
7625 | if (!isa<Instruction>(GEPIOp)) | ||||
7626 | return false; | ||||
7627 | auto *GEPIOpI = cast<Instruction>(GEPIOp); | ||||
7628 | if (GEPIOpI->getParent() != SrcBlock) | ||||
7629 | return false; | ||||
7630 | // Check that GEP is used outside the block, meaning it's alive on the | ||||
7631 | // IndirectBr edge(s). | ||||
7632 | if (find_if(GEPI->users(), [&](User *Usr) { | ||||
7633 | if (auto *I = dyn_cast<Instruction>(Usr)) { | ||||
7634 | if (I->getParent() != SrcBlock) { | ||||
7635 | return true; | ||||
7636 | } | ||||
7637 | } | ||||
7638 | return false; | ||||
7639 | }) == GEPI->users().end()) | ||||
7640 | return false; | ||||
7641 | // The second elements of the GEP chains to be unmerged. | ||||
7642 | std::vector<GetElementPtrInst *> UGEPIs; | ||||
7643 | // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive | ||||
7644 | // on IndirectBr edges. | ||||
7645 | for (User *Usr : GEPIOp->users()) { | ||||
7646 | if (Usr == GEPI) continue; | ||||
7647 | // Check if Usr is an Instruction. If not, give up. | ||||
7648 | if (!isa<Instruction>(Usr)) | ||||
7649 | return false; | ||||
7650 | auto *UI = cast<Instruction>(Usr); | ||||
7651 | // Check if Usr in the same block as GEPIOp, which is fine, skip. | ||||
7652 | if (UI->getParent() == SrcBlock) | ||||
7653 | continue; | ||||
7654 | // Check if Usr is a GEP. If not, give up. | ||||
7655 | if (!isa<GetElementPtrInst>(Usr)) | ||||
7656 | return false; | ||||
7657 | auto *UGEPI = cast<GetElementPtrInst>(Usr); | ||||
7658 | // Check if UGEPI is a simple gep with a single constant index and GEPIOp is | ||||
7659 | // the pointer operand to it. If so, record it in the vector. If not, give | ||||
7660 | // up. | ||||
7661 | if (!GEPSequentialConstIndexed(UGEPI)) | ||||
7662 | return false; | ||||
7663 | if (UGEPI->getOperand(0) != GEPIOp) | ||||
7664 | return false; | ||||
7665 | if (GEPIIdx->getType() != | ||||
7666 | cast<ConstantInt>(UGEPI->getOperand(1))->getType()) | ||||
7667 | return false; | ||||
7668 | ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); | ||||
7669 | if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType(), | ||||
7670 | TargetTransformInfo::TCK_SizeAndLatency) | ||||
7671 | > TargetTransformInfo::TCC_Basic) | ||||
7672 | return false; | ||||
7673 | UGEPIs.push_back(UGEPI); | ||||
7674 | } | ||||
7675 | if (UGEPIs.size() == 0) | ||||
7676 | return false; | ||||
7677 | // Check the materializing cost of (Uidx-Idx). | ||||
7678 | for (GetElementPtrInst *UGEPI : UGEPIs) { | ||||
7679 | ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); | ||||
7680 | APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue(); | ||||
7681 | InstructionCost ImmCost = TTI->getIntImmCost( | ||||
7682 | NewIdx, GEPIIdx->getType(), TargetTransformInfo::TCK_SizeAndLatency); | ||||
7683 | if (ImmCost > TargetTransformInfo::TCC_Basic) | ||||
7684 | return false; | ||||
7685 | } | ||||
7686 | // Now unmerge between GEPI and UGEPIs. | ||||
7687 | for (GetElementPtrInst *UGEPI : UGEPIs) { | ||||
7688 | UGEPI->setOperand(0, GEPI); | ||||
7689 | ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); | ||||
7690 | Constant *NewUGEPIIdx = | ||||
7691 | ConstantInt::get(GEPIIdx->getType(), | ||||
7692 | UGEPIIdx->getValue() - GEPIIdx->getValue()); | ||||
7693 | UGEPI->setOperand(1, NewUGEPIIdx); | ||||
7694 | // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not | ||||
7695 | // inbounds to avoid UB. | ||||
7696 | if (!GEPI->isInBounds()) { | ||||
7697 | UGEPI->setIsInBounds(false); | ||||
7698 | } | ||||
7699 | } | ||||
7700 | // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not | ||||
7701 | // alive on IndirectBr edges). | ||||
7702 | assert(find_if(GEPIOp->users(), [&](User *Usr) {(static_cast <bool> (find_if(GEPIOp->users(), [& ](User *Usr) { return cast<Instruction>(Usr)->getParent () != SrcBlock; }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock" ) ? void (0) : __assert_fail ("find_if(GEPIOp->users(), [&](User *Usr) { return cast<Instruction>(Usr)->getParent() != SrcBlock; }) == GEPIOp->users().end() && \"GEPIOp is used outside SrcBlock\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7704, __extension__ __PRETTY_FUNCTION__ )) | ||||
7703 | return cast<Instruction>(Usr)->getParent() != SrcBlock;(static_cast <bool> (find_if(GEPIOp->users(), [& ](User *Usr) { return cast<Instruction>(Usr)->getParent () != SrcBlock; }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock" ) ? void (0) : __assert_fail ("find_if(GEPIOp->users(), [&](User *Usr) { return cast<Instruction>(Usr)->getParent() != SrcBlock; }) == GEPIOp->users().end() && \"GEPIOp is used outside SrcBlock\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7704, __extension__ __PRETTY_FUNCTION__ )) | ||||
7704 | }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock")(static_cast <bool> (find_if(GEPIOp->users(), [& ](User *Usr) { return cast<Instruction>(Usr)->getParent () != SrcBlock; }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock" ) ? void (0) : __assert_fail ("find_if(GEPIOp->users(), [&](User *Usr) { return cast<Instruction>(Usr)->getParent() != SrcBlock; }) == GEPIOp->users().end() && \"GEPIOp is used outside SrcBlock\"" , "llvm/lib/CodeGen/CodeGenPrepare.cpp", 7704, __extension__ __PRETTY_FUNCTION__ )); | ||||
7705 | return true; | ||||
7706 | } | ||||
7707 | |||||
7708 | static bool optimizeBranch(BranchInst *Branch, const TargetLowering &TLI) { | ||||
7709 | // Try and convert | ||||
7710 | // %c = icmp ult %x, 8 | ||||
7711 | // br %c, bla, blb | ||||
7712 | // %tc = lshr %x, 3 | ||||
7713 | // to | ||||
7714 | // %tc = lshr %x, 3 | ||||
7715 | // %c = icmp eq %tc, 0 | ||||
7716 | // br %c, bla, blb | ||||
7717 | // Creating the cmp to zero can be better for the backend, especially if the | ||||
7718 | // lshr produces flags that can be used automatically. | ||||
7719 | if (!TLI.preferZeroCompareBranch() || !Branch->isConditional()) | ||||
7720 | return false; | ||||
7721 | |||||
7722 | ICmpInst *Cmp = dyn_cast<ICmpInst>(Branch->getCondition()); | ||||
7723 | if (!Cmp || !isa<ConstantInt>(Cmp->getOperand(1)) || !Cmp->hasOneUse()) | ||||
7724 | return false; | ||||
7725 | |||||
7726 | Value *X = Cmp->getOperand(0); | ||||
7727 | APInt CmpC = cast<ConstantInt>(Cmp->getOperand(1))->getValue(); | ||||
7728 | |||||
7729 | for (auto *U : X->users()) { | ||||
7730 | Instruction *UI = dyn_cast<Instruction>(U); | ||||
7731 | // A quick dominance check | ||||
7732 | if (!UI || | ||||
7733 | (UI->getParent() != Branch->getParent() && | ||||
7734 | UI->getParent() != Branch->getSuccessor(0) && | ||||
7735 | UI->getParent() != Branch->getSuccessor(1)) || | ||||
7736 | (UI->getParent() != Branch->getParent() && | ||||
7737 | !UI->getParent()->getSinglePredecessor())) | ||||
7738 | continue; | ||||
7739 | |||||
7740 | if (CmpC.isPowerOf2() && Cmp->getPredicate() == ICmpInst::ICMP_ULT && | ||||
7741 | match(UI, m_Shr(m_Specific(X), m_SpecificInt(CmpC.logBase2())))) { | ||||
7742 | IRBuilder<> Builder(Branch); | ||||
7743 | if (UI->getParent() != Branch->getParent()) | ||||
7744 | UI->moveBefore(Branch); | ||||
7745 | Value *NewCmp = Builder.CreateCmp(ICmpInst::ICMP_EQ, UI, | ||||
7746 | ConstantInt::get(UI->getType(), 0)); | ||||
7747 | LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Converting " << * Cmp << "\n"; } } while (false); | ||||
7748 | LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << " to compare on zero: " << *NewCmp << "\n"; } } while (false); | ||||
7749 | Cmp->replaceAllUsesWith(NewCmp); | ||||
7750 | return true; | ||||
7751 | } | ||||
7752 | if (Cmp->isEquality() && | ||||
7753 | (match(UI, m_Add(m_Specific(X), m_SpecificInt(-CmpC))) || | ||||
7754 | match(UI, m_Sub(m_Specific(X), m_SpecificInt(CmpC))))) { | ||||
7755 | IRBuilder<> Builder(Branch); | ||||
7756 | if (UI->getParent() != Branch->getParent()) | ||||
7757 | UI->moveBefore(Branch); | ||||
7758 | Value *NewCmp = Builder.CreateCmp(Cmp->getPredicate(), UI, | ||||
7759 | ConstantInt::get(UI->getType(), 0)); | ||||
7760 | LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Converting " << * Cmp << "\n"; } } while (false); | ||||
7761 | LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << " to compare on zero: " << *NewCmp << "\n"; } } while (false); | ||||
7762 | Cmp->replaceAllUsesWith(NewCmp); | ||||
7763 | return true; | ||||
7764 | } | ||||
7765 | } | ||||
7766 | return false; | ||||
7767 | } | ||||
7768 | |||||
7769 | bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) { | ||||
7770 | // Bail out if we inserted the instruction to prevent optimizations from | ||||
7771 | // stepping on each other's toes. | ||||
7772 | if (InsertedInsts.count(I)) | ||||
7773 | return false; | ||||
7774 | |||||
7775 | // TODO: Move into the switch on opcode below here. | ||||
7776 | if (PHINode *P = dyn_cast<PHINode>(I)) { | ||||
7777 | // It is possible for very late stage optimizations (such as SimplifyCFG) | ||||
7778 | // to introduce PHI nodes too late to be cleaned up. If we detect such a | ||||
7779 | // trivial PHI, go ahead and zap it here. | ||||
7780 | if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) { | ||||
7781 | LargeOffsetGEPMap.erase(P); | ||||
7782 | P->replaceAllUsesWith(V); | ||||
7783 | P->eraseFromParent(); | ||||
7784 | ++NumPHIsElim; | ||||
7785 | return true; | ||||
7786 | } | ||||
7787 | return false; | ||||
7788 | } | ||||
7789 | |||||
7790 | if (CastInst *CI = dyn_cast<CastInst>(I)) { | ||||
7791 | // If the source of the cast is a constant, then this should have | ||||
7792 | // already been constant folded. The only reason NOT to constant fold | ||||
7793 | // it is if something (e.g. LSR) was careful to place the constant | ||||
7794 | // evaluation in a block other than then one that uses it (e.g. to hoist | ||||
7795 | // the address of globals out of a loop). If this is the case, we don't | ||||
7796 | // want to forward-subst the cast. | ||||
7797 | if (isa<Constant>(CI->getOperand(0))) | ||||
7798 | return false; | ||||
7799 | |||||
7800 | if (OptimizeNoopCopyExpression(CI, *TLI, *DL)) | ||||
7801 | return true; | ||||
7802 | |||||
7803 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { | ||||
7804 | /// Sink a zext or sext into its user blocks if the target type doesn't | ||||
7805 | /// fit in one register | ||||
7806 | if (TLI->getTypeAction(CI->getContext(), | ||||
7807 | TLI->getValueType(*DL, CI->getType())) == | ||||
7808 | TargetLowering::TypeExpandInteger) { | ||||
7809 | return SinkCast(CI); | ||||
7810 | } else { | ||||
7811 | bool MadeChange = optimizeExt(I); | ||||
7812 | return MadeChange | optimizeExtUses(I); | ||||
7813 | } | ||||
7814 | } | ||||
7815 | return false; | ||||
7816 | } | ||||
7817 | |||||
7818 | if (auto *Cmp = dyn_cast<CmpInst>(I)) | ||||
7819 | if (optimizeCmp(Cmp, ModifiedDT)) | ||||
7820 | return true; | ||||
7821 | |||||
7822 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { | ||||
7823 | LI->setMetadata(LLVMContext::MD_invariant_group, nullptr); | ||||
7824 | bool Modified = optimizeLoadExt(LI); | ||||
7825 | unsigned AS = LI->getPointerAddressSpace(); | ||||
7826 | Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS); | ||||
7827 | return Modified; | ||||
7828 | } | ||||
7829 | |||||
7830 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { | ||||
7831 | if (splitMergedValStore(*SI, *DL, *TLI)) | ||||
7832 | return true; | ||||
7833 | SI->setMetadata(LLVMContext::MD_invariant_group, nullptr); | ||||
7834 | unsigned AS = SI->getPointerAddressSpace(); | ||||
7835 | return optimizeMemoryInst(I, SI->getOperand(1), | ||||
7836 | SI->getOperand(0)->getType(), AS); | ||||
7837 | } | ||||
7838 | |||||
7839 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) { | ||||
7840 | unsigned AS = RMW->getPointerAddressSpace(); | ||||
7841 | return optimizeMemoryInst(I, RMW->getPointerOperand(), | ||||
7842 | RMW->getType(), AS); | ||||
7843 | } | ||||
7844 | |||||
7845 | if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) { | ||||
7846 | unsigned AS = CmpX->getPointerAddressSpace(); | ||||
7847 | return optimizeMemoryInst(I, CmpX->getPointerOperand(), | ||||
7848 | CmpX->getCompareOperand()->getType(), AS); | ||||
7849 | } | ||||
7850 | |||||
7851 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); | ||||
7852 | |||||
7853 | if (BinOp && BinOp->getOpcode() == Instruction::And && EnableAndCmpSinking && | ||||
7854 | sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts)) | ||||
7855 | return true; | ||||
7856 | |||||
7857 | // TODO: Move this into the switch on opcode - it handles shifts already. | ||||
7858 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || | ||||
7859 | BinOp->getOpcode() == Instruction::LShr)) { | ||||
7860 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); | ||||
7861 | if (CI && TLI->hasExtractBitsInsn()) | ||||
7862 | if (OptimizeExtractBits(BinOp, CI, *TLI, *DL)) | ||||
7863 | return true; | ||||
7864 | } | ||||
7865 | |||||
7866 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { | ||||
7867 | if (GEPI->hasAllZeroIndices()) { | ||||
7868 | /// The GEP operand must be a pointer, so must its result -> BitCast | ||||
7869 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), | ||||
7870 | GEPI->getName(), GEPI); | ||||
7871 | NC->setDebugLoc(GEPI->getDebugLoc()); | ||||
7872 | GEPI->replaceAllUsesWith(NC); | ||||
7873 | GEPI->eraseFromParent(); | ||||
7874 | ++NumGEPsElim; | ||||
7875 | optimizeInst(NC, ModifiedDT); | ||||
7876 | return true; | ||||
7877 | } | ||||
7878 | if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) { | ||||
7879 | return true; | ||||
7880 | } | ||||
7881 | return false; | ||||
7882 | } | ||||
7883 | |||||
7884 | if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) { | ||||
7885 | // freeze(icmp a, const)) -> icmp (freeze a), const | ||||
7886 | // This helps generate efficient conditional jumps. | ||||
7887 | Instruction *CmpI = nullptr; | ||||
7888 | if (ICmpInst *II = dyn_cast<ICmpInst>(FI->getOperand(0))) | ||||
7889 | CmpI = II; | ||||
7890 | else if (FCmpInst *F = dyn_cast<FCmpInst>(FI->getOperand(0))) | ||||
7891 | CmpI = F->getFastMathFlags().none() ? F : nullptr; | ||||
7892 | |||||
7893 | if (CmpI && CmpI->hasOneUse()) { | ||||
7894 | auto Op0 = CmpI->getOperand(0), Op1 = CmpI->getOperand(1); | ||||
7895 | bool Const0 = isa<ConstantInt>(Op0) || isa<ConstantFP>(Op0) || | ||||
7896 | isa<ConstantPointerNull>(Op0); | ||||
7897 | bool Const1 = isa<ConstantInt>(Op1) || isa<ConstantFP>(Op1) || | ||||
7898 | isa<ConstantPointerNull>(Op1); | ||||
7899 | if (Const0 || Const1) { | ||||
7900 | if (!Const0 || !Const1) { | ||||
7901 | auto *F = new FreezeInst(Const0 ? Op1 : Op0, "", CmpI); | ||||
7902 | F->takeName(FI); | ||||
7903 | CmpI->setOperand(Const0 ? 1 : 0, F); | ||||
7904 | } | ||||
7905 | FI->replaceAllUsesWith(CmpI); | ||||
7906 | FI->eraseFromParent(); | ||||
7907 | return true; | ||||
7908 | } | ||||
7909 | } | ||||
7910 | return false; | ||||
7911 | } | ||||
7912 | |||||
7913 | if (tryToSinkFreeOperands(I)) | ||||
7914 | return true; | ||||
7915 | |||||
7916 | switch (I->getOpcode()) { | ||||
7917 | case Instruction::Shl: | ||||
7918 | case Instruction::LShr: | ||||
7919 | case Instruction::AShr: | ||||
7920 | return optimizeShiftInst(cast<BinaryOperator>(I)); | ||||
7921 | case Instruction::Call: | ||||
7922 | return optimizeCallInst(cast<CallInst>(I), ModifiedDT); | ||||
7923 | case Instruction::Select: | ||||
7924 | return optimizeSelectInst(cast<SelectInst>(I)); | ||||
7925 | case Instruction::ShuffleVector: | ||||
7926 | return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I)); | ||||
7927 | case Instruction::Switch: | ||||
7928 | return optimizeSwitchInst(cast<SwitchInst>(I)); | ||||
7929 | case Instruction::ExtractElement: | ||||
7930 | return optimizeExtractElementInst(cast<ExtractElementInst>(I)); | ||||
7931 | case Instruction::Br: | ||||
7932 | return optimizeBranch(cast<BranchInst>(I), *TLI); | ||||
7933 | } | ||||
7934 | |||||
7935 | return false; | ||||
7936 | } | ||||
7937 | |||||
7938 | /// Given an OR instruction, check to see if this is a bitreverse | ||||
7939 | /// idiom. If so, insert the new intrinsic and return true. | ||||
7940 | bool CodeGenPrepare::makeBitReverse(Instruction &I) { | ||||
7941 | if (!I.getType()->isIntegerTy() || | ||||
7942 | !TLI->isOperationLegalOrCustom(ISD::BITREVERSE, | ||||
7943 | TLI->getValueType(*DL, I.getType(), true))) | ||||
7944 | return false; | ||||
7945 | |||||
7946 | SmallVector<Instruction*, 4> Insts; | ||||
7947 | if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts)) | ||||
7948 | return false; | ||||
7949 | Instruction *LastInst = Insts.back(); | ||||
7950 | I.replaceAllUsesWith(LastInst); | ||||
7951 | RecursivelyDeleteTriviallyDeadInstructions( | ||||
7952 | &I, TLInfo, nullptr, [&](Value *V) { removeAllAssertingVHReferences(V); }); | ||||
7953 | return true; | ||||
7954 | } | ||||
7955 | |||||
7956 | // In this pass we look for GEP and cast instructions that are used | ||||
7957 | // across basic blocks and rewrite them to improve basic-block-at-a-time | ||||
7958 | // selection. | ||||
7959 | bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) { | ||||
7960 | SunkAddrs.clear(); | ||||
7961 | bool MadeChange = false; | ||||
7962 | |||||
7963 | CurInstIterator = BB.begin(); | ||||
7964 | while (CurInstIterator != BB.end()) { | ||||
7965 | MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT); | ||||
7966 | if (ModifiedDT) | ||||
7967 | return true; | ||||
7968 | } | ||||
7969 | |||||
7970 | bool MadeBitReverse = true; | ||||
7971 | while (MadeBitReverse) { | ||||
7972 | MadeBitReverse = false; | ||||
7973 | for (auto &I : reverse(BB)) { | ||||
7974 | if (makeBitReverse(I)) { | ||||
7975 | MadeBitReverse = MadeChange = true; | ||||
7976 | break; | ||||
7977 | } | ||||
7978 | } | ||||
7979 | } | ||||
7980 | MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT); | ||||
7981 | |||||
7982 | return MadeChange; | ||||
7983 | } | ||||
7984 | |||||
7985 | // Some CGP optimizations may move or alter what's computed in a block. Check | ||||
7986 | // whether a dbg.value intrinsic could be pointed at a more appropriate operand. | ||||
7987 | bool CodeGenPrepare::fixupDbgValue(Instruction *I) { | ||||
7988 | assert(isa<DbgValueInst>(I))(static_cast <bool> (isa<DbgValueInst>(I)) ? void (0) : __assert_fail ("isa<DbgValueInst>(I)", "llvm/lib/CodeGen/CodeGenPrepare.cpp" , 7988, __extension__ __PRETTY_FUNCTION__)); | ||||
7989 | DbgValueInst &DVI = *cast<DbgValueInst>(I); | ||||
7990 | |||||
7991 | // Does this dbg.value refer to a sunk address calculation? | ||||
7992 | bool AnyChange = false; | ||||
7993 | SmallDenseSet<Value *> LocationOps(DVI.location_ops().begin(), | ||||
7994 | DVI.location_ops().end()); | ||||
7995 | for (Value *Location : LocationOps) { | ||||
7996 | WeakTrackingVH SunkAddrVH = SunkAddrs[Location]; | ||||
7997 | Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr; | ||||
7998 | if (SunkAddr) { | ||||
7999 | // Point dbg.value at locally computed address, which should give the best | ||||
8000 | // opportunity to be accurately lowered. This update may change the type | ||||
8001 | // of pointer being referred to; however this makes no difference to | ||||
8002 | // debugging information, and we can't generate bitcasts that may affect | ||||
8003 | // codegen. | ||||
8004 | DVI.replaceVariableLocationOp(Location, SunkAddr); | ||||
8005 | AnyChange = true; | ||||
8006 | } | ||||
8007 | } | ||||
8008 | return AnyChange; | ||||
8009 | } | ||||
8010 | |||||
8011 | // A llvm.dbg.value may be using a value before its definition, due to | ||||
8012 | // optimizations in this pass and others. Scan for such dbg.values, and rescue | ||||
8013 | // them by moving the dbg.value to immediately after the value definition. | ||||
8014 | // FIXME: Ideally this should never be necessary, and this has the potential | ||||
8015 | // to re-order dbg.value intrinsics. | ||||
8016 | bool CodeGenPrepare::placeDbgValues(Function &F) { | ||||
8017 | bool MadeChange = false; | ||||
8018 | DominatorTree DT(F); | ||||
8019 | |||||
8020 | for (BasicBlock &BB : F) { | ||||
8021 | for (Instruction &Insn : llvm::make_early_inc_range(BB)) { | ||||
8022 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(&Insn); | ||||
8023 | if (!DVI) | ||||
8024 | continue; | ||||
8025 | |||||
8026 | SmallVector<Instruction *, 4> VIs; | ||||
8027 | for (Value *V : DVI->getValues()) | ||||
8028 | if (Instruction *VI = dyn_cast_or_null<Instruction>(V)) | ||||
8029 | VIs.push_back(VI); | ||||
8030 | |||||
8031 | // This DVI may depend on multiple instructions, complicating any | ||||
8032 | // potential sink. This block takes the defensive approach, opting to | ||||
8033 | // "undef" the DVI if it has more than one instruction and any of them do | ||||
8034 | // not dominate DVI. | ||||
8035 | for (Instruction *VI : VIs) { | ||||
8036 | if (VI->isTerminator()) | ||||
8037 | continue; | ||||
8038 | |||||
8039 | // If VI is a phi in a block with an EHPad terminator, we can't insert | ||||
8040 | // after it. | ||||
8041 | if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad()) | ||||
8042 | continue; | ||||
8043 | |||||
8044 | // If the defining instruction dominates the dbg.value, we do not need | ||||
8045 | // to move the dbg.value. | ||||
8046 | if (DT.dominates(VI, DVI)) | ||||
8047 | continue; | ||||
8048 | |||||
8049 | // If we depend on multiple instructions and any of them doesn't | ||||
8050 | // dominate this DVI, we probably can't salvage it: moving it to | ||||
8051 | // after any of the instructions could cause us to lose the others. | ||||
8052 | if (VIs.size() > 1) { | ||||
8053 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Unable to find valid location for Debug Value, undefing:\n" << *DVI; } } while (false) | ||||
8054 | dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Unable to find valid location for Debug Value, undefing:\n" << *DVI; } } while (false) | ||||
8055 | << "Unable to find valid location for Debug Value, undefing:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Unable to find valid location for Debug Value, undefing:\n" << *DVI; } } while (false) | ||||
8056 | << *DVI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Unable to find valid location for Debug Value, undefing:\n" << *DVI; } } while (false); | ||||
8057 | DVI->setUndef(); | ||||
8058 | break; | ||||
8059 | } | ||||
8060 | |||||
8061 | LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI; } } while (false) | ||||
8062 | << *DVI << ' ' << *VI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI; } } while (false); | ||||
8063 | DVI->removeFromParent(); | ||||
8064 | if (isa<PHINode>(VI)) | ||||
8065 | DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt()); | ||||
8066 | else | ||||
8067 | DVI->insertAfter(VI); | ||||
8068 | MadeChange = true; | ||||
8069 | ++NumDbgValueMoved; | ||||
8070 | } | ||||
8071 | } | ||||
8072 | } | ||||
8073 | return MadeChange; | ||||
8074 | } | ||||
8075 | |||||
8076 | // Group scattered pseudo probes in a block to favor SelectionDAG. Scattered | ||||
8077 | // probes can be chained dependencies of other regular DAG nodes and block DAG | ||||
8078 | // combine optimizations. | ||||
8079 | bool CodeGenPrepare::placePseudoProbes(Function &F) { | ||||
8080 | bool MadeChange = false; | ||||
8081 | for (auto &Block : F) { | ||||
8082 | // Move the rest probes to the beginning of the block. | ||||
8083 | auto FirstInst = Block.getFirstInsertionPt(); | ||||
8084 | while (FirstInst != Block.end() && FirstInst->isDebugOrPseudoInst()) | ||||
8085 | ++FirstInst; | ||||
8086 | BasicBlock::iterator I(FirstInst); | ||||
8087 | I++; | ||||
8088 | while (I != Block.end()) { | ||||
8089 | if (auto *II = dyn_cast<PseudoProbeInst>(I++)) { | ||||
8090 | II->moveBefore(&*FirstInst); | ||||
8091 | MadeChange = true; | ||||
8092 | } | ||||
8093 | } | ||||
8094 | } | ||||
8095 | return MadeChange; | ||||
8096 | } | ||||
8097 | |||||
8098 | /// Scale down both weights to fit into uint32_t. | ||||
8099 | static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { | ||||
8100 | uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; | ||||
8101 | uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1; | ||||
8102 | NewTrue = NewTrue / Scale; | ||||
8103 | NewFalse = NewFalse / Scale; | ||||
8104 | } | ||||
8105 | |||||
8106 | /// Some targets prefer to split a conditional branch like: | ||||
8107 | /// \code | ||||
8108 | /// %0 = icmp ne i32 %a, 0 | ||||
8109 | /// %1 = icmp ne i32 %b, 0 | ||||
8110 | /// %or.cond = or i1 %0, %1 | ||||
8111 | /// br i1 %or.cond, label %TrueBB, label %FalseBB | ||||
8112 | /// \endcode | ||||
8113 | /// into multiple branch instructions like: | ||||
8114 | /// \code | ||||
8115 | /// bb1: | ||||
8116 | /// %0 = icmp ne i32 %a, 0 | ||||
8117 | /// br i1 %0, label %TrueBB, label %bb2 | ||||
8118 | /// bb2: | ||||
8119 | /// %1 = icmp ne i32 %b, 0 | ||||
8120 | /// br i1 %1, label %TrueBB, label %FalseBB | ||||
8121 | /// \endcode | ||||
8122 | /// This usually allows instruction selection to do even further optimizations | ||||
8123 | /// and combine the compare with the branch instruction. Currently this is | ||||
8124 | /// applied for targets which have "cheap" jump instructions. | ||||
8125 | /// | ||||
8126 | /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. | ||||
8127 | /// | ||||
8128 | bool CodeGenPrepare::splitBranchCondition(Function &F, bool &ModifiedDT) { | ||||
8129 | if (!TM->Options.EnableFastISel || TLI->isJumpExpensive()) | ||||
8130 | return false; | ||||
8131 | |||||
8132 | bool MadeChange = false; | ||||
8133 | for (auto &BB : F) { | ||||
8134 | // Does this BB end with the following? | ||||
8135 | // %cond1 = icmp|fcmp|binary instruction ... | ||||
8136 | // %cond2 = icmp|fcmp|binary instruction ... | ||||
8137 | // %cond.or = or|and i1 %cond1, cond2 | ||||
8138 | // br i1 %cond.or label %dest1, label %dest2" | ||||
8139 | Instruction *LogicOp; | ||||
8140 | BasicBlock *TBB, *FBB; | ||||
8141 | if (!match(BB.getTerminator(), | ||||
8142 | m_Br(m_OneUse(m_Instruction(LogicOp)), TBB, FBB))) | ||||
8143 | continue; | ||||
8144 | |||||
8145 | auto *Br1 = cast<BranchInst>(BB.getTerminator()); | ||||
8146 | if (Br1->getMetadata(LLVMContext::MD_unpredictable)) | ||||
8147 | continue; | ||||
8148 | |||||
8149 | // The merging of mostly empty BB can cause a degenerate branch. | ||||
8150 | if (TBB == FBB) | ||||
8151 | continue; | ||||
8152 | |||||
8153 | unsigned Opc; | ||||
8154 | Value *Cond1, *Cond2; | ||||
8155 | if (match(LogicOp, | ||||
8156 | m_LogicalAnd(m_OneUse(m_Value(Cond1)), m_OneUse(m_Value(Cond2))))) | ||||
8157 | Opc = Instruction::And; | ||||
8158 | else if (match(LogicOp, m_LogicalOr(m_OneUse(m_Value(Cond1)), | ||||
8159 | m_OneUse(m_Value(Cond2))))) | ||||
8160 | Opc = Instruction::Or; | ||||
8161 | else | ||||
8162 | continue; | ||||
8163 | |||||
8164 | auto IsGoodCond = [](Value *Cond) { | ||||
8165 | return match( | ||||
8166 | Cond, | ||||
8167 | m_CombineOr(m_Cmp(), m_CombineOr(m_LogicalAnd(m_Value(), m_Value()), | ||||
8168 | m_LogicalOr(m_Value(), m_Value())))); | ||||
8169 | }; | ||||
8170 | if (!IsGoodCond(Cond1) || !IsGoodCond(Cond2)) | ||||
8171 | continue; | ||||
8172 | |||||
8173 | LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "Before branch condition splitting\n" ; BB.dump(); } } while (false); | ||||
8174 | |||||
8175 | // Create a new BB. | ||||
8176 | auto *TmpBB = | ||||
8177 | BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split", | ||||
8178 | BB.getParent(), BB.getNextNode()); | ||||
8179 | |||||
8180 | // Update original basic block by using the first condition directly by the | ||||
8181 | // branch instruction and removing the no longer needed and/or instruction. | ||||
8182 | Br1->setCondition(Cond1); | ||||
8183 | LogicOp->eraseFromParent(); | ||||
8184 | |||||
8185 | // Depending on the condition we have to either replace the true or the | ||||
8186 | // false successor of the original branch instruction. | ||||
8187 | if (Opc == Instruction::And) | ||||
8188 | Br1->setSuccessor(0, TmpBB); | ||||
8189 | else | ||||
8190 | Br1->setSuccessor(1, TmpBB); | ||||
8191 | |||||
8192 | // Fill in the new basic block. | ||||
8193 | auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); | ||||
8194 | if (auto *I = dyn_cast<Instruction>(Cond2)) { | ||||
8195 | I->removeFromParent(); | ||||
8196 | I->insertBefore(Br2); | ||||
8197 | } | ||||
8198 | |||||
8199 | // Update PHI nodes in both successors. The original BB needs to be | ||||
8200 | // replaced in one successor's PHI nodes, because the branch comes now from | ||||
8201 | // the newly generated BB (NewBB). In the other successor we need to add one | ||||
8202 | // incoming edge to the PHI nodes, because both branch instructions target | ||||
8203 | // now the same successor. Depending on the original branch condition | ||||
8204 | // (and/or) we have to swap the successors (TrueDest, FalseDest), so that | ||||
8205 | // we perform the correct update for the PHI nodes. | ||||
8206 | // This doesn't change the successor order of the just created branch | ||||
8207 | // instruction (or any other instruction). | ||||
8208 | if (Opc == Instruction::Or) | ||||
8209 | std::swap(TBB, FBB); | ||||
8210 | |||||
8211 | // Replace the old BB with the new BB. | ||||
8212 | TBB->replacePhiUsesWith(&BB, TmpBB); | ||||
8213 | |||||
8214 | // Add another incoming edge form the new BB. | ||||
8215 | for (PHINode &PN : FBB->phis()) { | ||||
8216 | auto *Val = PN.getIncomingValueForBlock(&BB); | ||||
8217 | PN.addIncoming(Val, TmpBB); | ||||
8218 | } | ||||
8219 | |||||
8220 | // Update the branch weights (from SelectionDAGBuilder:: | ||||
8221 | // FindMergedConditions). | ||||
8222 | if (Opc == Instruction::Or) { | ||||
8223 | // Codegen X | Y as: | ||||
8224 | // BB1: | ||||
8225 | // jmp_if_X TBB | ||||
8226 | // jmp TmpBB | ||||
8227 | // TmpBB: | ||||
8228 | // jmp_if_Y TBB | ||||
8229 | // jmp FBB | ||||
8230 | // | ||||
8231 | |||||
8232 | // We have flexibility in setting Prob for BB1 and Prob for NewBB. | ||||
8233 | // The requirement is that | ||||
8234 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) | ||||
8235 | // = TrueProb for original BB. | ||||
8236 | // Assuming the original weights are A and B, one choice is to set BB1's | ||||
8237 | // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice | ||||
8238 | // assumes that | ||||
8239 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. | ||||
8240 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for | ||||
8241 | // TmpBB, but the math is more complicated. | ||||
8242 | uint64_t TrueWeight, FalseWeight; | ||||
8243 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { | ||||
8244 | uint64_t NewTrueWeight = TrueWeight; | ||||
8245 | uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; | ||||
8246 | scaleWeights(NewTrueWeight, NewFalseWeight); | ||||
8247 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) | ||||
8248 | .createBranchWeights(TrueWeight, FalseWeight)); | ||||
8249 | |||||
8250 | NewTrueWeight = TrueWeight; | ||||
8251 | NewFalseWeight = 2 * FalseWeight; | ||||
8252 | scaleWeights(NewTrueWeight, NewFalseWeight); | ||||
8253 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) | ||||
8254 | .createBranchWeights(TrueWeight, FalseWeight)); | ||||
8255 | } | ||||
8256 | } else { | ||||
8257 | // Codegen X & Y as: | ||||
8258 | // BB1: | ||||
8259 | // jmp_if_X TmpBB | ||||
8260 | // jmp FBB | ||||
8261 | // TmpBB: | ||||
8262 | // jmp_if_Y TBB | ||||
8263 | // jmp FBB | ||||
8264 | // | ||||
8265 | // This requires creation of TmpBB after CurBB. | ||||
8266 | |||||
8267 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. | ||||
8268 | // The requirement is that | ||||
8269 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) | ||||
8270 | // = FalseProb for original BB. | ||||
8271 | // Assuming the original weights are A and B, one choice is to set BB1's | ||||
8272 | // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice | ||||
8273 | // assumes that | ||||
8274 | // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. | ||||
8275 | uint64_t TrueWeight, FalseWeight; | ||||
8276 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { | ||||
8277 | uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; | ||||
8278 | uint64_t NewFalseWeight = FalseWeight; | ||||
8279 | scaleWeights(NewTrueWeight, NewFalseWeight); | ||||
8280 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) | ||||
8281 | .createBranchWeights(TrueWeight, FalseWeight)); | ||||
8282 | |||||
8283 | NewTrueWeight = 2 * TrueWeight; | ||||
8284 | NewFalseWeight = FalseWeight; | ||||
8285 | scaleWeights(NewTrueWeight, NewFalseWeight); | ||||
8286 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) | ||||
8287 | .createBranchWeights(TrueWeight, FalseWeight)); | ||||
8288 | } | ||||
8289 | } | ||||
8290 | |||||
8291 | ModifiedDT = true; | ||||
8292 | MadeChange = true; | ||||
8293 | |||||
8294 | LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "After branch condition splitting\n" ; BB.dump(); TmpBB->dump(); } } while (false) | ||||
8295 | TmpBB->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("codegenprepare")) { dbgs() << "After branch condition splitting\n" ; BB.dump(); TmpBB->dump(); } } while (false); | ||||
8296 | } | ||||
8297 | return MadeChange; | ||||
8298 | } |
1 | //===- llvm/Instructions.h - Instruction subclass definitions ---*- 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 | // This file exposes the class definitions of all of the subclasses of the |
10 | // Instruction class. This is meant to be an easy way to get access to all |
11 | // instruction subclasses. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_IR_INSTRUCTIONS_H |
16 | #define LLVM_IR_INSTRUCTIONS_H |
17 | |
18 | #include "llvm/ADT/ArrayRef.h" |
19 | #include "llvm/ADT/Bitfields.h" |
20 | #include "llvm/ADT/MapVector.h" |
21 | #include "llvm/ADT/None.h" |
22 | #include "llvm/ADT/STLExtras.h" |
23 | #include "llvm/ADT/SmallVector.h" |
24 | #include "llvm/ADT/Twine.h" |
25 | #include "llvm/ADT/iterator.h" |
26 | #include "llvm/ADT/iterator_range.h" |
27 | #include "llvm/IR/CFG.h" |
28 | #include "llvm/IR/Constant.h" |
29 | #include "llvm/IR/DerivedTypes.h" |
30 | #include "llvm/IR/InstrTypes.h" |
31 | #include "llvm/IR/Instruction.h" |
32 | #include "llvm/IR/OperandTraits.h" |
33 | #include "llvm/IR/Use.h" |
34 | #include "llvm/IR/User.h" |
35 | #include "llvm/Support/AtomicOrdering.h" |
36 | #include "llvm/Support/ErrorHandling.h" |
37 | #include <cassert> |
38 | #include <cstddef> |
39 | #include <cstdint> |
40 | #include <iterator> |
41 | |
42 | namespace llvm { |
43 | |
44 | class APFloat; |
45 | class APInt; |
46 | class BasicBlock; |
47 | class ConstantInt; |
48 | class DataLayout; |
49 | class StringRef; |
50 | class Type; |
51 | class Value; |
52 | |
53 | //===----------------------------------------------------------------------===// |
54 | // AllocaInst Class |
55 | //===----------------------------------------------------------------------===// |
56 | |
57 | /// an instruction to allocate memory on the stack |
58 | class AllocaInst : public UnaryInstruction { |
59 | Type *AllocatedType; |
60 | |
61 | using AlignmentField = AlignmentBitfieldElementT<0>; |
62 | using UsedWithInAllocaField = BoolBitfieldElementT<AlignmentField::NextBit>; |
63 | using SwiftErrorField = BoolBitfieldElementT<UsedWithInAllocaField::NextBit>; |
64 | static_assert(Bitfield::areContiguous<AlignmentField, UsedWithInAllocaField, |
65 | SwiftErrorField>(), |
66 | "Bitfields must be contiguous"); |
67 | |
68 | protected: |
69 | // Note: Instruction needs to be a friend here to call cloneImpl. |
70 | friend class Instruction; |
71 | |
72 | AllocaInst *cloneImpl() const; |
73 | |
74 | public: |
75 | explicit AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
76 | const Twine &Name, Instruction *InsertBefore); |
77 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
78 | const Twine &Name, BasicBlock *InsertAtEnd); |
79 | |
80 | AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, |
81 | Instruction *InsertBefore); |
82 | AllocaInst(Type *Ty, unsigned AddrSpace, |
83 | const Twine &Name, BasicBlock *InsertAtEnd); |
84 | |
85 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align, |
86 | const Twine &Name = "", Instruction *InsertBefore = nullptr); |
87 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align, |
88 | const Twine &Name, BasicBlock *InsertAtEnd); |
89 | |
90 | /// Return true if there is an allocation size parameter to the allocation |
91 | /// instruction that is not 1. |
92 | bool isArrayAllocation() const; |
93 | |
94 | /// Get the number of elements allocated. For a simple allocation of a single |
95 | /// element, this will return a constant 1 value. |
96 | const Value *getArraySize() const { return getOperand(0); } |
97 | Value *getArraySize() { return getOperand(0); } |
98 | |
99 | /// Overload to return most specific pointer type. |
100 | PointerType *getType() const { |
101 | return cast<PointerType>(Instruction::getType()); |
102 | } |
103 | |
104 | /// Return the address space for the allocation. |
105 | unsigned getAddressSpace() const { |
106 | return getType()->getAddressSpace(); |
107 | } |
108 | |
109 | /// Get allocation size in bits. Returns None if size can't be determined, |
110 | /// e.g. in case of a VLA. |
111 | Optional<TypeSize> getAllocationSizeInBits(const DataLayout &DL) const; |
112 | |
113 | /// Return the type that is being allocated by the instruction. |
114 | Type *getAllocatedType() const { return AllocatedType; } |
115 | /// for use only in special circumstances that need to generically |
116 | /// transform a whole instruction (eg: IR linking and vectorization). |
117 | void setAllocatedType(Type *Ty) { AllocatedType = Ty; } |
118 | |
119 | /// Return the alignment of the memory that is being allocated by the |
120 | /// instruction. |
121 | Align getAlign() const { |
122 | return Align(1ULL << getSubclassData<AlignmentField>()); |
123 | } |
124 | |
125 | void setAlignment(Align Align) { |
126 | setSubclassData<AlignmentField>(Log2(Align)); |
127 | } |
128 | |
129 | // FIXME: Remove this one transition to Align is over. |
130 | uint64_t getAlignment() const { return getAlign().value(); } |
131 | |
132 | /// Return true if this alloca is in the entry block of the function and is a |
133 | /// constant size. If so, the code generator will fold it into the |
134 | /// prolog/epilog code, so it is basically free. |
135 | bool isStaticAlloca() const; |
136 | |
137 | /// Return true if this alloca is used as an inalloca argument to a call. Such |
138 | /// allocas are never considered static even if they are in the entry block. |
139 | bool isUsedWithInAlloca() const { |
140 | return getSubclassData<UsedWithInAllocaField>(); |
141 | } |
142 | |
143 | /// Specify whether this alloca is used to represent the arguments to a call. |
144 | void setUsedWithInAlloca(bool V) { |
145 | setSubclassData<UsedWithInAllocaField>(V); |
146 | } |
147 | |
148 | /// Return true if this alloca is used as a swifterror argument to a call. |
149 | bool isSwiftError() const { return getSubclassData<SwiftErrorField>(); } |
150 | /// Specify whether this alloca is used to represent a swifterror. |
151 | void setSwiftError(bool V) { setSubclassData<SwiftErrorField>(V); } |
152 | |
153 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
154 | static bool classof(const Instruction *I) { |
155 | return (I->getOpcode() == Instruction::Alloca); |
156 | } |
157 | static bool classof(const Value *V) { |
158 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
159 | } |
160 | |
161 | private: |
162 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
163 | // method so that subclasses cannot accidentally use it. |
164 | template <typename Bitfield> |
165 | void setSubclassData(typename Bitfield::Type Value) { |
166 | Instruction::setSubclassData<Bitfield>(Value); |
167 | } |
168 | }; |
169 | |
170 | //===----------------------------------------------------------------------===// |
171 | // LoadInst Class |
172 | //===----------------------------------------------------------------------===// |
173 | |
174 | /// An instruction for reading from memory. This uses the SubclassData field in |
175 | /// Value to store whether or not the load is volatile. |
176 | class LoadInst : public UnaryInstruction { |
177 | using VolatileField = BoolBitfieldElementT<0>; |
178 | using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>; |
179 | using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>; |
180 | static_assert( |
181 | Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(), |
182 | "Bitfields must be contiguous"); |
183 | |
184 | void AssertOK(); |
185 | |
186 | protected: |
187 | // Note: Instruction needs to be a friend here to call cloneImpl. |
188 | friend class Instruction; |
189 | |
190 | LoadInst *cloneImpl() const; |
191 | |
192 | public: |
193 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, |
194 | Instruction *InsertBefore); |
195 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd); |
196 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
197 | Instruction *InsertBefore); |
198 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
199 | BasicBlock *InsertAtEnd); |
200 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
201 | Align Align, Instruction *InsertBefore = nullptr); |
202 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
203 | Align Align, BasicBlock *InsertAtEnd); |
204 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
205 | Align Align, AtomicOrdering Order, |
206 | SyncScope::ID SSID = SyncScope::System, |
207 | Instruction *InsertBefore = nullptr); |
208 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
209 | Align Align, AtomicOrdering Order, SyncScope::ID SSID, |
210 | BasicBlock *InsertAtEnd); |
211 | |
212 | /// Return true if this is a load from a volatile memory location. |
213 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
214 | |
215 | /// Specify whether this is a volatile load or not. |
216 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
217 | |
218 | /// Return the alignment of the access that is being performed. |
219 | /// FIXME: Remove this function once transition to Align is over. |
220 | /// Use getAlign() instead. |
221 | uint64_t getAlignment() const { return getAlign().value(); } |
222 | |
223 | /// Return the alignment of the access that is being performed. |
224 | Align getAlign() const { |
225 | return Align(1ULL << (getSubclassData<AlignmentField>())); |
226 | } |
227 | |
228 | void setAlignment(Align Align) { |
229 | setSubclassData<AlignmentField>(Log2(Align)); |
230 | } |
231 | |
232 | /// Returns the ordering constraint of this load instruction. |
233 | AtomicOrdering getOrdering() const { |
234 | return getSubclassData<OrderingField>(); |
235 | } |
236 | /// Sets the ordering constraint of this load instruction. May not be Release |
237 | /// or AcquireRelease. |
238 | void setOrdering(AtomicOrdering Ordering) { |
239 | setSubclassData<OrderingField>(Ordering); |
240 | } |
241 | |
242 | /// Returns the synchronization scope ID of this load instruction. |
243 | SyncScope::ID getSyncScopeID() const { |
244 | return SSID; |
245 | } |
246 | |
247 | /// Sets the synchronization scope ID of this load instruction. |
248 | void setSyncScopeID(SyncScope::ID SSID) { |
249 | this->SSID = SSID; |
250 | } |
251 | |
252 | /// Sets the ordering constraint and the synchronization scope ID of this load |
253 | /// instruction. |
254 | void setAtomic(AtomicOrdering Ordering, |
255 | SyncScope::ID SSID = SyncScope::System) { |
256 | setOrdering(Ordering); |
257 | setSyncScopeID(SSID); |
258 | } |
259 | |
260 | bool isSimple() const { return !isAtomic() && !isVolatile(); } |
261 | |
262 | bool isUnordered() const { |
263 | return (getOrdering() == AtomicOrdering::NotAtomic || |
264 | getOrdering() == AtomicOrdering::Unordered) && |
265 | !isVolatile(); |
266 | } |
267 | |
268 | Value *getPointerOperand() { return getOperand(0); } |
269 | const Value *getPointerOperand() const { return getOperand(0); } |
270 | static unsigned getPointerOperandIndex() { return 0U; } |
271 | Type *getPointerOperandType() const { return getPointerOperand()->getType(); } |
272 | |
273 | /// Returns the address space of the pointer operand. |
274 | unsigned getPointerAddressSpace() const { |
275 | return getPointerOperandType()->getPointerAddressSpace(); |
276 | } |
277 | |
278 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
279 | static bool classof(const Instruction *I) { |
280 | return I->getOpcode() == Instruction::Load; |
281 | } |
282 | static bool classof(const Value *V) { |
283 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
284 | } |
285 | |
286 | private: |
287 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
288 | // method so that subclasses cannot accidentally use it. |
289 | template <typename Bitfield> |
290 | void setSubclassData(typename Bitfield::Type Value) { |
291 | Instruction::setSubclassData<Bitfield>(Value); |
292 | } |
293 | |
294 | /// The synchronization scope ID of this load instruction. Not quite enough |
295 | /// room in SubClassData for everything, so synchronization scope ID gets its |
296 | /// own field. |
297 | SyncScope::ID SSID; |
298 | }; |
299 | |
300 | //===----------------------------------------------------------------------===// |
301 | // StoreInst Class |
302 | //===----------------------------------------------------------------------===// |
303 | |
304 | /// An instruction for storing to memory. |
305 | class StoreInst : public Instruction { |
306 | using VolatileField = BoolBitfieldElementT<0>; |
307 | using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>; |
308 | using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>; |
309 | static_assert( |
310 | Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(), |
311 | "Bitfields must be contiguous"); |
312 | |
313 | void AssertOK(); |
314 | |
315 | protected: |
316 | // Note: Instruction needs to be a friend here to call cloneImpl. |
317 | friend class Instruction; |
318 | |
319 | StoreInst *cloneImpl() const; |
320 | |
321 | public: |
322 | StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore); |
323 | StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd); |
324 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Instruction *InsertBefore); |
325 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd); |
326 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
327 | Instruction *InsertBefore = nullptr); |
328 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
329 | BasicBlock *InsertAtEnd); |
330 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
331 | AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System, |
332 | Instruction *InsertBefore = nullptr); |
333 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
334 | AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd); |
335 | |
336 | // allocate space for exactly two operands |
337 | void *operator new(size_t S) { return User::operator new(S, 2); } |
338 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
339 | |
340 | /// Return true if this is a store to a volatile memory location. |
341 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
342 | |
343 | /// Specify whether this is a volatile store or not. |
344 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
345 | |
346 | /// Transparently provide more efficient getOperand methods. |
347 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
348 | |
349 | /// Return the alignment of the access that is being performed |
350 | /// FIXME: Remove this function once transition to Align is over. |
351 | /// Use getAlign() instead. |
352 | uint64_t getAlignment() const { return getAlign().value(); } |
353 | |
354 | Align getAlign() const { |
355 | return Align(1ULL << (getSubclassData<AlignmentField>())); |
356 | } |
357 | |
358 | void setAlignment(Align Align) { |
359 | setSubclassData<AlignmentField>(Log2(Align)); |
360 | } |
361 | |
362 | /// Returns the ordering constraint of this store instruction. |
363 | AtomicOrdering getOrdering() const { |
364 | return getSubclassData<OrderingField>(); |
365 | } |
366 | |
367 | /// Sets the ordering constraint of this store instruction. May not be |
368 | /// Acquire or AcquireRelease. |
369 | void setOrdering(AtomicOrdering Ordering) { |
370 | setSubclassData<OrderingField>(Ordering); |
371 | } |
372 | |
373 | /// Returns the synchronization scope ID of this store instruction. |
374 | SyncScope::ID getSyncScopeID() const { |
375 | return SSID; |
376 | } |
377 | |
378 | /// Sets the synchronization scope ID of this store instruction. |
379 | void setSyncScopeID(SyncScope::ID SSID) { |
380 | this->SSID = SSID; |
381 | } |
382 | |
383 | /// Sets the ordering constraint and the synchronization scope ID of this |
384 | /// store instruction. |
385 | void setAtomic(AtomicOrdering Ordering, |
386 | SyncScope::ID SSID = SyncScope::System) { |
387 | setOrdering(Ordering); |
388 | setSyncScopeID(SSID); |
389 | } |
390 | |
391 | bool isSimple() const { return !isAtomic() && !isVolatile(); } |
392 | |
393 | bool isUnordered() const { |
394 | return (getOrdering() == AtomicOrdering::NotAtomic || |
395 | getOrdering() == AtomicOrdering::Unordered) && |
396 | !isVolatile(); |
397 | } |
398 | |
399 | Value *getValueOperand() { return getOperand(0); } |
400 | const Value *getValueOperand() const { return getOperand(0); } |
401 | |
402 | Value *getPointerOperand() { return getOperand(1); } |
403 | const Value *getPointerOperand() const { return getOperand(1); } |
404 | static unsigned getPointerOperandIndex() { return 1U; } |
405 | Type *getPointerOperandType() const { return getPointerOperand()->getType(); } |
406 | |
407 | /// Returns the address space of the pointer operand. |
408 | unsigned getPointerAddressSpace() const { |
409 | return getPointerOperandType()->getPointerAddressSpace(); |
410 | } |
411 | |
412 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
413 | static bool classof(const Instruction *I) { |
414 | return I->getOpcode() == Instruction::Store; |
415 | } |
416 | static bool classof(const Value *V) { |
417 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
418 | } |
419 | |
420 | private: |
421 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
422 | // method so that subclasses cannot accidentally use it. |
423 | template <typename Bitfield> |
424 | void setSubclassData(typename Bitfield::Type Value) { |
425 | Instruction::setSubclassData<Bitfield>(Value); |
426 | } |
427 | |
428 | /// The synchronization scope ID of this store instruction. Not quite enough |
429 | /// room in SubClassData for everything, so synchronization scope ID gets its |
430 | /// own field. |
431 | SyncScope::ID SSID; |
432 | }; |
433 | |
434 | template <> |
435 | struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> { |
436 | }; |
437 | |
438 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)StoreInst::op_iterator StoreInst::op_begin() { return OperandTraits <StoreInst>::op_begin(this); } StoreInst::const_op_iterator StoreInst::op_begin() const { return OperandTraits<StoreInst >::op_begin(const_cast<StoreInst*>(this)); } StoreInst ::op_iterator StoreInst::op_end() { return OperandTraits<StoreInst >::op_end(this); } StoreInst::const_op_iterator StoreInst:: op_end() const { return OperandTraits<StoreInst>::op_end (const_cast<StoreInst*>(this)); } Value *StoreInst::getOperand (unsigned i_nocapture) const { (static_cast <bool> (i_nocapture < OperandTraits<StoreInst>::operands(this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 438, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<StoreInst >::op_begin(const_cast<StoreInst*>(this))[i_nocapture ].get()); } void StoreInst::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<StoreInst>::operands(this) && "setOperand() out of range!" ) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 438, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<StoreInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned StoreInst::getNumOperands() const { return OperandTraits<StoreInst>::operands(this); } template <int Idx_nocapture> Use &StoreInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &StoreInst::Op() const { return this->OpFrom <Idx_nocapture>(this); } |
439 | |
440 | //===----------------------------------------------------------------------===// |
441 | // FenceInst Class |
442 | //===----------------------------------------------------------------------===// |
443 | |
444 | /// An instruction for ordering other memory operations. |
445 | class FenceInst : public Instruction { |
446 | using OrderingField = AtomicOrderingBitfieldElementT<0>; |
447 | |
448 | void Init(AtomicOrdering Ordering, SyncScope::ID SSID); |
449 | |
450 | protected: |
451 | // Note: Instruction needs to be a friend here to call cloneImpl. |
452 | friend class Instruction; |
453 | |
454 | FenceInst *cloneImpl() const; |
455 | |
456 | public: |
457 | // Ordering may only be Acquire, Release, AcquireRelease, or |
458 | // SequentiallyConsistent. |
459 | FenceInst(LLVMContext &C, AtomicOrdering Ordering, |
460 | SyncScope::ID SSID = SyncScope::System, |
461 | Instruction *InsertBefore = nullptr); |
462 | FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID, |
463 | BasicBlock *InsertAtEnd); |
464 | |
465 | // allocate space for exactly zero operands |
466 | void *operator new(size_t S) { return User::operator new(S, 0); } |
467 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
468 | |
469 | /// Returns the ordering constraint of this fence instruction. |
470 | AtomicOrdering getOrdering() const { |
471 | return getSubclassData<OrderingField>(); |
472 | } |
473 | |
474 | /// Sets the ordering constraint of this fence instruction. May only be |
475 | /// Acquire, Release, AcquireRelease, or SequentiallyConsistent. |
476 | void setOrdering(AtomicOrdering Ordering) { |
477 | setSubclassData<OrderingField>(Ordering); |
478 | } |
479 | |
480 | /// Returns the synchronization scope ID of this fence instruction. |
481 | SyncScope::ID getSyncScopeID() const { |
482 | return SSID; |
483 | } |
484 | |
485 | /// Sets the synchronization scope ID of this fence instruction. |
486 | void setSyncScopeID(SyncScope::ID SSID) { |
487 | this->SSID = SSID; |
488 | } |
489 | |
490 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
491 | static bool classof(const Instruction *I) { |
492 | return I->getOpcode() == Instruction::Fence; |
493 | } |
494 | static bool classof(const Value *V) { |
495 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
496 | } |
497 | |
498 | private: |
499 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
500 | // method so that subclasses cannot accidentally use it. |
501 | template <typename Bitfield> |
502 | void setSubclassData(typename Bitfield::Type Value) { |
503 | Instruction::setSubclassData<Bitfield>(Value); |
504 | } |
505 | |
506 | /// The synchronization scope ID of this fence instruction. Not quite enough |
507 | /// room in SubClassData for everything, so synchronization scope ID gets its |
508 | /// own field. |
509 | SyncScope::ID SSID; |
510 | }; |
511 | |
512 | //===----------------------------------------------------------------------===// |
513 | // AtomicCmpXchgInst Class |
514 | //===----------------------------------------------------------------------===// |
515 | |
516 | /// An instruction that atomically checks whether a |
517 | /// specified value is in a memory location, and, if it is, stores a new value |
518 | /// there. The value returned by this instruction is a pair containing the |
519 | /// original value as first element, and an i1 indicating success (true) or |
520 | /// failure (false) as second element. |
521 | /// |
522 | class AtomicCmpXchgInst : public Instruction { |
523 | void Init(Value *Ptr, Value *Cmp, Value *NewVal, Align Align, |
524 | AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, |
525 | SyncScope::ID SSID); |
526 | |
527 | template <unsigned Offset> |
528 | using AtomicOrderingBitfieldElement = |
529 | typename Bitfield::Element<AtomicOrdering, Offset, 3, |
530 | AtomicOrdering::LAST>; |
531 | |
532 | protected: |
533 | // Note: Instruction needs to be a friend here to call cloneImpl. |
534 | friend class Instruction; |
535 | |
536 | AtomicCmpXchgInst *cloneImpl() const; |
537 | |
538 | public: |
539 | AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment, |
540 | AtomicOrdering SuccessOrdering, |
541 | AtomicOrdering FailureOrdering, SyncScope::ID SSID, |
542 | Instruction *InsertBefore = nullptr); |
543 | AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment, |
544 | AtomicOrdering SuccessOrdering, |
545 | AtomicOrdering FailureOrdering, SyncScope::ID SSID, |
546 | BasicBlock *InsertAtEnd); |
547 | |
548 | // allocate space for exactly three operands |
549 | void *operator new(size_t S) { return User::operator new(S, 3); } |
550 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
551 | |
552 | using VolatileField = BoolBitfieldElementT<0>; |
553 | using WeakField = BoolBitfieldElementT<VolatileField::NextBit>; |
554 | using SuccessOrderingField = |
555 | AtomicOrderingBitfieldElementT<WeakField::NextBit>; |
556 | using FailureOrderingField = |
557 | AtomicOrderingBitfieldElementT<SuccessOrderingField::NextBit>; |
558 | using AlignmentField = |
559 | AlignmentBitfieldElementT<FailureOrderingField::NextBit>; |
560 | static_assert( |
561 | Bitfield::areContiguous<VolatileField, WeakField, SuccessOrderingField, |
562 | FailureOrderingField, AlignmentField>(), |
563 | "Bitfields must be contiguous"); |
564 | |
565 | /// Return the alignment of the memory that is being allocated by the |
566 | /// instruction. |
567 | Align getAlign() const { |
568 | return Align(1ULL << getSubclassData<AlignmentField>()); |
569 | } |
570 | |
571 | void setAlignment(Align Align) { |
572 | setSubclassData<AlignmentField>(Log2(Align)); |
573 | } |
574 | |
575 | /// Return true if this is a cmpxchg from a volatile memory |
576 | /// location. |
577 | /// |
578 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
579 | |
580 | /// Specify whether this is a volatile cmpxchg. |
581 | /// |
582 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
583 | |
584 | /// Return true if this cmpxchg may spuriously fail. |
585 | bool isWeak() const { return getSubclassData<WeakField>(); } |
586 | |
587 | void setWeak(bool IsWeak) { setSubclassData<WeakField>(IsWeak); } |
588 | |
589 | /// Transparently provide more efficient getOperand methods. |
590 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
591 | |
592 | static bool isValidSuccessOrdering(AtomicOrdering Ordering) { |
593 | return Ordering != AtomicOrdering::NotAtomic && |
594 | Ordering != AtomicOrdering::Unordered; |
595 | } |
596 | |
597 | static bool isValidFailureOrdering(AtomicOrdering Ordering) { |
598 | return Ordering != AtomicOrdering::NotAtomic && |
599 | Ordering != AtomicOrdering::Unordered && |
600 | Ordering != AtomicOrdering::AcquireRelease && |
601 | Ordering != AtomicOrdering::Release; |
602 | } |
603 | |
604 | /// Returns the success ordering constraint of this cmpxchg instruction. |
605 | AtomicOrdering getSuccessOrdering() const { |
606 | return getSubclassData<SuccessOrderingField>(); |
607 | } |
608 | |
609 | /// Sets the success ordering constraint of this cmpxchg instruction. |
610 | void setSuccessOrdering(AtomicOrdering Ordering) { |
611 | assert(isValidSuccessOrdering(Ordering) &&(static_cast <bool> (isValidSuccessOrdering(Ordering) && "invalid CmpXchg success ordering") ? void (0) : __assert_fail ("isValidSuccessOrdering(Ordering) && \"invalid CmpXchg success ordering\"" , "llvm/include/llvm/IR/Instructions.h", 612, __extension__ __PRETTY_FUNCTION__ )) |
612 | "invalid CmpXchg success ordering")(static_cast <bool> (isValidSuccessOrdering(Ordering) && "invalid CmpXchg success ordering") ? void (0) : __assert_fail ("isValidSuccessOrdering(Ordering) && \"invalid CmpXchg success ordering\"" , "llvm/include/llvm/IR/Instructions.h", 612, __extension__ __PRETTY_FUNCTION__ )); |
613 | setSubclassData<SuccessOrderingField>(Ordering); |
614 | } |
615 | |
616 | /// Returns the failure ordering constraint of this cmpxchg instruction. |
617 | AtomicOrdering getFailureOrdering() const { |
618 | return getSubclassData<FailureOrderingField>(); |
619 | } |
620 | |
621 | /// Sets the failure ordering constraint of this cmpxchg instruction. |
622 | void setFailureOrdering(AtomicOrdering Ordering) { |
623 | assert(isValidFailureOrdering(Ordering) &&(static_cast <bool> (isValidFailureOrdering(Ordering) && "invalid CmpXchg failure ordering") ? void (0) : __assert_fail ("isValidFailureOrdering(Ordering) && \"invalid CmpXchg failure ordering\"" , "llvm/include/llvm/IR/Instructions.h", 624, __extension__ __PRETTY_FUNCTION__ )) |
624 | "invalid CmpXchg failure ordering")(static_cast <bool> (isValidFailureOrdering(Ordering) && "invalid CmpXchg failure ordering") ? void (0) : __assert_fail ("isValidFailureOrdering(Ordering) && \"invalid CmpXchg failure ordering\"" , "llvm/include/llvm/IR/Instructions.h", 624, __extension__ __PRETTY_FUNCTION__ )); |
625 | setSubclassData<FailureOrderingField>(Ordering); |
626 | } |
627 | |
628 | /// Returns a single ordering which is at least as strong as both the |
629 | /// success and failure orderings for this cmpxchg. |
630 | AtomicOrdering getMergedOrdering() const { |
631 | if (getFailureOrdering() == AtomicOrdering::SequentiallyConsistent) |
632 | return AtomicOrdering::SequentiallyConsistent; |
633 | if (getFailureOrdering() == AtomicOrdering::Acquire) { |
634 | if (getSuccessOrdering() == AtomicOrdering::Monotonic) |
635 | return AtomicOrdering::Acquire; |
636 | if (getSuccessOrdering() == AtomicOrdering::Release) |
637 | return AtomicOrdering::AcquireRelease; |
638 | } |
639 | return getSuccessOrdering(); |
640 | } |
641 | |
642 | /// Returns the synchronization scope ID of this cmpxchg instruction. |
643 | SyncScope::ID getSyncScopeID() const { |
644 | return SSID; |
645 | } |
646 | |
647 | /// Sets the synchronization scope ID of this cmpxchg instruction. |
648 | void setSyncScopeID(SyncScope::ID SSID) { |
649 | this->SSID = SSID; |
650 | } |
651 | |
652 | Value *getPointerOperand() { return getOperand(0); } |
653 | const Value *getPointerOperand() const { return getOperand(0); } |
654 | static unsigned getPointerOperandIndex() { return 0U; } |
655 | |
656 | Value *getCompareOperand() { return getOperand(1); } |
657 | const Value *getCompareOperand() const { return getOperand(1); } |
658 | |
659 | Value *getNewValOperand() { return getOperand(2); } |
660 | const Value *getNewValOperand() const { return getOperand(2); } |
661 | |
662 | /// Returns the address space of the pointer operand. |
663 | unsigned getPointerAddressSpace() const { |
664 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
665 | } |
666 | |
667 | /// Returns the strongest permitted ordering on failure, given the |
668 | /// desired ordering on success. |
669 | /// |
670 | /// If the comparison in a cmpxchg operation fails, there is no atomic store |
671 | /// so release semantics cannot be provided. So this function drops explicit |
672 | /// Release requests from the AtomicOrdering. A SequentiallyConsistent |
673 | /// operation would remain SequentiallyConsistent. |
674 | static AtomicOrdering |
675 | getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) { |
676 | switch (SuccessOrdering) { |
677 | default: |
678 | llvm_unreachable("invalid cmpxchg success ordering")::llvm::llvm_unreachable_internal("invalid cmpxchg success ordering" , "llvm/include/llvm/IR/Instructions.h", 678); |
679 | case AtomicOrdering::Release: |
680 | case AtomicOrdering::Monotonic: |
681 | return AtomicOrdering::Monotonic; |
682 | case AtomicOrdering::AcquireRelease: |
683 | case AtomicOrdering::Acquire: |
684 | return AtomicOrdering::Acquire; |
685 | case AtomicOrdering::SequentiallyConsistent: |
686 | return AtomicOrdering::SequentiallyConsistent; |
687 | } |
688 | } |
689 | |
690 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
691 | static bool classof(const Instruction *I) { |
692 | return I->getOpcode() == Instruction::AtomicCmpXchg; |
693 | } |
694 | static bool classof(const Value *V) { |
695 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
696 | } |
697 | |
698 | private: |
699 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
700 | // method so that subclasses cannot accidentally use it. |
701 | template <typename Bitfield> |
702 | void setSubclassData(typename Bitfield::Type Value) { |
703 | Instruction::setSubclassData<Bitfield>(Value); |
704 | } |
705 | |
706 | /// The synchronization scope ID of this cmpxchg instruction. Not quite |
707 | /// enough room in SubClassData for everything, so synchronization scope ID |
708 | /// gets its own field. |
709 | SyncScope::ID SSID; |
710 | }; |
711 | |
712 | template <> |
713 | struct OperandTraits<AtomicCmpXchgInst> : |
714 | public FixedNumOperandTraits<AtomicCmpXchgInst, 3> { |
715 | }; |
716 | |
717 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)AtomicCmpXchgInst::op_iterator AtomicCmpXchgInst::op_begin() { return OperandTraits<AtomicCmpXchgInst>::op_begin(this ); } AtomicCmpXchgInst::const_op_iterator AtomicCmpXchgInst:: op_begin() const { return OperandTraits<AtomicCmpXchgInst> ::op_begin(const_cast<AtomicCmpXchgInst*>(this)); } AtomicCmpXchgInst ::op_iterator AtomicCmpXchgInst::op_end() { return OperandTraits <AtomicCmpXchgInst>::op_end(this); } AtomicCmpXchgInst:: const_op_iterator AtomicCmpXchgInst::op_end() const { return OperandTraits <AtomicCmpXchgInst>::op_end(const_cast<AtomicCmpXchgInst *>(this)); } Value *AtomicCmpXchgInst::getOperand(unsigned i_nocapture) const { (static_cast <bool> (i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 717, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<AtomicCmpXchgInst >::op_begin(const_cast<AtomicCmpXchgInst*>(this))[i_nocapture ].get()); } void AtomicCmpXchgInst::setOperand(unsigned i_nocapture , Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 717, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<AtomicCmpXchgInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned AtomicCmpXchgInst::getNumOperands () const { return OperandTraits<AtomicCmpXchgInst>::operands (this); } template <int Idx_nocapture> Use &AtomicCmpXchgInst ::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &AtomicCmpXchgInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
718 | |
719 | //===----------------------------------------------------------------------===// |
720 | // AtomicRMWInst Class |
721 | //===----------------------------------------------------------------------===// |
722 | |
723 | /// an instruction that atomically reads a memory location, |
724 | /// combines it with another value, and then stores the result back. Returns |
725 | /// the old value. |
726 | /// |
727 | class AtomicRMWInst : public Instruction { |
728 | protected: |
729 | // Note: Instruction needs to be a friend here to call cloneImpl. |
730 | friend class Instruction; |
731 | |
732 | AtomicRMWInst *cloneImpl() const; |
733 | |
734 | public: |
735 | /// This enumeration lists the possible modifications atomicrmw can make. In |
736 | /// the descriptions, 'p' is the pointer to the instruction's memory location, |
737 | /// 'old' is the initial value of *p, and 'v' is the other value passed to the |
738 | /// instruction. These instructions always return 'old'. |
739 | enum BinOp : unsigned { |
740 | /// *p = v |
741 | Xchg, |
742 | /// *p = old + v |
743 | Add, |
744 | /// *p = old - v |
745 | Sub, |
746 | /// *p = old & v |
747 | And, |
748 | /// *p = ~(old & v) |
749 | Nand, |
750 | /// *p = old | v |
751 | Or, |
752 | /// *p = old ^ v |
753 | Xor, |
754 | /// *p = old >signed v ? old : v |
755 | Max, |
756 | /// *p = old <signed v ? old : v |
757 | Min, |
758 | /// *p = old >unsigned v ? old : v |
759 | UMax, |
760 | /// *p = old <unsigned v ? old : v |
761 | UMin, |
762 | |
763 | /// *p = old + v |
764 | FAdd, |
765 | |
766 | /// *p = old - v |
767 | FSub, |
768 | |
769 | FIRST_BINOP = Xchg, |
770 | LAST_BINOP = FSub, |
771 | BAD_BINOP |
772 | }; |
773 | |
774 | private: |
775 | template <unsigned Offset> |
776 | using AtomicOrderingBitfieldElement = |
777 | typename Bitfield::Element<AtomicOrdering, Offset, 3, |
778 | AtomicOrdering::LAST>; |
779 | |
780 | template <unsigned Offset> |
781 | using BinOpBitfieldElement = |
782 | typename Bitfield::Element<BinOp, Offset, 4, BinOp::LAST_BINOP>; |
783 | |
784 | public: |
785 | AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment, |
786 | AtomicOrdering Ordering, SyncScope::ID SSID, |
787 | Instruction *InsertBefore = nullptr); |
788 | AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment, |
789 | AtomicOrdering Ordering, SyncScope::ID SSID, |
790 | BasicBlock *InsertAtEnd); |
791 | |
792 | // allocate space for exactly two operands |
793 | void *operator new(size_t S) { return User::operator new(S, 2); } |
794 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
795 | |
796 | using VolatileField = BoolBitfieldElementT<0>; |
797 | using AtomicOrderingField = |
798 | AtomicOrderingBitfieldElementT<VolatileField::NextBit>; |
799 | using OperationField = BinOpBitfieldElement<AtomicOrderingField::NextBit>; |
800 | using AlignmentField = AlignmentBitfieldElementT<OperationField::NextBit>; |
801 | static_assert(Bitfield::areContiguous<VolatileField, AtomicOrderingField, |
802 | OperationField, AlignmentField>(), |
803 | "Bitfields must be contiguous"); |
804 | |
805 | BinOp getOperation() const { return getSubclassData<OperationField>(); } |
806 | |
807 | static StringRef getOperationName(BinOp Op); |
808 | |
809 | static bool isFPOperation(BinOp Op) { |
810 | switch (Op) { |
811 | case AtomicRMWInst::FAdd: |
812 | case AtomicRMWInst::FSub: |
813 | return true; |
814 | default: |
815 | return false; |
816 | } |
817 | } |
818 | |
819 | void setOperation(BinOp Operation) { |
820 | setSubclassData<OperationField>(Operation); |
821 | } |
822 | |
823 | /// Return the alignment of the memory that is being allocated by the |
824 | /// instruction. |
825 | Align getAlign() const { |
826 | return Align(1ULL << getSubclassData<AlignmentField>()); |
827 | } |
828 | |
829 | void setAlignment(Align Align) { |
830 | setSubclassData<AlignmentField>(Log2(Align)); |
831 | } |
832 | |
833 | /// Return true if this is a RMW on a volatile memory location. |
834 | /// |
835 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
836 | |
837 | /// Specify whether this is a volatile RMW or not. |
838 | /// |
839 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
840 | |
841 | /// Transparently provide more efficient getOperand methods. |
842 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
843 | |
844 | /// Returns the ordering constraint of this rmw instruction. |
845 | AtomicOrdering getOrdering() const { |
846 | return getSubclassData<AtomicOrderingField>(); |
847 | } |
848 | |
849 | /// Sets the ordering constraint of this rmw instruction. |
850 | void setOrdering(AtomicOrdering Ordering) { |
851 | assert(Ordering != AtomicOrdering::NotAtomic &&(static_cast <bool> (Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic.") ? void (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\"" , "llvm/include/llvm/IR/Instructions.h", 852, __extension__ __PRETTY_FUNCTION__ )) |
852 | "atomicrmw instructions can only be atomic.")(static_cast <bool> (Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic.") ? void (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\"" , "llvm/include/llvm/IR/Instructions.h", 852, __extension__ __PRETTY_FUNCTION__ )); |
853 | setSubclassData<AtomicOrderingField>(Ordering); |
854 | } |
855 | |
856 | /// Returns the synchronization scope ID of this rmw instruction. |
857 | SyncScope::ID getSyncScopeID() const { |
858 | return SSID; |
859 | } |
860 | |
861 | /// Sets the synchronization scope ID of this rmw instruction. |
862 | void setSyncScopeID(SyncScope::ID SSID) { |
863 | this->SSID = SSID; |
864 | } |
865 | |
866 | Value *getPointerOperand() { return getOperand(0); } |
867 | const Value *getPointerOperand() const { return getOperand(0); } |
868 | static unsigned getPointerOperandIndex() { return 0U; } |
869 | |
870 | Value *getValOperand() { return getOperand(1); } |
871 | const Value *getValOperand() const { return getOperand(1); } |
872 | |
873 | /// Returns the address space of the pointer operand. |
874 | unsigned getPointerAddressSpace() const { |
875 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
876 | } |
877 | |
878 | bool isFloatingPointOperation() const { |
879 | return isFPOperation(getOperation()); |
880 | } |
881 | |
882 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
883 | static bool classof(const Instruction *I) { |
884 | return I->getOpcode() == Instruction::AtomicRMW; |
885 | } |
886 | static bool classof(const Value *V) { |
887 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
888 | } |
889 | |
890 | private: |
891 | void Init(BinOp Operation, Value *Ptr, Value *Val, Align Align, |
892 | AtomicOrdering Ordering, SyncScope::ID SSID); |
893 | |
894 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
895 | // method so that subclasses cannot accidentally use it. |
896 | template <typename Bitfield> |
897 | void setSubclassData(typename Bitfield::Type Value) { |
898 | Instruction::setSubclassData<Bitfield>(Value); |
899 | } |
900 | |
901 | /// The synchronization scope ID of this rmw instruction. Not quite enough |
902 | /// room in SubClassData for everything, so synchronization scope ID gets its |
903 | /// own field. |
904 | SyncScope::ID SSID; |
905 | }; |
906 | |
907 | template <> |
908 | struct OperandTraits<AtomicRMWInst> |
909 | : public FixedNumOperandTraits<AtomicRMWInst,2> { |
910 | }; |
911 | |
912 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)AtomicRMWInst::op_iterator AtomicRMWInst::op_begin() { return OperandTraits<AtomicRMWInst>::op_begin(this); } AtomicRMWInst ::const_op_iterator AtomicRMWInst::op_begin() const { return OperandTraits <AtomicRMWInst>::op_begin(const_cast<AtomicRMWInst*> (this)); } AtomicRMWInst::op_iterator AtomicRMWInst::op_end() { return OperandTraits<AtomicRMWInst>::op_end(this); } AtomicRMWInst::const_op_iterator AtomicRMWInst::op_end() const { return OperandTraits<AtomicRMWInst>::op_end(const_cast <AtomicRMWInst*>(this)); } Value *AtomicRMWInst::getOperand (unsigned i_nocapture) const { (static_cast <bool> (i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 912, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<AtomicRMWInst >::op_begin(const_cast<AtomicRMWInst*>(this))[i_nocapture ].get()); } void AtomicRMWInst::setOperand(unsigned i_nocapture , Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 912, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<AtomicRMWInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned AtomicRMWInst::getNumOperands() const { return OperandTraits<AtomicRMWInst>::operands( this); } template <int Idx_nocapture> Use &AtomicRMWInst ::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &AtomicRMWInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
913 | |
914 | //===----------------------------------------------------------------------===// |
915 | // GetElementPtrInst Class |
916 | //===----------------------------------------------------------------------===// |
917 | |
918 | // checkGEPType - Simple wrapper function to give a better assertion failure |
919 | // message on bad indexes for a gep instruction. |
920 | // |
921 | inline Type *checkGEPType(Type *Ty) { |
922 | assert(Ty && "Invalid GetElementPtrInst indices for type!")(static_cast <bool> (Ty && "Invalid GetElementPtrInst indices for type!" ) ? void (0) : __assert_fail ("Ty && \"Invalid GetElementPtrInst indices for type!\"" , "llvm/include/llvm/IR/Instructions.h", 922, __extension__ __PRETTY_FUNCTION__ )); |
923 | return Ty; |
924 | } |
925 | |
926 | /// an instruction for type-safe pointer arithmetic to |
927 | /// access elements of arrays and structs |
928 | /// |
929 | class GetElementPtrInst : public Instruction { |
930 | Type *SourceElementType; |
931 | Type *ResultElementType; |
932 | |
933 | GetElementPtrInst(const GetElementPtrInst &GEPI); |
934 | |
935 | /// Constructors - Create a getelementptr instruction with a base pointer an |
936 | /// list of indices. The first ctor can optionally insert before an existing |
937 | /// instruction, the second appends the new instruction to the specified |
938 | /// BasicBlock. |
939 | inline GetElementPtrInst(Type *PointeeType, Value *Ptr, |
940 | ArrayRef<Value *> IdxList, unsigned Values, |
941 | const Twine &NameStr, Instruction *InsertBefore); |
942 | inline GetElementPtrInst(Type *PointeeType, Value *Ptr, |
943 | ArrayRef<Value *> IdxList, unsigned Values, |
944 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
945 | |
946 | void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr); |
947 | |
948 | protected: |
949 | // Note: Instruction needs to be a friend here to call cloneImpl. |
950 | friend class Instruction; |
951 | |
952 | GetElementPtrInst *cloneImpl() const; |
953 | |
954 | public: |
955 | static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr, |
956 | ArrayRef<Value *> IdxList, |
957 | const Twine &NameStr = "", |
958 | Instruction *InsertBefore = nullptr) { |
959 | unsigned Values = 1 + unsigned(IdxList.size()); |
960 | assert(PointeeType && "Must specify element type")(static_cast <bool> (PointeeType && "Must specify element type" ) ? void (0) : __assert_fail ("PointeeType && \"Must specify element type\"" , "llvm/include/llvm/IR/Instructions.h", 960, __extension__ __PRETTY_FUNCTION__ )); |
961 | assert(cast<PointerType>(Ptr->getType()->getScalarType())(static_cast <bool> (cast<PointerType>(Ptr->getType ()->getScalarType()) ->isOpaqueOrPointeeTypeMatches(PointeeType )) ? void (0) : __assert_fail ("cast<PointerType>(Ptr->getType()->getScalarType()) ->isOpaqueOrPointeeTypeMatches(PointeeType)" , "llvm/include/llvm/IR/Instructions.h", 962, __extension__ __PRETTY_FUNCTION__ )) |
962 | ->isOpaqueOrPointeeTypeMatches(PointeeType))(static_cast <bool> (cast<PointerType>(Ptr->getType ()->getScalarType()) ->isOpaqueOrPointeeTypeMatches(PointeeType )) ? void (0) : __assert_fail ("cast<PointerType>(Ptr->getType()->getScalarType()) ->isOpaqueOrPointeeTypeMatches(PointeeType)" , "llvm/include/llvm/IR/Instructions.h", 962, __extension__ __PRETTY_FUNCTION__ )); |
963 | return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values, |
964 | NameStr, InsertBefore); |
965 | } |
966 | |
967 | static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr, |
968 | ArrayRef<Value *> IdxList, |
969 | const Twine &NameStr, |
970 | BasicBlock *InsertAtEnd) { |
971 | unsigned Values = 1 + unsigned(IdxList.size()); |
972 | assert(PointeeType && "Must specify element type")(static_cast <bool> (PointeeType && "Must specify element type" ) ? void (0) : __assert_fail ("PointeeType && \"Must specify element type\"" , "llvm/include/llvm/IR/Instructions.h", 972, __extension__ __PRETTY_FUNCTION__ )); |
973 | assert(cast<PointerType>(Ptr->getType()->getScalarType())(static_cast <bool> (cast<PointerType>(Ptr->getType ()->getScalarType()) ->isOpaqueOrPointeeTypeMatches(PointeeType )) ? void (0) : __assert_fail ("cast<PointerType>(Ptr->getType()->getScalarType()) ->isOpaqueOrPointeeTypeMatches(PointeeType)" , "llvm/include/llvm/IR/Instructions.h", 974, __extension__ __PRETTY_FUNCTION__ )) |
974 | ->isOpaqueOrPointeeTypeMatches(PointeeType))(static_cast <bool> (cast<PointerType>(Ptr->getType ()->getScalarType()) ->isOpaqueOrPointeeTypeMatches(PointeeType )) ? void (0) : __assert_fail ("cast<PointerType>(Ptr->getType()->getScalarType()) ->isOpaqueOrPointeeTypeMatches(PointeeType)" , "llvm/include/llvm/IR/Instructions.h", 974, __extension__ __PRETTY_FUNCTION__ )); |
975 | return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values, |
976 | NameStr, InsertAtEnd); |
977 | } |
978 | |
979 | /// Create an "inbounds" getelementptr. See the documentation for the |
980 | /// "inbounds" flag in LangRef.html for details. |
981 | static GetElementPtrInst * |
982 | CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList, |
983 | const Twine &NameStr = "", |
984 | Instruction *InsertBefore = nullptr) { |
985 | GetElementPtrInst *GEP = |
986 | Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore); |
987 | GEP->setIsInBounds(true); |
988 | return GEP; |
989 | } |
990 | |
991 | static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr, |
992 | ArrayRef<Value *> IdxList, |
993 | const Twine &NameStr, |
994 | BasicBlock *InsertAtEnd) { |
995 | GetElementPtrInst *GEP = |
996 | Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd); |
997 | GEP->setIsInBounds(true); |
998 | return GEP; |
999 | } |
1000 | |
1001 | /// Transparently provide more efficient getOperand methods. |
1002 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1003 | |
1004 | Type *getSourceElementType() const { return SourceElementType; } |
1005 | |
1006 | void setSourceElementType(Type *Ty) { SourceElementType = Ty; } |
1007 | void setResultElementType(Type *Ty) { ResultElementType = Ty; } |
1008 | |
1009 | Type *getResultElementType() const { |
1010 | assert(cast<PointerType>(getType()->getScalarType())(static_cast <bool> (cast<PointerType>(getType()-> getScalarType()) ->isOpaqueOrPointeeTypeMatches(ResultElementType )) ? void (0) : __assert_fail ("cast<PointerType>(getType()->getScalarType()) ->isOpaqueOrPointeeTypeMatches(ResultElementType)" , "llvm/include/llvm/IR/Instructions.h", 1011, __extension__ __PRETTY_FUNCTION__ )) |
1011 | ->isOpaqueOrPointeeTypeMatches(ResultElementType))(static_cast <bool> (cast<PointerType>(getType()-> getScalarType()) ->isOpaqueOrPointeeTypeMatches(ResultElementType )) ? void (0) : __assert_fail ("cast<PointerType>(getType()->getScalarType()) ->isOpaqueOrPointeeTypeMatches(ResultElementType)" , "llvm/include/llvm/IR/Instructions.h", 1011, __extension__ __PRETTY_FUNCTION__ )); |
1012 | return ResultElementType; |
1013 | } |
1014 | |
1015 | /// Returns the address space of this instruction's pointer type. |
1016 | unsigned getAddressSpace() const { |
1017 | // Note that this is always the same as the pointer operand's address space |
1018 | // and that is cheaper to compute, so cheat here. |
1019 | return getPointerAddressSpace(); |
1020 | } |
1021 | |
1022 | /// Returns the result type of a getelementptr with the given source |
1023 | /// element type and indexes. |
1024 | /// |
1025 | /// Null is returned if the indices are invalid for the specified |
1026 | /// source element type. |
1027 | static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList); |
1028 | static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList); |
1029 | static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList); |
1030 | |
1031 | /// Return the type of the element at the given index of an indexable |
1032 | /// type. This is equivalent to "getIndexedType(Agg, {Zero, Idx})". |
1033 | /// |
1034 | /// Returns null if the type can't be indexed, or the given index is not |
1035 | /// legal for the given type. |
1036 | static Type *getTypeAtIndex(Type *Ty, Value *Idx); |
1037 | static Type *getTypeAtIndex(Type *Ty, uint64_t Idx); |
1038 | |
1039 | inline op_iterator idx_begin() { return op_begin()+1; } |
1040 | inline const_op_iterator idx_begin() const { return op_begin()+1; } |
1041 | inline op_iterator idx_end() { return op_end(); } |
1042 | inline const_op_iterator idx_end() const { return op_end(); } |
1043 | |
1044 | inline iterator_range<op_iterator> indices() { |
1045 | return make_range(idx_begin(), idx_end()); |
1046 | } |
1047 | |
1048 | inline iterator_range<const_op_iterator> indices() const { |
1049 | return make_range(idx_begin(), idx_end()); |
1050 | } |
1051 | |
1052 | Value *getPointerOperand() { |
1053 | return getOperand(0); |
1054 | } |
1055 | const Value *getPointerOperand() const { |
1056 | return getOperand(0); |
1057 | } |
1058 | static unsigned getPointerOperandIndex() { |
1059 | return 0U; // get index for modifying correct operand. |
1060 | } |
1061 | |
1062 | /// Method to return the pointer operand as a |
1063 | /// PointerType. |
1064 | Type *getPointerOperandType() const { |
1065 | return getPointerOperand()->getType(); |
1066 | } |
1067 | |
1068 | /// Returns the address space of the pointer operand. |
1069 | unsigned getPointerAddressSpace() const { |
1070 | return getPointerOperandType()->getPointerAddressSpace(); |
1071 | } |
1072 | |
1073 | /// Returns the pointer type returned by the GEP |
1074 | /// instruction, which may be a vector of pointers. |
1075 | static Type *getGEPReturnType(Type *ElTy, Value *Ptr, |
1076 | ArrayRef<Value *> IdxList) { |
1077 | PointerType *OrigPtrTy = cast<PointerType>(Ptr->getType()->getScalarType()); |
1078 | unsigned AddrSpace = OrigPtrTy->getAddressSpace(); |
1079 | Type *ResultElemTy = checkGEPType(getIndexedType(ElTy, IdxList)); |
1080 | Type *PtrTy = OrigPtrTy->isOpaque() |
1081 | ? PointerType::get(OrigPtrTy->getContext(), AddrSpace) |
1082 | : PointerType::get(ResultElemTy, AddrSpace); |
1083 | // Vector GEP |
1084 | if (auto *PtrVTy = dyn_cast<VectorType>(Ptr->getType())) { |
1085 | ElementCount EltCount = PtrVTy->getElementCount(); |
1086 | return VectorType::get(PtrTy, EltCount); |
1087 | } |
1088 | for (Value *Index : IdxList) |
1089 | if (auto *IndexVTy = dyn_cast<VectorType>(Index->getType())) { |
1090 | ElementCount EltCount = IndexVTy->getElementCount(); |
1091 | return VectorType::get(PtrTy, EltCount); |
1092 | } |
1093 | // Scalar GEP |
1094 | return PtrTy; |
1095 | } |
1096 | |
1097 | unsigned getNumIndices() const { // Note: always non-negative |
1098 | return getNumOperands() - 1; |
1099 | } |
1100 | |
1101 | bool hasIndices() const { |
1102 | return getNumOperands() > 1; |
1103 | } |
1104 | |
1105 | /// Return true if all of the indices of this GEP are |
1106 | /// zeros. If so, the result pointer and the first operand have the same |
1107 | /// value, just potentially different types. |
1108 | bool hasAllZeroIndices() const; |
1109 | |
1110 | /// Return true if all of the indices of this GEP are |
1111 | /// constant integers. If so, the result pointer and the first operand have |
1112 | /// a constant offset between them. |
1113 | bool hasAllConstantIndices() const; |
1114 | |
1115 | /// Set or clear the inbounds flag on this GEP instruction. |
1116 | /// See LangRef.html for the meaning of inbounds on a getelementptr. |
1117 | void setIsInBounds(bool b = true); |
1118 | |
1119 | /// Determine whether the GEP has the inbounds flag. |
1120 | bool isInBounds() const; |
1121 | |
1122 | /// Accumulate the constant address offset of this GEP if possible. |
1123 | /// |
1124 | /// This routine accepts an APInt into which it will accumulate the constant |
1125 | /// offset of this GEP if the GEP is in fact constant. If the GEP is not |
1126 | /// all-constant, it returns false and the value of the offset APInt is |
1127 | /// undefined (it is *not* preserved!). The APInt passed into this routine |
1128 | /// must be at least as wide as the IntPtr type for the address space of |
1129 | /// the base GEP pointer. |
1130 | bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const; |
1131 | bool collectOffset(const DataLayout &DL, unsigned BitWidth, |
1132 | MapVector<Value *, APInt> &VariableOffsets, |
1133 | APInt &ConstantOffset) const; |
1134 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1135 | static bool classof(const Instruction *I) { |
1136 | return (I->getOpcode() == Instruction::GetElementPtr); |
1137 | } |
1138 | static bool classof(const Value *V) { |
1139 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1140 | } |
1141 | }; |
1142 | |
1143 | template <> |
1144 | struct OperandTraits<GetElementPtrInst> : |
1145 | public VariadicOperandTraits<GetElementPtrInst, 1> { |
1146 | }; |
1147 | |
1148 | GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr, |
1149 | ArrayRef<Value *> IdxList, unsigned Values, |
1150 | const Twine &NameStr, |
1151 | Instruction *InsertBefore) |
1152 | : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr, |
1153 | OperandTraits<GetElementPtrInst>::op_end(this) - Values, |
1154 | Values, InsertBefore), |
1155 | SourceElementType(PointeeType), |
1156 | ResultElementType(getIndexedType(PointeeType, IdxList)) { |
1157 | assert(cast<PointerType>(getType()->getScalarType())(static_cast <bool> (cast<PointerType>(getType()-> getScalarType()) ->isOpaqueOrPointeeTypeMatches(ResultElementType )) ? void (0) : __assert_fail ("cast<PointerType>(getType()->getScalarType()) ->isOpaqueOrPointeeTypeMatches(ResultElementType)" , "llvm/include/llvm/IR/Instructions.h", 1158, __extension__ __PRETTY_FUNCTION__ )) |
1158 | ->isOpaqueOrPointeeTypeMatches(ResultElementType))(static_cast <bool> (cast<PointerType>(getType()-> getScalarType()) ->isOpaqueOrPointeeTypeMatches(ResultElementType )) ? void (0) : __assert_fail ("cast<PointerType>(getType()->getScalarType()) ->isOpaqueOrPointeeTypeMatches(ResultElementType)" , "llvm/include/llvm/IR/Instructions.h", 1158, __extension__ __PRETTY_FUNCTION__ )); |
1159 | init(Ptr, IdxList, NameStr); |
1160 | } |
1161 | |
1162 | GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr, |
1163 | ArrayRef<Value *> IdxList, unsigned Values, |
1164 | const Twine &NameStr, |
1165 | BasicBlock *InsertAtEnd) |
1166 | : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr, |
1167 | OperandTraits<GetElementPtrInst>::op_end(this) - Values, |
1168 | Values, InsertAtEnd), |
1169 | SourceElementType(PointeeType), |
1170 | ResultElementType(getIndexedType(PointeeType, IdxList)) { |
1171 | assert(cast<PointerType>(getType()->getScalarType())(static_cast <bool> (cast<PointerType>(getType()-> getScalarType()) ->isOpaqueOrPointeeTypeMatches(ResultElementType )) ? void (0) : __assert_fail ("cast<PointerType>(getType()->getScalarType()) ->isOpaqueOrPointeeTypeMatches(ResultElementType)" , "llvm/include/llvm/IR/Instructions.h", 1172, __extension__ __PRETTY_FUNCTION__ )) |
1172 | ->isOpaqueOrPointeeTypeMatches(ResultElementType))(static_cast <bool> (cast<PointerType>(getType()-> getScalarType()) ->isOpaqueOrPointeeTypeMatches(ResultElementType )) ? void (0) : __assert_fail ("cast<PointerType>(getType()->getScalarType()) ->isOpaqueOrPointeeTypeMatches(ResultElementType)" , "llvm/include/llvm/IR/Instructions.h", 1172, __extension__ __PRETTY_FUNCTION__ )); |
1173 | init(Ptr, IdxList, NameStr); |
1174 | } |
1175 | |
1176 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)GetElementPtrInst::op_iterator GetElementPtrInst::op_begin() { return OperandTraits<GetElementPtrInst>::op_begin(this ); } GetElementPtrInst::const_op_iterator GetElementPtrInst:: op_begin() const { return OperandTraits<GetElementPtrInst> ::op_begin(const_cast<GetElementPtrInst*>(this)); } GetElementPtrInst ::op_iterator GetElementPtrInst::op_end() { return OperandTraits <GetElementPtrInst>::op_end(this); } GetElementPtrInst:: const_op_iterator GetElementPtrInst::op_end() const { return OperandTraits <GetElementPtrInst>::op_end(const_cast<GetElementPtrInst *>(this)); } Value *GetElementPtrInst::getOperand(unsigned i_nocapture) const { (static_cast <bool> (i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 1176, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<GetElementPtrInst >::op_begin(const_cast<GetElementPtrInst*>(this))[i_nocapture ].get()); } void GetElementPtrInst::setOperand(unsigned i_nocapture , Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 1176, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<GetElementPtrInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned GetElementPtrInst::getNumOperands () const { return OperandTraits<GetElementPtrInst>::operands (this); } template <int Idx_nocapture> Use &GetElementPtrInst ::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &GetElementPtrInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
1177 | |
1178 | //===----------------------------------------------------------------------===// |
1179 | // ICmpInst Class |
1180 | //===----------------------------------------------------------------------===// |
1181 | |
1182 | /// This instruction compares its operands according to the predicate given |
1183 | /// to the constructor. It only operates on integers or pointers. The operands |
1184 | /// must be identical types. |
1185 | /// Represent an integer comparison operator. |
1186 | class ICmpInst: public CmpInst { |
1187 | void AssertOK() { |
1188 | assert(isIntPredicate() &&(static_cast <bool> (isIntPredicate() && "Invalid ICmp predicate value" ) ? void (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\"" , "llvm/include/llvm/IR/Instructions.h", 1189, __extension__ __PRETTY_FUNCTION__ )) |
1189 | "Invalid ICmp predicate value")(static_cast <bool> (isIntPredicate() && "Invalid ICmp predicate value" ) ? void (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\"" , "llvm/include/llvm/IR/Instructions.h", 1189, __extension__ __PRETTY_FUNCTION__ )); |
1190 | assert(getOperand(0)->getType() == getOperand(1)->getType() &&(static_cast <bool> (getOperand(0)->getType() == getOperand (1)->getType() && "Both operands to ICmp instruction are not of the same type!" ) ? void (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\"" , "llvm/include/llvm/IR/Instructions.h", 1191, __extension__ __PRETTY_FUNCTION__ )) |
1191 | "Both operands to ICmp instruction are not of the same type!")(static_cast <bool> (getOperand(0)->getType() == getOperand (1)->getType() && "Both operands to ICmp instruction are not of the same type!" ) ? void (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\"" , "llvm/include/llvm/IR/Instructions.h", 1191, __extension__ __PRETTY_FUNCTION__ )); |
1192 | // Check that the operands are the right type |
1193 | assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||(static_cast <bool> ((getOperand(0)->getType()->isIntOrIntVectorTy () || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction") ? void (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\"" , "llvm/include/llvm/IR/Instructions.h", 1195, __extension__ __PRETTY_FUNCTION__ )) |
1194 | getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&(static_cast <bool> ((getOperand(0)->getType()->isIntOrIntVectorTy () || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction") ? void (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\"" , "llvm/include/llvm/IR/Instructions.h", 1195, __extension__ __PRETTY_FUNCTION__ )) |
1195 | "Invalid operand types for ICmp instruction")(static_cast <bool> ((getOperand(0)->getType()->isIntOrIntVectorTy () || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction") ? void (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\"" , "llvm/include/llvm/IR/Instructions.h", 1195, __extension__ __PRETTY_FUNCTION__ )); |
1196 | } |
1197 | |
1198 | protected: |
1199 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1200 | friend class Instruction; |
1201 | |
1202 | /// Clone an identical ICmpInst |
1203 | ICmpInst *cloneImpl() const; |
1204 | |
1205 | public: |
1206 | /// Constructor with insert-before-instruction semantics. |
1207 | ICmpInst( |
1208 | Instruction *InsertBefore, ///< Where to insert |
1209 | Predicate pred, ///< The predicate to use for the comparison |
1210 | Value *LHS, ///< The left-hand-side of the expression |
1211 | Value *RHS, ///< The right-hand-side of the expression |
1212 | const Twine &NameStr = "" ///< Name of the instruction |
1213 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1214 | Instruction::ICmp, pred, LHS, RHS, NameStr, |
1215 | InsertBefore) { |
1216 | #ifndef NDEBUG |
1217 | AssertOK(); |
1218 | #endif |
1219 | } |
1220 | |
1221 | /// Constructor with insert-at-end semantics. |
1222 | ICmpInst( |
1223 | BasicBlock &InsertAtEnd, ///< Block to insert into. |
1224 | Predicate pred, ///< The predicate to use for the comparison |
1225 | Value *LHS, ///< The left-hand-side of the expression |
1226 | Value *RHS, ///< The right-hand-side of the expression |
1227 | const Twine &NameStr = "" ///< Name of the instruction |
1228 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1229 | Instruction::ICmp, pred, LHS, RHS, NameStr, |
1230 | &InsertAtEnd) { |
1231 | #ifndef NDEBUG |
1232 | AssertOK(); |
1233 | #endif |
1234 | } |
1235 | |
1236 | /// Constructor with no-insertion semantics |
1237 | ICmpInst( |
1238 | Predicate pred, ///< The predicate to use for the comparison |
1239 | Value *LHS, ///< The left-hand-side of the expression |
1240 | Value *RHS, ///< The right-hand-side of the expression |
1241 | const Twine &NameStr = "" ///< Name of the instruction |
1242 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1243 | Instruction::ICmp, pred, LHS, RHS, NameStr) { |
1244 | #ifndef NDEBUG |
1245 | AssertOK(); |
1246 | #endif |
1247 | } |
1248 | |
1249 | /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc. |
1250 | /// @returns the predicate that would be the result if the operand were |
1251 | /// regarded as signed. |
1252 | /// Return the signed version of the predicate |
1253 | Predicate getSignedPredicate() const { |
1254 | return getSignedPredicate(getPredicate()); |
1255 | } |
1256 | |
1257 | /// This is a static version that you can use without an instruction. |
1258 | /// Return the signed version of the predicate. |
1259 | static Predicate getSignedPredicate(Predicate pred); |
1260 | |
1261 | /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc. |
1262 | /// @returns the predicate that would be the result if the operand were |
1263 | /// regarded as unsigned. |
1264 | /// Return the unsigned version of the predicate |
1265 | Predicate getUnsignedPredicate() const { |
1266 | return getUnsignedPredicate(getPredicate()); |
1267 | } |
1268 | |
1269 | /// This is a static version that you can use without an instruction. |
1270 | /// Return the unsigned version of the predicate. |
1271 | static Predicate getUnsignedPredicate(Predicate pred); |
1272 | |
1273 | /// Return true if this predicate is either EQ or NE. This also |
1274 | /// tests for commutativity. |
1275 | static bool isEquality(Predicate P) { |
1276 | return P == ICMP_EQ || P == ICMP_NE; |
1277 | } |
1278 | |
1279 | /// Return true if this predicate is either EQ or NE. This also |
1280 | /// tests for commutativity. |
1281 | bool isEquality() const { |
1282 | return isEquality(getPredicate()); |
1283 | } |
1284 | |
1285 | /// @returns true if the predicate of this ICmpInst is commutative |
1286 | /// Determine if this relation is commutative. |
1287 | bool isCommutative() const { return isEquality(); } |
1288 | |
1289 | /// Return true if the predicate is relational (not EQ or NE). |
1290 | /// |
1291 | bool isRelational() const { |
1292 | return !isEquality(); |
1293 | } |
1294 | |
1295 | /// Return true if the predicate is relational (not EQ or NE). |
1296 | /// |
1297 | static bool isRelational(Predicate P) { |
1298 | return !isEquality(P); |
1299 | } |
1300 | |
1301 | /// Return true if the predicate is SGT or UGT. |
1302 | /// |
1303 | static bool isGT(Predicate P) { |
1304 | return P == ICMP_SGT || P == ICMP_UGT; |
1305 | } |
1306 | |
1307 | /// Return true if the predicate is SLT or ULT. |
1308 | /// |
1309 | static bool isLT(Predicate P) { |
1310 | return P == ICMP_SLT || P == ICMP_ULT; |
1311 | } |
1312 | |
1313 | /// Return true if the predicate is SGE or UGE. |
1314 | /// |
1315 | static bool isGE(Predicate P) { |
1316 | return P == ICMP_SGE || P == ICMP_UGE; |
1317 | } |
1318 | |
1319 | /// Return true if the predicate is SLE or ULE. |
1320 | /// |
1321 | static bool isLE(Predicate P) { |
1322 | return P == ICMP_SLE || P == ICMP_ULE; |
1323 | } |
1324 | |
1325 | /// Returns the sequence of all ICmp predicates. |
1326 | /// |
1327 | static auto predicates() { return ICmpPredicates(); } |
1328 | |
1329 | /// Exchange the two operands to this instruction in such a way that it does |
1330 | /// not modify the semantics of the instruction. The predicate value may be |
1331 | /// changed to retain the same result if the predicate is order dependent |
1332 | /// (e.g. ult). |
1333 | /// Swap operands and adjust predicate. |
1334 | void swapOperands() { |
1335 | setPredicate(getSwappedPredicate()); |
1336 | Op<0>().swap(Op<1>()); |
1337 | } |
1338 | |
1339 | /// Return result of `LHS Pred RHS` comparison. |
1340 | static bool compare(const APInt &LHS, const APInt &RHS, |
1341 | ICmpInst::Predicate Pred); |
1342 | |
1343 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1344 | static bool classof(const Instruction *I) { |
1345 | return I->getOpcode() == Instruction::ICmp; |
1346 | } |
1347 | static bool classof(const Value *V) { |
1348 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1349 | } |
1350 | }; |
1351 | |
1352 | //===----------------------------------------------------------------------===// |
1353 | // FCmpInst Class |
1354 | //===----------------------------------------------------------------------===// |
1355 | |
1356 | /// This instruction compares its operands according to the predicate given |
1357 | /// to the constructor. It only operates on floating point values or packed |
1358 | /// vectors of floating point values. The operands must be identical types. |
1359 | /// Represents a floating point comparison operator. |
1360 | class FCmpInst: public CmpInst { |
1361 | void AssertOK() { |
1362 | assert(isFPPredicate() && "Invalid FCmp predicate value")(static_cast <bool> (isFPPredicate() && "Invalid FCmp predicate value" ) ? void (0) : __assert_fail ("isFPPredicate() && \"Invalid FCmp predicate value\"" , "llvm/include/llvm/IR/Instructions.h", 1362, __extension__ __PRETTY_FUNCTION__ )); |
1363 | assert(getOperand(0)->getType() == getOperand(1)->getType() &&(static_cast <bool> (getOperand(0)->getType() == getOperand (1)->getType() && "Both operands to FCmp instruction are not of the same type!" ) ? void (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\"" , "llvm/include/llvm/IR/Instructions.h", 1364, __extension__ __PRETTY_FUNCTION__ )) |
1364 | "Both operands to FCmp instruction are not of the same type!")(static_cast <bool> (getOperand(0)->getType() == getOperand (1)->getType() && "Both operands to FCmp instruction are not of the same type!" ) ? void (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\"" , "llvm/include/llvm/IR/Instructions.h", 1364, __extension__ __PRETTY_FUNCTION__ )); |
1365 | // Check that the operands are the right type |
1366 | assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&(static_cast <bool> (getOperand(0)->getType()->isFPOrFPVectorTy () && "Invalid operand types for FCmp instruction") ? void (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\"" , "llvm/include/llvm/IR/Instructions.h", 1367, __extension__ __PRETTY_FUNCTION__ )) |
1367 | "Invalid operand types for FCmp instruction")(static_cast <bool> (getOperand(0)->getType()->isFPOrFPVectorTy () && "Invalid operand types for FCmp instruction") ? void (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\"" , "llvm/include/llvm/IR/Instructions.h", 1367, __extension__ __PRETTY_FUNCTION__ )); |
1368 | } |
1369 | |
1370 | protected: |
1371 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1372 | friend class Instruction; |
1373 | |
1374 | /// Clone an identical FCmpInst |
1375 | FCmpInst *cloneImpl() const; |
1376 | |
1377 | public: |
1378 | /// Constructor with insert-before-instruction semantics. |
1379 | FCmpInst( |
1380 | Instruction *InsertBefore, ///< Where to insert |
1381 | Predicate pred, ///< The predicate to use for the comparison |
1382 | Value *LHS, ///< The left-hand-side of the expression |
1383 | Value *RHS, ///< The right-hand-side of the expression |
1384 | const Twine &NameStr = "" ///< Name of the instruction |
1385 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1386 | Instruction::FCmp, pred, LHS, RHS, NameStr, |
1387 | InsertBefore) { |
1388 | AssertOK(); |
1389 | } |
1390 | |
1391 | /// Constructor with insert-at-end semantics. |
1392 | FCmpInst( |
1393 | BasicBlock &InsertAtEnd, ///< Block to insert into. |
1394 | Predicate pred, ///< The predicate to use for the comparison |
1395 | Value *LHS, ///< The left-hand-side of the expression |
1396 | Value *RHS, ///< The right-hand-side of the expression |
1397 | const Twine &NameStr = "" ///< Name of the instruction |
1398 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1399 | Instruction::FCmp, pred, LHS, RHS, NameStr, |
1400 | &InsertAtEnd) { |
1401 | AssertOK(); |
1402 | } |
1403 | |
1404 | /// Constructor with no-insertion semantics |
1405 | FCmpInst( |
1406 | Predicate Pred, ///< The predicate to use for the comparison |
1407 | Value *LHS, ///< The left-hand-side of the expression |
1408 | Value *RHS, ///< The right-hand-side of the expression |
1409 | const Twine &NameStr = "", ///< Name of the instruction |
1410 | Instruction *FlagsSource = nullptr |
1411 | ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS, |
1412 | RHS, NameStr, nullptr, FlagsSource) { |
1413 | AssertOK(); |
1414 | } |
1415 | |
1416 | /// @returns true if the predicate of this instruction is EQ or NE. |
1417 | /// Determine if this is an equality predicate. |
1418 | static bool isEquality(Predicate Pred) { |
1419 | return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ || |
1420 | Pred == FCMP_UNE; |
1421 | } |
1422 | |
1423 | /// @returns true if the predicate of this instruction is EQ or NE. |
1424 | /// Determine if this is an equality predicate. |
1425 | bool isEquality() const { return isEquality(getPredicate()); } |
1426 | |
1427 | /// @returns true if the predicate of this instruction is commutative. |
1428 | /// Determine if this is a commutative predicate. |
1429 | bool isCommutative() const { |
1430 | return isEquality() || |
1431 | getPredicate() == FCMP_FALSE || |
1432 | getPredicate() == FCMP_TRUE || |
1433 | getPredicate() == FCMP_ORD || |
1434 | getPredicate() == FCMP_UNO; |
1435 | } |
1436 | |
1437 | /// @returns true if the predicate is relational (not EQ or NE). |
1438 | /// Determine if this a relational predicate. |
1439 | bool isRelational() const { return !isEquality(); } |
1440 | |
1441 | /// Exchange the two operands to this instruction in such a way that it does |
1442 | /// not modify the semantics of the instruction. The predicate value may be |
1443 | /// changed to retain the same result if the predicate is order dependent |
1444 | /// (e.g. ult). |
1445 | /// Swap operands and adjust predicate. |
1446 | void swapOperands() { |
1447 | setPredicate(getSwappedPredicate()); |
1448 | Op<0>().swap(Op<1>()); |
1449 | } |
1450 | |
1451 | /// Returns the sequence of all FCmp predicates. |
1452 | /// |
1453 | static auto predicates() { return FCmpPredicates(); } |
1454 | |
1455 | /// Return result of `LHS Pred RHS` comparison. |
1456 | static bool compare(const APFloat &LHS, const APFloat &RHS, |
1457 | FCmpInst::Predicate Pred); |
1458 | |
1459 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
1460 | static bool classof(const Instruction *I) { |
1461 | return I->getOpcode() == Instruction::FCmp; |
1462 | } |
1463 | static bool classof(const Value *V) { |
1464 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1465 | } |
1466 | }; |
1467 | |
1468 | //===----------------------------------------------------------------------===// |
1469 | /// This class represents a function call, abstracting a target |
1470 | /// machine's calling convention. This class uses low bit of the SubClassData |
1471 | /// field to indicate whether or not this is a tail call. The rest of the bits |
1472 | /// hold the calling convention of the call. |
1473 | /// |
1474 | class CallInst : public CallBase { |
1475 | CallInst(const CallInst &CI); |
1476 | |
1477 | /// Construct a CallInst given a range of arguments. |
1478 | /// Construct a CallInst from a range of arguments |
1479 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1480 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1481 | Instruction *InsertBefore); |
1482 | |
1483 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1484 | const Twine &NameStr, Instruction *InsertBefore) |
1485 | : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {} |
1486 | |
1487 | /// Construct a CallInst given a range of arguments. |
1488 | /// Construct a CallInst from a range of arguments |
1489 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1490 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1491 | BasicBlock *InsertAtEnd); |
1492 | |
1493 | explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr, |
1494 | Instruction *InsertBefore); |
1495 | |
1496 | CallInst(FunctionType *ty, Value *F, const Twine &NameStr, |
1497 | BasicBlock *InsertAtEnd); |
1498 | |
1499 | void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args, |
1500 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
1501 | void init(FunctionType *FTy, Value *Func, const Twine &NameStr); |
1502 | |
1503 | /// Compute the number of operands to allocate. |
1504 | static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) { |
1505 | // We need one operand for the called function, plus the input operand |
1506 | // counts provided. |
1507 | return 1 + NumArgs + NumBundleInputs; |
1508 | } |
1509 | |
1510 | protected: |
1511 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1512 | friend class Instruction; |
1513 | |
1514 | CallInst *cloneImpl() const; |
1515 | |
1516 | public: |
1517 | static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "", |
1518 | Instruction *InsertBefore = nullptr) { |
1519 | return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore); |
1520 | } |
1521 | |
1522 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1523 | const Twine &NameStr, |
1524 | Instruction *InsertBefore = nullptr) { |
1525 | return new (ComputeNumOperands(Args.size())) |
1526 | CallInst(Ty, Func, Args, None, NameStr, InsertBefore); |
1527 | } |
1528 | |
1529 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1530 | ArrayRef<OperandBundleDef> Bundles = None, |
1531 | const Twine &NameStr = "", |
1532 | Instruction *InsertBefore = nullptr) { |
1533 | const int NumOperands = |
1534 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
1535 | const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
1536 | |
1537 | return new (NumOperands, DescriptorBytes) |
1538 | CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore); |
1539 | } |
1540 | |
1541 | static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr, |
1542 | BasicBlock *InsertAtEnd) { |
1543 | return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd); |
1544 | } |
1545 | |
1546 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1547 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1548 | return new (ComputeNumOperands(Args.size())) |
1549 | CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd); |
1550 | } |
1551 | |
1552 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1553 | ArrayRef<OperandBundleDef> Bundles, |
1554 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1555 | const int NumOperands = |
1556 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
1557 | const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
1558 | |
1559 | return new (NumOperands, DescriptorBytes) |
1560 | CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd); |
1561 | } |
1562 | |
1563 | static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "", |
1564 | Instruction *InsertBefore = nullptr) { |
1565 | return Create(Func.getFunctionType(), Func.getCallee(), NameStr, |
1566 | InsertBefore); |
1567 | } |
1568 | |
1569 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1570 | ArrayRef<OperandBundleDef> Bundles = None, |
1571 | const Twine &NameStr = "", |
1572 | Instruction *InsertBefore = nullptr) { |
1573 | return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles, |
1574 | NameStr, InsertBefore); |
1575 | } |
1576 | |
1577 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1578 | const Twine &NameStr, |
1579 | Instruction *InsertBefore = nullptr) { |
1580 | return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr, |
1581 | InsertBefore); |
1582 | } |
1583 | |
1584 | static CallInst *Create(FunctionCallee Func, const Twine &NameStr, |
1585 | BasicBlock *InsertAtEnd) { |
1586 | return Create(Func.getFunctionType(), Func.getCallee(), NameStr, |
1587 | InsertAtEnd); |
1588 | } |
1589 | |
1590 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1591 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1592 | return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr, |
1593 | InsertAtEnd); |
1594 | } |
1595 | |
1596 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1597 | ArrayRef<OperandBundleDef> Bundles, |
1598 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1599 | return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles, |
1600 | NameStr, InsertAtEnd); |
1601 | } |
1602 | |
1603 | /// Create a clone of \p CI with a different set of operand bundles and |
1604 | /// insert it before \p InsertPt. |
1605 | /// |
1606 | /// The returned call instruction is identical \p CI in every way except that |
1607 | /// the operand bundles for the new instruction are set to the operand bundles |
1608 | /// in \p Bundles. |
1609 | static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles, |
1610 | Instruction *InsertPt = nullptr); |
1611 | |
1612 | /// Generate the IR for a call to malloc: |
1613 | /// 1. Compute the malloc call's argument as the specified type's size, |
1614 | /// possibly multiplied by the array size if the array size is not |
1615 | /// constant 1. |
1616 | /// 2. Call malloc with that argument. |
1617 | /// 3. Bitcast the result of the malloc call to the specified type. |
1618 | static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, |
1619 | Type *AllocTy, Value *AllocSize, |
1620 | Value *ArraySize = nullptr, |
1621 | Function *MallocF = nullptr, |
1622 | const Twine &Name = ""); |
1623 | static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy, |
1624 | Type *AllocTy, Value *AllocSize, |
1625 | Value *ArraySize = nullptr, |
1626 | Function *MallocF = nullptr, |
1627 | const Twine &Name = ""); |
1628 | static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, |
1629 | Type *AllocTy, Value *AllocSize, |
1630 | Value *ArraySize = nullptr, |
1631 | ArrayRef<OperandBundleDef> Bundles = None, |
1632 | Function *MallocF = nullptr, |
1633 | const Twine &Name = ""); |
1634 | static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy, |
1635 | Type *AllocTy, Value *AllocSize, |
1636 | Value *ArraySize = nullptr, |
1637 | ArrayRef<OperandBundleDef> Bundles = None, |
1638 | Function *MallocF = nullptr, |
1639 | const Twine &Name = ""); |
1640 | /// Generate the IR for a call to the builtin free function. |
1641 | static Instruction *CreateFree(Value *Source, Instruction *InsertBefore); |
1642 | static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd); |
1643 | static Instruction *CreateFree(Value *Source, |
1644 | ArrayRef<OperandBundleDef> Bundles, |
1645 | Instruction *InsertBefore); |
1646 | static Instruction *CreateFree(Value *Source, |
1647 | ArrayRef<OperandBundleDef> Bundles, |
1648 | BasicBlock *InsertAtEnd); |
1649 | |
1650 | // Note that 'musttail' implies 'tail'. |
1651 | enum TailCallKind : unsigned { |
1652 | TCK_None = 0, |
1653 | TCK_Tail = 1, |
1654 | TCK_MustTail = 2, |
1655 | TCK_NoTail = 3, |
1656 | TCK_LAST = TCK_NoTail |
1657 | }; |
1658 | |
1659 | using TailCallKindField = Bitfield::Element<TailCallKind, 0, 2, TCK_LAST>; |
1660 | static_assert( |
1661 | Bitfield::areContiguous<TailCallKindField, CallBase::CallingConvField>(), |
1662 | "Bitfields must be contiguous"); |
1663 | |
1664 | TailCallKind getTailCallKind() const { |
1665 | return getSubclassData<TailCallKindField>(); |
1666 | } |
1667 | |
1668 | bool isTailCall() const { |
1669 | TailCallKind Kind = getTailCallKind(); |
1670 | return Kind == TCK_Tail || Kind == TCK_MustTail; |
1671 | } |
1672 | |
1673 | bool isMustTailCall() const { return getTailCallKind() == TCK_MustTail; } |
1674 | |
1675 | bool isNoTailCall() const { return getTailCallKind() == TCK_NoTail; } |
1676 | |
1677 | void setTailCallKind(TailCallKind TCK) { |
1678 | setSubclassData<TailCallKindField>(TCK); |
1679 | } |
1680 | |
1681 | void setTailCall(bool IsTc = true) { |
1682 | setTailCallKind(IsTc ? TCK_Tail : TCK_None); |
1683 | } |
1684 | |
1685 | /// Return true if the call can return twice |
1686 | bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); } |
1687 | void setCanReturnTwice() { addFnAttr(Attribute::ReturnsTwice); } |
1688 | |
1689 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1690 | static bool classof(const Instruction *I) { |
1691 | return I->getOpcode() == Instruction::Call; |
1692 | } |
1693 | static bool classof(const Value *V) { |
1694 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1695 | } |
1696 | |
1697 | /// Updates profile metadata by scaling it by \p S / \p T. |
1698 | void updateProfWeight(uint64_t S, uint64_t T); |
1699 | |
1700 | private: |
1701 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
1702 | // method so that subclasses cannot accidentally use it. |
1703 | template <typename Bitfield> |
1704 | void setSubclassData(typename Bitfield::Type Value) { |
1705 | Instruction::setSubclassData<Bitfield>(Value); |
1706 | } |
1707 | }; |
1708 | |
1709 | CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1710 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1711 | BasicBlock *InsertAtEnd) |
1712 | : CallBase(Ty->getReturnType(), Instruction::Call, |
1713 | OperandTraits<CallBase>::op_end(this) - |
1714 | (Args.size() + CountBundleInputs(Bundles) + 1), |
1715 | unsigned(Args.size() + CountBundleInputs(Bundles) + 1), |
1716 | InsertAtEnd) { |
1717 | init(Ty, Func, Args, Bundles, NameStr); |
1718 | } |
1719 | |
1720 | CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1721 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1722 | Instruction *InsertBefore) |
1723 | : CallBase(Ty->getReturnType(), Instruction::Call, |
1724 | OperandTraits<CallBase>::op_end(this) - |
1725 | (Args.size() + CountBundleInputs(Bundles) + 1), |
1726 | unsigned(Args.size() + CountBundleInputs(Bundles) + 1), |
1727 | InsertBefore) { |
1728 | init(Ty, Func, Args, Bundles, NameStr); |
1729 | } |
1730 | |
1731 | //===----------------------------------------------------------------------===// |
1732 | // SelectInst Class |
1733 | //===----------------------------------------------------------------------===// |
1734 | |
1735 | /// This class represents the LLVM 'select' instruction. |
1736 | /// |
1737 | class SelectInst : public Instruction { |
1738 | SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr, |
1739 | Instruction *InsertBefore) |
1740 | : Instruction(S1->getType(), Instruction::Select, |
1741 | &Op<0>(), 3, InsertBefore) { |
1742 | init(C, S1, S2); |
1743 | setName(NameStr); |
1744 | } |
1745 | |
1746 | SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr, |
1747 | BasicBlock *InsertAtEnd) |
1748 | : Instruction(S1->getType(), Instruction::Select, |
1749 | &Op<0>(), 3, InsertAtEnd) { |
1750 | init(C, S1, S2); |
1751 | setName(NameStr); |
1752 | } |
1753 | |
1754 | void init(Value *C, Value *S1, Value *S2) { |
1755 | assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select")(static_cast <bool> (!areInvalidOperands(C, S1, S2) && "Invalid operands for select") ? void (0) : __assert_fail ("!areInvalidOperands(C, S1, S2) && \"Invalid operands for select\"" , "llvm/include/llvm/IR/Instructions.h", 1755, __extension__ __PRETTY_FUNCTION__ )); |
1756 | Op<0>() = C; |
1757 | Op<1>() = S1; |
1758 | Op<2>() = S2; |
1759 | } |
1760 | |
1761 | protected: |
1762 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1763 | friend class Instruction; |
1764 | |
1765 | SelectInst *cloneImpl() const; |
1766 | |
1767 | public: |
1768 | static SelectInst *Create(Value *C, Value *S1, Value *S2, |
1769 | const Twine &NameStr = "", |
1770 | Instruction *InsertBefore = nullptr, |
1771 | Instruction *MDFrom = nullptr) { |
1772 | SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore); |
1773 | if (MDFrom) |
1774 | Sel->copyMetadata(*MDFrom); |
1775 | return Sel; |
1776 | } |
1777 | |
1778 | static SelectInst *Create(Value *C, Value *S1, Value *S2, |
1779 | const Twine &NameStr, |
1780 | BasicBlock *InsertAtEnd) { |
1781 | return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd); |
1782 | } |
1783 | |
1784 | const Value *getCondition() const { return Op<0>(); } |
1785 | const Value *getTrueValue() const { return Op<1>(); } |
1786 | const Value *getFalseValue() const { return Op<2>(); } |
1787 | Value *getCondition() { return Op<0>(); } |
1788 | Value *getTrueValue() { return Op<1>(); } |
1789 | Value *getFalseValue() { return Op<2>(); } |
1790 | |
1791 | void setCondition(Value *V) { Op<0>() = V; } |
1792 | void setTrueValue(Value *V) { Op<1>() = V; } |
1793 | void setFalseValue(Value *V) { Op<2>() = V; } |
1794 | |
1795 | /// Swap the true and false values of the select instruction. |
1796 | /// This doesn't swap prof metadata. |
1797 | void swapValues() { Op<1>().swap(Op<2>()); } |
1798 | |
1799 | /// Return a string if the specified operands are invalid |
1800 | /// for a select operation, otherwise return null. |
1801 | static const char *areInvalidOperands(Value *Cond, Value *True, Value *False); |
1802 | |
1803 | /// Transparently provide more efficient getOperand methods. |
1804 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1805 | |
1806 | OtherOps getOpcode() const { |
1807 | return static_cast<OtherOps>(Instruction::getOpcode()); |
1808 | } |
1809 | |
1810 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1811 | static bool classof(const Instruction *I) { |
1812 | return I->getOpcode() == Instruction::Select; |
1813 | } |
1814 | static bool classof(const Value *V) { |
1815 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1816 | } |
1817 | }; |
1818 | |
1819 | template <> |
1820 | struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> { |
1821 | }; |
1822 | |
1823 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)SelectInst::op_iterator SelectInst::op_begin() { return OperandTraits <SelectInst>::op_begin(this); } SelectInst::const_op_iterator SelectInst::op_begin() const { return OperandTraits<SelectInst >::op_begin(const_cast<SelectInst*>(this)); } SelectInst ::op_iterator SelectInst::op_end() { return OperandTraits< SelectInst>::op_end(this); } SelectInst::const_op_iterator SelectInst::op_end() const { return OperandTraits<SelectInst >::op_end(const_cast<SelectInst*>(this)); } Value *SelectInst ::getOperand(unsigned i_nocapture) const { (static_cast <bool > (i_nocapture < OperandTraits<SelectInst>::operands (this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 1823, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<SelectInst >::op_begin(const_cast<SelectInst*>(this))[i_nocapture ].get()); } void SelectInst::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<SelectInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 1823, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<SelectInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned SelectInst::getNumOperands() const { return OperandTraits<SelectInst>::operands(this); } template <int Idx_nocapture> Use &SelectInst::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &SelectInst::Op() const { return this->OpFrom<Idx_nocapture>(this); } |
1824 | |
1825 | //===----------------------------------------------------------------------===// |
1826 | // VAArgInst Class |
1827 | //===----------------------------------------------------------------------===// |
1828 | |
1829 | /// This class represents the va_arg llvm instruction, which returns |
1830 | /// an argument of the specified type given a va_list and increments that list |
1831 | /// |
1832 | class VAArgInst : public UnaryInstruction { |
1833 | protected: |
1834 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1835 | friend class Instruction; |
1836 | |
1837 | VAArgInst *cloneImpl() const; |
1838 | |
1839 | public: |
1840 | VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "", |
1841 | Instruction *InsertBefore = nullptr) |
1842 | : UnaryInstruction(Ty, VAArg, List, InsertBefore) { |
1843 | setName(NameStr); |
1844 | } |
1845 | |
1846 | VAArgInst(Value *List, Type *Ty, const Twine &NameStr, |
1847 | BasicBlock *InsertAtEnd) |
1848 | : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) { |
1849 | setName(NameStr); |
1850 | } |
1851 | |
1852 | Value *getPointerOperand() { return getOperand(0); } |
1853 | const Value *getPointerOperand() const { return getOperand(0); } |
1854 | static unsigned getPointerOperandIndex() { return 0U; } |
1855 | |
1856 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1857 | static bool classof(const Instruction *I) { |
1858 | return I->getOpcode() == VAArg; |
1859 | } |
1860 | static bool classof(const Value *V) { |
1861 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1862 | } |
1863 | }; |
1864 | |
1865 | //===----------------------------------------------------------------------===// |
1866 | // ExtractElementInst Class |
1867 | //===----------------------------------------------------------------------===// |
1868 | |
1869 | /// This instruction extracts a single (scalar) |
1870 | /// element from a VectorType value |
1871 | /// |
1872 | class ExtractElementInst : public Instruction { |
1873 | ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "", |
1874 | Instruction *InsertBefore = nullptr); |
1875 | ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr, |
1876 | BasicBlock *InsertAtEnd); |
1877 | |
1878 | protected: |
1879 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1880 | friend class Instruction; |
1881 | |
1882 | ExtractElementInst *cloneImpl() const; |
1883 | |
1884 | public: |
1885 | static ExtractElementInst *Create(Value *Vec, Value *Idx, |
1886 | const Twine &NameStr = "", |
1887 | Instruction *InsertBefore = nullptr) { |
1888 | return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore); |
1889 | } |
1890 | |
1891 | static ExtractElementInst *Create(Value *Vec, Value *Idx, |
1892 | const Twine &NameStr, |
1893 | BasicBlock *InsertAtEnd) { |
1894 | return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd); |
1895 | } |
1896 | |
1897 | /// Return true if an extractelement instruction can be |
1898 | /// formed with the specified operands. |
1899 | static bool isValidOperands(const Value *Vec, const Value *Idx); |
1900 | |
1901 | Value *getVectorOperand() { return Op<0>(); } |
1902 | Value *getIndexOperand() { return Op<1>(); } |
1903 | const Value *getVectorOperand() const { return Op<0>(); } |
1904 | const Value *getIndexOperand() const { return Op<1>(); } |
1905 | |
1906 | VectorType *getVectorOperandType() const { |
1907 | return cast<VectorType>(getVectorOperand()->getType()); |
1908 | } |
1909 | |
1910 | /// Transparently provide more efficient getOperand methods. |
1911 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1912 | |
1913 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1914 | static bool classof(const Instruction *I) { |
1915 | return I->getOpcode() == Instruction::ExtractElement; |
1916 | } |
1917 | static bool classof(const Value *V) { |
1918 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1919 | } |
1920 | }; |
1921 | |
1922 | template <> |
1923 | struct OperandTraits<ExtractElementInst> : |
1924 | public FixedNumOperandTraits<ExtractElementInst, 2> { |
1925 | }; |
1926 | |
1927 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)ExtractElementInst::op_iterator ExtractElementInst::op_begin( ) { return OperandTraits<ExtractElementInst>::op_begin( this); } ExtractElementInst::const_op_iterator ExtractElementInst ::op_begin() const { return OperandTraits<ExtractElementInst >::op_begin(const_cast<ExtractElementInst*>(this)); } ExtractElementInst::op_iterator ExtractElementInst::op_end() { return OperandTraits<ExtractElementInst>::op_end(this ); } ExtractElementInst::const_op_iterator ExtractElementInst ::op_end() const { return OperandTraits<ExtractElementInst >::op_end(const_cast<ExtractElementInst*>(this)); } Value *ExtractElementInst::getOperand(unsigned i_nocapture) const { (static_cast <bool> (i_nocapture < OperandTraits< ExtractElementInst>::operands(this) && "getOperand() out of range!" ) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 1927, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<ExtractElementInst >::op_begin(const_cast<ExtractElementInst*>(this))[i_nocapture ].get()); } void ExtractElementInst::setOperand(unsigned i_nocapture , Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 1927, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<ExtractElementInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned ExtractElementInst::getNumOperands () const { return OperandTraits<ExtractElementInst>::operands (this); } template <int Idx_nocapture> Use &ExtractElementInst ::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &ExtractElementInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
1928 | |
1929 | //===----------------------------------------------------------------------===// |
1930 | // InsertElementInst Class |
1931 | //===----------------------------------------------------------------------===// |
1932 | |
1933 | /// This instruction inserts a single (scalar) |
1934 | /// element into a VectorType value |
1935 | /// |
1936 | class InsertElementInst : public Instruction { |
1937 | InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, |
1938 | const Twine &NameStr = "", |
1939 | Instruction *InsertBefore = nullptr); |
1940 | InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr, |
1941 | BasicBlock *InsertAtEnd); |
1942 | |
1943 | protected: |
1944 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1945 | friend class Instruction; |
1946 | |
1947 | InsertElementInst *cloneImpl() const; |
1948 | |
1949 | public: |
1950 | static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx, |
1951 | const Twine &NameStr = "", |
1952 | Instruction *InsertBefore = nullptr) { |
1953 | return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore); |
1954 | } |
1955 | |
1956 | static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx, |
1957 | const Twine &NameStr, |
1958 | BasicBlock *InsertAtEnd) { |
1959 | return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd); |
1960 | } |
1961 | |
1962 | /// Return true if an insertelement instruction can be |
1963 | /// formed with the specified operands. |
1964 | static bool isValidOperands(const Value *Vec, const Value *NewElt, |
1965 | const Value *Idx); |
1966 | |
1967 | /// Overload to return most specific vector type. |
1968 | /// |
1969 | VectorType *getType() const { |
1970 | return cast<VectorType>(Instruction::getType()); |
1971 | } |
1972 | |
1973 | /// Transparently provide more efficient getOperand methods. |
1974 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1975 | |
1976 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1977 | static bool classof(const Instruction *I) { |
1978 | return I->getOpcode() == Instruction::InsertElement; |
1979 | } |
1980 | static bool classof(const Value *V) { |
1981 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1982 | } |
1983 | }; |
1984 | |
1985 | template <> |
1986 | struct OperandTraits<InsertElementInst> : |
1987 | public FixedNumOperandTraits<InsertElementInst, 3> { |
1988 | }; |
1989 | |
1990 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)InsertElementInst::op_iterator InsertElementInst::op_begin() { return OperandTraits<InsertElementInst>::op_begin(this ); } InsertElementInst::const_op_iterator InsertElementInst:: op_begin() const { return OperandTraits<InsertElementInst> ::op_begin(const_cast<InsertElementInst*>(this)); } InsertElementInst ::op_iterator InsertElementInst::op_end() { return OperandTraits <InsertElementInst>::op_end(this); } InsertElementInst:: const_op_iterator InsertElementInst::op_end() const { return OperandTraits <InsertElementInst>::op_end(const_cast<InsertElementInst *>(this)); } Value *InsertElementInst::getOperand(unsigned i_nocapture) const { (static_cast <bool> (i_nocapture < OperandTraits<InsertElementInst>::operands(this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 1990, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<InsertElementInst >::op_begin(const_cast<InsertElementInst*>(this))[i_nocapture ].get()); } void InsertElementInst::setOperand(unsigned i_nocapture , Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<InsertElementInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 1990, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<InsertElementInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned InsertElementInst::getNumOperands () const { return OperandTraits<InsertElementInst>::operands (this); } template <int Idx_nocapture> Use &InsertElementInst ::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &InsertElementInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
1991 | |
1992 | //===----------------------------------------------------------------------===// |
1993 | // ShuffleVectorInst Class |
1994 | //===----------------------------------------------------------------------===// |
1995 | |
1996 | constexpr int UndefMaskElem = -1; |
1997 | |
1998 | /// This instruction constructs a fixed permutation of two |
1999 | /// input vectors. |
2000 | /// |
2001 | /// For each element of the result vector, the shuffle mask selects an element |
2002 | /// from one of the input vectors to copy to the result. Non-negative elements |
2003 | /// in the mask represent an index into the concatenated pair of input vectors. |
2004 | /// UndefMaskElem (-1) specifies that the result element is undefined. |
2005 | /// |
2006 | /// For scalable vectors, all the elements of the mask must be 0 or -1. This |
2007 | /// requirement may be relaxed in the future. |
2008 | class ShuffleVectorInst : public Instruction { |
2009 | SmallVector<int, 4> ShuffleMask; |
2010 | Constant *ShuffleMaskForBitcode; |
2011 | |
2012 | protected: |
2013 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2014 | friend class Instruction; |
2015 | |
2016 | ShuffleVectorInst *cloneImpl() const; |
2017 | |
2018 | public: |
2019 | ShuffleVectorInst(Value *V1, Value *Mask, const Twine &NameStr = "", |
2020 | Instruction *InsertBefore = nullptr); |
2021 | ShuffleVectorInst(Value *V1, Value *Mask, const Twine &NameStr, |
2022 | BasicBlock *InsertAtEnd); |
2023 | ShuffleVectorInst(Value *V1, ArrayRef<int> Mask, const Twine &NameStr = "", |
2024 | Instruction *InsertBefore = nullptr); |
2025 | ShuffleVectorInst(Value *V1, ArrayRef<int> Mask, const Twine &NameStr, |
2026 | BasicBlock *InsertAtEnd); |
2027 | ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, |
2028 | const Twine &NameStr = "", |
2029 | Instruction *InsertBefor = nullptr); |
2030 | ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, |
2031 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2032 | ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, |
2033 | const Twine &NameStr = "", |
2034 | Instruction *InsertBefor = nullptr); |
2035 | ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, |
2036 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2037 | |
2038 | void *operator new(size_t S) { return User::operator new(S, 2); } |
2039 | void operator delete(void *Ptr) { return User::operator delete(Ptr); } |
2040 | |
2041 | /// Swap the operands and adjust the mask to preserve the semantics |
2042 | /// of the instruction. |
2043 | void commute(); |
2044 | |
2045 | /// Return true if a shufflevector instruction can be |
2046 | /// formed with the specified operands. |
2047 | static bool isValidOperands(const Value *V1, const Value *V2, |
2048 | const Value *Mask); |
2049 | static bool isValidOperands(const Value *V1, const Value *V2, |
2050 | ArrayRef<int> Mask); |
2051 | |
2052 | /// Overload to return most specific vector type. |
2053 | /// |
2054 | VectorType *getType() const { |
2055 | return cast<VectorType>(Instruction::getType()); |
2056 | } |
2057 | |
2058 | /// Transparently provide more efficient getOperand methods. |
2059 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2060 | |
2061 | /// Return the shuffle mask value of this instruction for the given element |
2062 | /// index. Return UndefMaskElem if the element is undef. |
2063 | int getMaskValue(unsigned Elt) const { return ShuffleMask[Elt]; } |
2064 | |
2065 | /// Convert the input shuffle mask operand to a vector of integers. Undefined |
2066 | /// elements of the mask are returned as UndefMaskElem. |
2067 | static void getShuffleMask(const Constant *Mask, |
2068 | SmallVectorImpl<int> &Result); |
2069 | |
2070 | /// Return the mask for this instruction as a vector of integers. Undefined |
2071 | /// elements of the mask are returned as UndefMaskElem. |
2072 | void getShuffleMask(SmallVectorImpl<int> &Result) const { |
2073 | Result.assign(ShuffleMask.begin(), ShuffleMask.end()); |
2074 | } |
2075 | |
2076 | /// Return the mask for this instruction, for use in bitcode. |
2077 | /// |
2078 | /// TODO: This is temporary until we decide a new bitcode encoding for |
2079 | /// shufflevector. |
2080 | Constant *getShuffleMaskForBitcode() const { return ShuffleMaskForBitcode; } |
2081 | |
2082 | static Constant *convertShuffleMaskForBitcode(ArrayRef<int> Mask, |
2083 | Type *ResultTy); |
2084 | |
2085 | void setShuffleMask(ArrayRef<int> Mask); |
2086 | |
2087 | ArrayRef<int> getShuffleMask() const { return ShuffleMask; } |
2088 | |
2089 | /// Return true if this shuffle returns a vector with a different number of |
2090 | /// elements than its source vectors. |
2091 | /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3> |
2092 | /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5> |
2093 | bool changesLength() const { |
2094 | unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType()) |
2095 | ->getElementCount() |
2096 | .getKnownMinValue(); |
2097 | unsigned NumMaskElts = ShuffleMask.size(); |
2098 | return NumSourceElts != NumMaskElts; |
2099 | } |
2100 | |
2101 | /// Return true if this shuffle returns a vector with a greater number of |
2102 | /// elements than its source vectors. |
2103 | /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3> |
2104 | bool increasesLength() const { |
2105 | unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType()) |
2106 | ->getElementCount() |
2107 | .getKnownMinValue(); |
2108 | unsigned NumMaskElts = ShuffleMask.size(); |
2109 | return NumSourceElts < NumMaskElts; |
2110 | } |
2111 | |
2112 | /// Return true if this shuffle mask chooses elements from exactly one source |
2113 | /// vector. |
2114 | /// Example: <7,5,undef,7> |
2115 | /// This assumes that vector operands are the same length as the mask. |
2116 | static bool isSingleSourceMask(ArrayRef<int> Mask); |
2117 | static bool isSingleSourceMask(const Constant *Mask) { |
2118 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy( ) && "Shuffle needs vector constant.") ? void (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "llvm/include/llvm/IR/Instructions.h", 2118, __extension__ __PRETTY_FUNCTION__ )); |
2119 | SmallVector<int, 16> MaskAsInts; |
2120 | getShuffleMask(Mask, MaskAsInts); |
2121 | return isSingleSourceMask(MaskAsInts); |
2122 | } |
2123 | |
2124 | /// Return true if this shuffle chooses elements from exactly one source |
2125 | /// vector without changing the length of that vector. |
2126 | /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3> |
2127 | /// TODO: Optionally allow length-changing shuffles. |
2128 | bool isSingleSource() const { |
2129 | return !changesLength() && isSingleSourceMask(ShuffleMask); |
2130 | } |
2131 | |
2132 | /// Return true if this shuffle mask chooses elements from exactly one source |
2133 | /// vector without lane crossings. A shuffle using this mask is not |
2134 | /// necessarily a no-op because it may change the number of elements from its |
2135 | /// input vectors or it may provide demanded bits knowledge via undef lanes. |
2136 | /// Example: <undef,undef,2,3> |
2137 | static bool isIdentityMask(ArrayRef<int> Mask); |
2138 | static bool isIdentityMask(const Constant *Mask) { |
2139 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy( ) && "Shuffle needs vector constant.") ? void (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "llvm/include/llvm/IR/Instructions.h", 2139, __extension__ __PRETTY_FUNCTION__ )); |
2140 | SmallVector<int, 16> MaskAsInts; |
2141 | getShuffleMask(Mask, MaskAsInts); |
2142 | return isIdentityMask(MaskAsInts); |
2143 | } |
2144 | |
2145 | /// Return true if this shuffle chooses elements from exactly one source |
2146 | /// vector without lane crossings and does not change the number of elements |
2147 | /// from its input vectors. |
2148 | /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef> |
2149 | bool isIdentity() const { |
2150 | return !changesLength() && isIdentityMask(ShuffleMask); |
2151 | } |
2152 | |
2153 | /// Return true if this shuffle lengthens exactly one source vector with |
2154 | /// undefs in the high elements. |
2155 | bool isIdentityWithPadding() const; |
2156 | |
2157 | /// Return true if this shuffle extracts the first N elements of exactly one |
2158 | /// source vector. |
2159 | bool isIdentityWithExtract() const; |
2160 | |
2161 | /// Return true if this shuffle concatenates its 2 source vectors. This |
2162 | /// returns false if either input is undefined. In that case, the shuffle is |
2163 | /// is better classified as an identity with padding operation. |
2164 | bool isConcat() const; |
2165 | |
2166 | /// Return true if this shuffle mask chooses elements from its source vectors |
2167 | /// without lane crossings. A shuffle using this mask would be |
2168 | /// equivalent to a vector select with a constant condition operand. |
2169 | /// Example: <4,1,6,undef> |
2170 | /// This returns false if the mask does not choose from both input vectors. |
2171 | /// In that case, the shuffle is better classified as an identity shuffle. |
2172 | /// This assumes that vector operands are the same length as the mask |
2173 | /// (a length-changing shuffle can never be equivalent to a vector select). |
2174 | static bool isSelectMask(ArrayRef<int> Mask); |
2175 | static bool isSelectMask(const Constant *Mask) { |
2176 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy( ) && "Shuffle needs vector constant.") ? void (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "llvm/include/llvm/IR/Instructions.h", 2176, __extension__ __PRETTY_FUNCTION__ )); |
2177 | SmallVector<int, 16> MaskAsInts; |
2178 | getShuffleMask(Mask, MaskAsInts); |
2179 | return isSelectMask(MaskAsInts); |
2180 | } |
2181 | |
2182 | /// Return true if this shuffle chooses elements from its source vectors |
2183 | /// without lane crossings and all operands have the same number of elements. |
2184 | /// In other words, this shuffle is equivalent to a vector select with a |
2185 | /// constant condition operand. |
2186 | /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3> |
2187 | /// This returns false if the mask does not choose from both input vectors. |
2188 | /// In that case, the shuffle is better classified as an identity shuffle. |
2189 | /// TODO: Optionally allow length-changing shuffles. |
2190 | bool isSelect() const { |
2191 | return !changesLength() && isSelectMask(ShuffleMask); |
2192 | } |
2193 | |
2194 | /// Return true if this shuffle mask swaps the order of elements from exactly |
2195 | /// one source vector. |
2196 | /// Example: <7,6,undef,4> |
2197 | /// This assumes that vector operands are the same length as the mask. |
2198 | static bool isReverseMask(ArrayRef<int> Mask); |
2199 | static bool isReverseMask(const Constant *Mask) { |
2200 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy( ) && "Shuffle needs vector constant.") ? void (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "llvm/include/llvm/IR/Instructions.h", 2200, __extension__ __PRETTY_FUNCTION__ )); |
2201 | SmallVector<int, 16> MaskAsInts; |
2202 | getShuffleMask(Mask, MaskAsInts); |
2203 | return isReverseMask(MaskAsInts); |
2204 | } |
2205 | |
2206 | /// Return true if this shuffle swaps the order of elements from exactly |
2207 | /// one source vector. |
2208 | /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef> |
2209 | /// TODO: Optionally allow length-changing shuffles. |
2210 | bool isReverse() const { |
2211 | return !changesLength() && isReverseMask(ShuffleMask); |
2212 | } |
2213 | |
2214 | /// Return true if this shuffle mask chooses all elements with the same value |
2215 | /// as the first element of exactly one source vector. |
2216 | /// Example: <4,undef,undef,4> |
2217 | /// This assumes that vector operands are the same length as the mask. |
2218 | static bool isZeroEltSplatMask(ArrayRef<int> Mask); |
2219 | static bool isZeroEltSplatMask(const Constant *Mask) { |
2220 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy( ) && "Shuffle needs vector constant.") ? void (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "llvm/include/llvm/IR/Instructions.h", 2220, __extension__ __PRETTY_FUNCTION__ )); |
2221 | SmallVector<int, 16> MaskAsInts; |
2222 | getShuffleMask(Mask, MaskAsInts); |
2223 | return isZeroEltSplatMask(MaskAsInts); |
2224 | } |
2225 | |
2226 | /// Return true if all elements of this shuffle are the same value as the |
2227 | /// first element of exactly one source vector without changing the length |
2228 | /// of that vector. |
2229 | /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0> |
2230 | /// TODO: Optionally allow length-changing shuffles. |
2231 | /// TODO: Optionally allow splats from other elements. |
2232 | bool isZeroEltSplat() const { |
2233 | return !changesLength() && isZeroEltSplatMask(ShuffleMask); |
2234 | } |
2235 | |
2236 | /// Return true if this shuffle mask is a transpose mask. |
2237 | /// Transpose vector masks transpose a 2xn matrix. They read corresponding |
2238 | /// even- or odd-numbered vector elements from two n-dimensional source |
2239 | /// vectors and write each result into consecutive elements of an |
2240 | /// n-dimensional destination vector. Two shuffles are necessary to complete |
2241 | /// the transpose, one for the even elements and another for the odd elements. |
2242 | /// This description closely follows how the TRN1 and TRN2 AArch64 |
2243 | /// instructions operate. |
2244 | /// |
2245 | /// For example, a simple 2x2 matrix can be transposed with: |
2246 | /// |
2247 | /// ; Original matrix |
2248 | /// m0 = < a, b > |
2249 | /// m1 = < c, d > |
2250 | /// |
2251 | /// ; Transposed matrix |
2252 | /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 > |
2253 | /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 > |
2254 | /// |
2255 | /// For matrices having greater than n columns, the resulting nx2 transposed |
2256 | /// matrix is stored in two result vectors such that one vector contains |
2257 | /// interleaved elements from all the even-numbered rows and the other vector |
2258 | /// contains interleaved elements from all the odd-numbered rows. For example, |
2259 | /// a 2x4 matrix can be transposed with: |
2260 | /// |
2261 | /// ; Original matrix |
2262 | /// m0 = < a, b, c, d > |
2263 | /// m1 = < e, f, g, h > |
2264 | /// |
2265 | /// ; Transposed matrix |
2266 | /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 > |
2267 | /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 > |
2268 | static bool isTransposeMask(ArrayRef<int> Mask); |
2269 | static bool isTransposeMask(const Constant *Mask) { |
2270 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy( ) && "Shuffle needs vector constant.") ? void (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "llvm/include/llvm/IR/Instructions.h", 2270, __extension__ __PRETTY_FUNCTION__ )); |
2271 | SmallVector<int, 16> MaskAsInts; |
2272 | getShuffleMask(Mask, MaskAsInts); |
2273 | return isTransposeMask(MaskAsInts); |
2274 | } |
2275 | |
2276 | /// Return true if this shuffle transposes the elements of its inputs without |
2277 | /// changing the length of the vectors. This operation may also be known as a |
2278 | /// merge or interleave. See the description for isTransposeMask() for the |
2279 | /// exact specification. |
2280 | /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6> |
2281 | bool isTranspose() const { |
2282 | return !changesLength() && isTransposeMask(ShuffleMask); |
2283 | } |
2284 | |
2285 | /// Return true if this shuffle mask is an extract subvector mask. |
2286 | /// A valid extract subvector mask returns a smaller vector from a single |
2287 | /// source operand. The base extraction index is returned as well. |
2288 | static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts, |
2289 | int &Index); |
2290 | static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts, |
2291 | int &Index) { |
2292 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy( ) && "Shuffle needs vector constant.") ? void (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "llvm/include/llvm/IR/Instructions.h", 2292, __extension__ __PRETTY_FUNCTION__ )); |
2293 | // Not possible to express a shuffle mask for a scalable vector for this |
2294 | // case. |
2295 | if (isa<ScalableVectorType>(Mask->getType())) |
2296 | return false; |
2297 | SmallVector<int, 16> MaskAsInts; |
2298 | getShuffleMask(Mask, MaskAsInts); |
2299 | return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index); |
2300 | } |
2301 | |
2302 | /// Return true if this shuffle mask is an extract subvector mask. |
2303 | bool isExtractSubvectorMask(int &Index) const { |
2304 | // Not possible to express a shuffle mask for a scalable vector for this |
2305 | // case. |
2306 | if (isa<ScalableVectorType>(getType())) |
2307 | return false; |
2308 | |
2309 | int NumSrcElts = |
2310 | cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); |
2311 | return isExtractSubvectorMask(ShuffleMask, NumSrcElts, Index); |
2312 | } |
2313 | |
2314 | /// Return true if this shuffle mask is an insert subvector mask. |
2315 | /// A valid insert subvector mask inserts the lowest elements of a second |
2316 | /// source operand into an in-place first source operand operand. |
2317 | /// Both the sub vector width and the insertion index is returned. |
2318 | static bool isInsertSubvectorMask(ArrayRef<int> Mask, int NumSrcElts, |
2319 | int &NumSubElts, int &Index); |
2320 | static bool isInsertSubvectorMask(const Constant *Mask, int NumSrcElts, |
2321 | int &NumSubElts, int &Index) { |
2322 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy( ) && "Shuffle needs vector constant.") ? void (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "llvm/include/llvm/IR/Instructions.h", 2322, __extension__ __PRETTY_FUNCTION__ )); |
2323 | // Not possible to express a shuffle mask for a scalable vector for this |
2324 | // case. |
2325 | if (isa<ScalableVectorType>(Mask->getType())) |
2326 | return false; |
2327 | SmallVector<int, 16> MaskAsInts; |
2328 | getShuffleMask(Mask, MaskAsInts); |
2329 | return isInsertSubvectorMask(MaskAsInts, NumSrcElts, NumSubElts, Index); |
2330 | } |
2331 | |
2332 | /// Return true if this shuffle mask is an insert subvector mask. |
2333 | bool isInsertSubvectorMask(int &NumSubElts, int &Index) const { |
2334 | // Not possible to express a shuffle mask for a scalable vector for this |
2335 | // case. |
2336 | if (isa<ScalableVectorType>(getType())) |
2337 | return false; |
2338 | |
2339 | int NumSrcElts = |
2340 | cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); |
2341 | return isInsertSubvectorMask(ShuffleMask, NumSrcElts, NumSubElts, Index); |
2342 | } |
2343 | |
2344 | /// Return true if this shuffle mask replicates each of the \p VF elements |
2345 | /// in a vector \p ReplicationFactor times. |
2346 | /// For example, the mask for \p ReplicationFactor=3 and \p VF=4 is: |
2347 | /// <0,0,0,1,1,1,2,2,2,3,3,3> |
2348 | static bool isReplicationMask(ArrayRef<int> Mask, int &ReplicationFactor, |
2349 | int &VF); |
2350 | static bool isReplicationMask(const Constant *Mask, int &ReplicationFactor, |
2351 | int &VF) { |
2352 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")(static_cast <bool> (Mask->getType()->isVectorTy( ) && "Shuffle needs vector constant.") ? void (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "llvm/include/llvm/IR/Instructions.h", 2352, __extension__ __PRETTY_FUNCTION__ )); |
2353 | // Not possible to express a shuffle mask for a scalable vector for this |
2354 | // case. |
2355 | if (isa<ScalableVectorType>(Mask->getType())) |
2356 | return false; |
2357 | SmallVector<int, 16> MaskAsInts; |
2358 | getShuffleMask(Mask, MaskAsInts); |
2359 | return isReplicationMask(MaskAsInts, ReplicationFactor, VF); |
2360 | } |
2361 | |
2362 | /// Return true if this shuffle mask is a replication mask. |
2363 | bool isReplicationMask(int &ReplicationFactor, int &VF) const; |
2364 | |
2365 | /// Change values in a shuffle permute mask assuming the two vector operands |
2366 | /// of length InVecNumElts have swapped position. |
2367 | static void commuteShuffleMask(MutableArrayRef<int> Mask, |
2368 | unsigned InVecNumElts) { |
2369 | for (int &Idx : Mask) { |
2370 | if (Idx == -1) |
2371 | continue; |
2372 | Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts; |
2373 | assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&(static_cast <bool> (Idx >= 0 && Idx < (int )InVecNumElts * 2 && "shufflevector mask index out of range" ) ? void (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\"" , "llvm/include/llvm/IR/Instructions.h", 2374, __extension__ __PRETTY_FUNCTION__ )) |
2374 | "shufflevector mask index out of range")(static_cast <bool> (Idx >= 0 && Idx < (int )InVecNumElts * 2 && "shufflevector mask index out of range" ) ? void (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\"" , "llvm/include/llvm/IR/Instructions.h", 2374, __extension__ __PRETTY_FUNCTION__ )); |
2375 | } |
2376 | } |
2377 | |
2378 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2379 | static bool classof(const Instruction *I) { |
2380 | return I->getOpcode() == Instruction::ShuffleVector; |
2381 | } |
2382 | static bool classof(const Value *V) { |
2383 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2384 | } |
2385 | }; |
2386 | |
2387 | template <> |
2388 | struct OperandTraits<ShuffleVectorInst> |
2389 | : public FixedNumOperandTraits<ShuffleVectorInst, 2> {}; |
2390 | |
2391 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)ShuffleVectorInst::op_iterator ShuffleVectorInst::op_begin() { return OperandTraits<ShuffleVectorInst>::op_begin(this ); } ShuffleVectorInst::const_op_iterator ShuffleVectorInst:: op_begin() const { return OperandTraits<ShuffleVectorInst> ::op_begin(const_cast<ShuffleVectorInst*>(this)); } ShuffleVectorInst ::op_iterator ShuffleVectorInst::op_end() { return OperandTraits <ShuffleVectorInst>::op_end(this); } ShuffleVectorInst:: const_op_iterator ShuffleVectorInst::op_end() const { return OperandTraits <ShuffleVectorInst>::op_end(const_cast<ShuffleVectorInst *>(this)); } Value *ShuffleVectorInst::getOperand(unsigned i_nocapture) const { (static_cast <bool> (i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 2391, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<ShuffleVectorInst >::op_begin(const_cast<ShuffleVectorInst*>(this))[i_nocapture ].get()); } void ShuffleVectorInst::setOperand(unsigned i_nocapture , Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 2391, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<ShuffleVectorInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned ShuffleVectorInst::getNumOperands () const { return OperandTraits<ShuffleVectorInst>::operands (this); } template <int Idx_nocapture> Use &ShuffleVectorInst ::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &ShuffleVectorInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
2392 | |
2393 | //===----------------------------------------------------------------------===// |
2394 | // ExtractValueInst Class |
2395 | //===----------------------------------------------------------------------===// |
2396 | |
2397 | /// This instruction extracts a struct member or array |
2398 | /// element value from an aggregate value. |
2399 | /// |
2400 | class ExtractValueInst : public UnaryInstruction { |
2401 | SmallVector<unsigned, 4> Indices; |
2402 | |
2403 | ExtractValueInst(const ExtractValueInst &EVI); |
2404 | |
2405 | /// Constructors - Create a extractvalue instruction with a base aggregate |
2406 | /// value and a list of indices. The first ctor can optionally insert before |
2407 | /// an existing instruction, the second appends the new instruction to the |
2408 | /// specified BasicBlock. |
2409 | inline ExtractValueInst(Value *Agg, |
2410 | ArrayRef<unsigned> Idxs, |
2411 | const Twine &NameStr, |
2412 | Instruction *InsertBefore); |
2413 | inline ExtractValueInst(Value *Agg, |
2414 | ArrayRef<unsigned> Idxs, |
2415 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2416 | |
2417 | void init(ArrayRef<unsigned> Idxs, const Twine &NameStr); |
2418 | |
2419 | protected: |
2420 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2421 | friend class Instruction; |
2422 | |
2423 | ExtractValueInst *cloneImpl() const; |
2424 | |
2425 | public: |
2426 | static ExtractValueInst *Create(Value *Agg, |
2427 | ArrayRef<unsigned> Idxs, |
2428 | const Twine &NameStr = "", |
2429 | Instruction *InsertBefore = nullptr) { |
2430 | return new |
2431 | ExtractValueInst(Agg, Idxs, NameStr, InsertBefore); |
2432 | } |
2433 | |
2434 | static ExtractValueInst *Create(Value *Agg, |
2435 | ArrayRef<unsigned> Idxs, |
2436 | const Twine &NameStr, |
2437 | BasicBlock *InsertAtEnd) { |
2438 | return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd); |
2439 | } |
2440 | |
2441 | /// Returns the type of the element that would be extracted |
2442 | /// with an extractvalue instruction with the specified parameters. |
2443 | /// |
2444 | /// Null is returned if the indices are invalid for the specified type. |
2445 | static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs); |
2446 | |
2447 | using idx_iterator = const unsigned*; |
2448 | |
2449 | inline idx_iterator idx_begin() const { return Indices.begin(); } |
2450 | inline idx_iterator idx_end() const { return Indices.end(); } |
2451 | inline iterator_range<idx_iterator> indices() const { |
2452 | return make_range(idx_begin(), idx_end()); |
2453 | } |
2454 | |
2455 | Value *getAggregateOperand() { |
2456 | return getOperand(0); |
2457 | } |
2458 | const Value *getAggregateOperand() const { |
2459 | return getOperand(0); |
2460 | } |
2461 | static unsigned getAggregateOperandIndex() { |
2462 | return 0U; // get index for modifying correct operand |
2463 | } |
2464 | |
2465 | ArrayRef<unsigned> getIndices() const { |
2466 | return Indices; |
2467 | } |
2468 | |
2469 | unsigned getNumIndices() const { |
2470 | return (unsigned)Indices.size(); |
2471 | } |
2472 | |
2473 | bool hasIndices() const { |
2474 | return true; |
2475 | } |
2476 | |
2477 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2478 | static bool classof(const Instruction *I) { |
2479 | return I->getOpcode() == Instruction::ExtractValue; |
2480 | } |
2481 | static bool classof(const Value *V) { |
2482 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2483 | } |
2484 | }; |
2485 | |
2486 | ExtractValueInst::ExtractValueInst(Value *Agg, |
2487 | ArrayRef<unsigned> Idxs, |
2488 | const Twine &NameStr, |
2489 | Instruction *InsertBefore) |
2490 | : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)), |
2491 | ExtractValue, Agg, InsertBefore) { |
2492 | init(Idxs, NameStr); |
2493 | } |
2494 | |
2495 | ExtractValueInst::ExtractValueInst(Value *Agg, |
2496 | ArrayRef<unsigned> Idxs, |
2497 | const Twine &NameStr, |
2498 | BasicBlock *InsertAtEnd) |
2499 | : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)), |
2500 | ExtractValue, Agg, InsertAtEnd) { |
2501 | init(Idxs, NameStr); |
2502 | } |
2503 | |
2504 | //===----------------------------------------------------------------------===// |
2505 | // InsertValueInst Class |
2506 | //===----------------------------------------------------------------------===// |
2507 | |
2508 | /// This instruction inserts a struct field of array element |
2509 | /// value into an aggregate value. |
2510 | /// |
2511 | class InsertValueInst : public Instruction { |
2512 | SmallVector<unsigned, 4> Indices; |
2513 | |
2514 | InsertValueInst(const InsertValueInst &IVI); |
2515 | |
2516 | /// Constructors - Create a insertvalue instruction with a base aggregate |
2517 | /// value, a value to insert, and a list of indices. The first ctor can |
2518 | /// optionally insert before an existing instruction, the second appends |
2519 | /// the new instruction to the specified BasicBlock. |
2520 | inline InsertValueInst(Value *Agg, Value *Val, |
2521 | ArrayRef<unsigned> Idxs, |
2522 | const Twine &NameStr, |
2523 | Instruction *InsertBefore); |
2524 | inline InsertValueInst(Value *Agg, Value *Val, |
2525 | ArrayRef<unsigned> Idxs, |
2526 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2527 | |
2528 | /// Constructors - These two constructors are convenience methods because one |
2529 | /// and two index insertvalue instructions are so common. |
2530 | InsertValueInst(Value *Agg, Value *Val, unsigned Idx, |
2531 | const Twine &NameStr = "", |
2532 | Instruction *InsertBefore = nullptr); |
2533 | InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr, |
2534 | BasicBlock *InsertAtEnd); |
2535 | |
2536 | void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, |
2537 | const Twine &NameStr); |
2538 | |
2539 | protected: |
2540 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2541 | friend class Instruction; |
2542 | |
2543 | InsertValueInst *cloneImpl() const; |
2544 | |
2545 | public: |
2546 | // allocate space for exactly two operands |
2547 | void *operator new(size_t S) { return User::operator new(S, 2); } |
2548 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
2549 | |
2550 | static InsertValueInst *Create(Value *Agg, Value *Val, |
2551 | ArrayRef<unsigned> Idxs, |
2552 | const Twine &NameStr = "", |
2553 | Instruction *InsertBefore = nullptr) { |
2554 | return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore); |
2555 | } |
2556 | |
2557 | static InsertValueInst *Create(Value *Agg, Value *Val, |
2558 | ArrayRef<unsigned> Idxs, |
2559 | const Twine &NameStr, |
2560 | BasicBlock *InsertAtEnd) { |
2561 | return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd); |
2562 | } |
2563 | |
2564 | /// Transparently provide more efficient getOperand methods. |
2565 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2566 | |
2567 | using idx_iterator = const unsigned*; |
2568 | |
2569 | inline idx_iterator idx_begin() const { return Indices.begin(); } |
2570 | inline idx_iterator idx_end() const { return Indices.end(); } |
2571 | inline iterator_range<idx_iterator> indices() const { |
2572 | return make_range(idx_begin(), idx_end()); |
2573 | } |
2574 | |
2575 | Value *getAggregateOperand() { |
2576 | return getOperand(0); |
2577 | } |
2578 | const Value *getAggregateOperand() const { |
2579 | return getOperand(0); |
2580 | } |
2581 | static unsigned getAggregateOperandIndex() { |
2582 | return 0U; // get index for modifying correct operand |
2583 | } |
2584 | |
2585 | Value *getInsertedValueOperand() { |
2586 | return getOperand(1); |
2587 | } |
2588 | const Value *getInsertedValueOperand() const { |
2589 | return getOperand(1); |
2590 | } |
2591 | static unsigned getInsertedValueOperandIndex() { |
2592 | return 1U; // get index for modifying correct operand |
2593 | } |
2594 | |
2595 | ArrayRef<unsigned> getIndices() const { |
2596 | return Indices; |
2597 | } |
2598 | |
2599 | unsigned getNumIndices() const { |
2600 | return (unsigned)Indices.size(); |
2601 | } |
2602 | |
2603 | bool hasIndices() const { |
2604 | return true; |
2605 | } |
2606 | |
2607 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2608 | static bool classof(const Instruction *I) { |
2609 | return I->getOpcode() == Instruction::InsertValue; |
2610 | } |
2611 | static bool classof(const Value *V) { |
2612 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2613 | } |
2614 | }; |
2615 | |
2616 | template <> |
2617 | struct OperandTraits<InsertValueInst> : |
2618 | public FixedNumOperandTraits<InsertValueInst, 2> { |
2619 | }; |
2620 | |
2621 | InsertValueInst::InsertValueInst(Value *Agg, |
2622 | Value *Val, |
2623 | ArrayRef<unsigned> Idxs, |
2624 | const Twine &NameStr, |
2625 | Instruction *InsertBefore) |
2626 | : Instruction(Agg->getType(), InsertValue, |
2627 | OperandTraits<InsertValueInst>::op_begin(this), |
2628 | 2, InsertBefore) { |
2629 | init(Agg, Val, Idxs, NameStr); |
2630 | } |
2631 | |
2632 | InsertValueInst::InsertValueInst(Value *Agg, |
2633 | Value *Val, |
2634 | ArrayRef<unsigned> Idxs, |
2635 | const Twine &NameStr, |
2636 | BasicBlock *InsertAtEnd) |
2637 | : Instruction(Agg->getType(), InsertValue, |
2638 | OperandTraits<InsertValueInst>::op_begin(this), |
2639 | 2, InsertAtEnd) { |
2640 | init(Agg, Val, Idxs, NameStr); |
2641 | } |
2642 | |
2643 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)InsertValueInst::op_iterator InsertValueInst::op_begin() { return OperandTraits<InsertValueInst>::op_begin(this); } InsertValueInst ::const_op_iterator InsertValueInst::op_begin() const { return OperandTraits<InsertValueInst>::op_begin(const_cast< InsertValueInst*>(this)); } InsertValueInst::op_iterator InsertValueInst ::op_end() { return OperandTraits<InsertValueInst>::op_end (this); } InsertValueInst::const_op_iterator InsertValueInst:: op_end() const { return OperandTraits<InsertValueInst>:: op_end(const_cast<InsertValueInst*>(this)); } Value *InsertValueInst ::getOperand(unsigned i_nocapture) const { (static_cast <bool > (i_nocapture < OperandTraits<InsertValueInst>:: operands(this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 2643, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<InsertValueInst >::op_begin(const_cast<InsertValueInst*>(this))[i_nocapture ].get()); } void InsertValueInst::setOperand(unsigned i_nocapture , Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<InsertValueInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 2643, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<InsertValueInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned InsertValueInst::getNumOperands () const { return OperandTraits<InsertValueInst>::operands (this); } template <int Idx_nocapture> Use &InsertValueInst ::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &InsertValueInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
2644 | |
2645 | //===----------------------------------------------------------------------===// |
2646 | // PHINode Class |
2647 | //===----------------------------------------------------------------------===// |
2648 | |
2649 | // PHINode - The PHINode class is used to represent the magical mystical PHI |
2650 | // node, that can not exist in nature, but can be synthesized in a computer |
2651 | // scientist's overactive imagination. |
2652 | // |
2653 | class PHINode : public Instruction { |
2654 | /// The number of operands actually allocated. NumOperands is |
2655 | /// the number actually in use. |
2656 | unsigned ReservedSpace; |
2657 | |
2658 | PHINode(const PHINode &PN); |
2659 | |
2660 | explicit PHINode(Type *Ty, unsigned NumReservedValues, |
2661 | const Twine &NameStr = "", |
2662 | Instruction *InsertBefore = nullptr) |
2663 | : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore), |
2664 | ReservedSpace(NumReservedValues) { |
2665 | assert(!Ty->isTokenTy() && "PHI nodes cannot have token type!")(static_cast <bool> (!Ty->isTokenTy() && "PHI nodes cannot have token type!" ) ? void (0) : __assert_fail ("!Ty->isTokenTy() && \"PHI nodes cannot have token type!\"" , "llvm/include/llvm/IR/Instructions.h", 2665, __extension__ __PRETTY_FUNCTION__ )); |
2666 | setName(NameStr); |
2667 | allocHungoffUses(ReservedSpace); |
2668 | } |
2669 | |
2670 | PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr, |
2671 | BasicBlock *InsertAtEnd) |
2672 | : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd), |
2673 | ReservedSpace(NumReservedValues) { |
2674 | assert(!Ty->isTokenTy() && "PHI nodes cannot have token type!")(static_cast <bool> (!Ty->isTokenTy() && "PHI nodes cannot have token type!" ) ? void (0) : __assert_fail ("!Ty->isTokenTy() && \"PHI nodes cannot have token type!\"" , "llvm/include/llvm/IR/Instructions.h", 2674, __extension__ __PRETTY_FUNCTION__ )); |
2675 | setName(NameStr); |
2676 | allocHungoffUses(ReservedSpace); |
2677 | } |
2678 | |
2679 | protected: |
2680 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2681 | friend class Instruction; |
2682 | |
2683 | PHINode *cloneImpl() const; |
2684 | |
2685 | // allocHungoffUses - this is more complicated than the generic |
2686 | // User::allocHungoffUses, because we have to allocate Uses for the incoming |
2687 | // values and pointers to the incoming blocks, all in one allocation. |
2688 | void allocHungoffUses(unsigned N) { |
2689 | User::allocHungoffUses(N, /* IsPhi */ true); |
2690 | } |
2691 | |
2692 | public: |
2693 | /// Constructors - NumReservedValues is a hint for the number of incoming |
2694 | /// edges that this phi node will have (use 0 if you really have no idea). |
2695 | static PHINode *Create(Type *Ty, unsigned NumReservedValues, |
2696 | const Twine &NameStr = "", |
2697 | Instruction *InsertBefore = nullptr) { |
2698 | return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore); |
2699 | } |
2700 | |
2701 | static PHINode *Create(Type *Ty, unsigned NumReservedValues, |
2702 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
2703 | return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd); |
2704 | } |
2705 | |
2706 | /// Provide fast operand accessors |
2707 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2708 | |
2709 | // Block iterator interface. This provides access to the list of incoming |
2710 | // basic blocks, which parallels the list of incoming values. |
2711 | |
2712 | using block_iterator = BasicBlock **; |
2713 | using const_block_iterator = BasicBlock * const *; |
2714 | |
2715 | block_iterator block_begin() { |
2716 | return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace); |
2717 | } |
2718 | |
2719 | const_block_iterator block_begin() const { |
2720 | return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace); |
2721 | } |
2722 | |
2723 | block_iterator block_end() { |
2724 | return block_begin() + getNumOperands(); |
2725 | } |
2726 | |
2727 | const_block_iterator block_end() const { |
2728 | return block_begin() + getNumOperands(); |
2729 | } |
2730 | |
2731 | iterator_range<block_iterator> blocks() { |
2732 | return make_range(block_begin(), block_end()); |
2733 | } |
2734 | |
2735 | iterator_range<const_block_iterator> blocks() const { |
2736 | return make_range(block_begin(), block_end()); |
2737 | } |
2738 | |
2739 | op_range incoming_values() { return operands(); } |
2740 | |
2741 | const_op_range incoming_values() const { return operands(); } |
2742 | |
2743 | /// Return the number of incoming edges |
2744 | /// |
2745 | unsigned getNumIncomingValues() const { return getNumOperands(); } |
2746 | |
2747 | /// Return incoming value number x |
2748 | /// |
2749 | Value *getIncomingValue(unsigned i) const { |
2750 | return getOperand(i); |
2751 | } |
2752 | void setIncomingValue(unsigned i, Value *V) { |
2753 | assert(V && "PHI node got a null value!")(static_cast <bool> (V && "PHI node got a null value!" ) ? void (0) : __assert_fail ("V && \"PHI node got a null value!\"" , "llvm/include/llvm/IR/Instructions.h", 2753, __extension__ __PRETTY_FUNCTION__ )); |
2754 | assert(getType() == V->getType() &&(static_cast <bool> (getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!" ) ? void (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\"" , "llvm/include/llvm/IR/Instructions.h", 2755, __extension__ __PRETTY_FUNCTION__ )) |
2755 | "All operands to PHI node must be the same type as the PHI node!")(static_cast <bool> (getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!" ) ? void (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\"" , "llvm/include/llvm/IR/Instructions.h", 2755, __extension__ __PRETTY_FUNCTION__ )); |
2756 | setOperand(i, V); |
2757 | } |
2758 | |
2759 | static unsigned getOperandNumForIncomingValue(unsigned i) { |
2760 | return i; |
2761 | } |
2762 | |
2763 | static unsigned getIncomingValueNumForOperand(unsigned i) { |
2764 | return i; |
2765 | } |
2766 | |
2767 | /// Return incoming basic block number @p i. |
2768 | /// |
2769 | BasicBlock *getIncomingBlock(unsigned i) const { |
2770 | return block_begin()[i]; |
2771 | } |
2772 | |
2773 | /// Return incoming basic block corresponding |
2774 | /// to an operand of the PHI. |
2775 | /// |
2776 | BasicBlock *getIncomingBlock(const Use &U) const { |
2777 | assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?")(static_cast <bool> (this == U.getUser() && "Iterator doesn't point to PHI's Uses?" ) ? void (0) : __assert_fail ("this == U.getUser() && \"Iterator doesn't point to PHI's Uses?\"" , "llvm/include/llvm/IR/Instructions.h", 2777, __extension__ __PRETTY_FUNCTION__ )); |
2778 | return getIncomingBlock(unsigned(&U - op_begin())); |
2779 | } |
2780 | |
2781 | /// Return incoming basic block corresponding |
2782 | /// to value use iterator. |
2783 | /// |
2784 | BasicBlock *getIncomingBlock(Value::const_user_iterator I) const { |
2785 | return getIncomingBlock(I.getUse()); |
2786 | } |
2787 | |
2788 | void setIncomingBlock(unsigned i, BasicBlock *BB) { |
2789 | assert(BB && "PHI node got a null basic block!")(static_cast <bool> (BB && "PHI node got a null basic block!" ) ? void (0) : __assert_fail ("BB && \"PHI node got a null basic block!\"" , "llvm/include/llvm/IR/Instructions.h", 2789, __extension__ __PRETTY_FUNCTION__ )); |
2790 | block_begin()[i] = BB; |
2791 | } |
2792 | |
2793 | /// Replace every incoming basic block \p Old to basic block \p New. |
2794 | void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) { |
2795 | assert(New && Old && "PHI node got a null basic block!")(static_cast <bool> (New && Old && "PHI node got a null basic block!" ) ? void (0) : __assert_fail ("New && Old && \"PHI node got a null basic block!\"" , "llvm/include/llvm/IR/Instructions.h", 2795, __extension__ __PRETTY_FUNCTION__ )); |
2796 | for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op) |
2797 | if (getIncomingBlock(Op) == Old) |
2798 | setIncomingBlock(Op, New); |
2799 | } |
2800 | |
2801 | /// Add an incoming value to the end of the PHI list |
2802 | /// |
2803 | void addIncoming(Value *V, BasicBlock *BB) { |
2804 | if (getNumOperands() == ReservedSpace) |
2805 | growOperands(); // Get more space! |
2806 | // Initialize some new operands. |
2807 | setNumHungOffUseOperands(getNumOperands() + 1); |
2808 | setIncomingValue(getNumOperands() - 1, V); |
2809 | setIncomingBlock(getNumOperands() - 1, BB); |
2810 | } |
2811 | |
2812 | /// Remove an incoming value. This is useful if a |
2813 | /// predecessor basic block is deleted. The value removed is returned. |
2814 | /// |
2815 | /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty |
2816 | /// is true), the PHI node is destroyed and any uses of it are replaced with |
2817 | /// dummy values. The only time there should be zero incoming values to a PHI |
2818 | /// node is when the block is dead, so this strategy is sound. |
2819 | /// |
2820 | Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true); |
2821 | |
2822 | Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) { |
2823 | int Idx = getBasicBlockIndex(BB); |
2824 | assert(Idx >= 0 && "Invalid basic block argument to remove!")(static_cast <bool> (Idx >= 0 && "Invalid basic block argument to remove!" ) ? void (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument to remove!\"" , "llvm/include/llvm/IR/Instructions.h", 2824, __extension__ __PRETTY_FUNCTION__ )); |
2825 | return removeIncomingValue(Idx, DeletePHIIfEmpty); |
2826 | } |
2827 | |
2828 | /// Return the first index of the specified basic |
2829 | /// block in the value list for this PHI. Returns -1 if no instance. |
2830 | /// |
2831 | int getBasicBlockIndex(const BasicBlock *BB) const { |
2832 | for (unsigned i = 0, e = getNumOperands(); i != e; ++i) |
2833 | if (block_begin()[i] == BB) |
2834 | return i; |
2835 | return -1; |
2836 | } |
2837 | |
2838 | Value *getIncomingValueForBlock(const BasicBlock *BB) const { |
2839 | int Idx = getBasicBlockIndex(BB); |
2840 | assert(Idx >= 0 && "Invalid basic block argument!")(static_cast <bool> (Idx >= 0 && "Invalid basic block argument!" ) ? void (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument!\"" , "llvm/include/llvm/IR/Instructions.h", 2840, __extension__ __PRETTY_FUNCTION__ )); |
2841 | return getIncomingValue(Idx); |
2842 | } |
2843 | |
2844 | /// Set every incoming value(s) for block \p BB to \p V. |
2845 | void setIncomingValueForBlock(const BasicBlock *BB, Value *V) { |
2846 | assert(BB && "PHI node got a null basic block!")(static_cast <bool> (BB && "PHI node got a null basic block!" ) ? void (0) : __assert_fail ("BB && \"PHI node got a null basic block!\"" , "llvm/include/llvm/IR/Instructions.h", 2846, __extension__ __PRETTY_FUNCTION__ )); |
2847 | bool Found = false; |
2848 | for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op) |
2849 | if (getIncomingBlock(Op) == BB) { |
2850 | Found = true; |
2851 | setIncomingValue(Op, V); |
2852 | } |
2853 | (void)Found; |
2854 | assert(Found && "Invalid basic block argument to set!")(static_cast <bool> (Found && "Invalid basic block argument to set!" ) ? void (0) : __assert_fail ("Found && \"Invalid basic block argument to set!\"" , "llvm/include/llvm/IR/Instructions.h", 2854, __extension__ __PRETTY_FUNCTION__ )); |
2855 | } |
2856 | |
2857 | /// If the specified PHI node always merges together the |
2858 | /// same value, return the value, otherwise return null. |
2859 | Value *hasConstantValue() const; |
2860 | |
2861 | /// Whether the specified PHI node always merges |
2862 | /// together the same value, assuming undefs are equal to a unique |
2863 | /// non-undef value. |
2864 | bool hasConstantOrUndefValue() const; |
2865 | |
2866 | /// If the PHI node is complete which means all of its parent's predecessors |
2867 | /// have incoming value in this PHI, return true, otherwise return false. |
2868 | bool isComplete() const { |
2869 | return llvm::all_of(predecessors(getParent()), |
2870 | [this](const BasicBlock *Pred) { |
2871 | return getBasicBlockIndex(Pred) >= 0; |
2872 | }); |
2873 | } |
2874 | |
2875 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
2876 | static bool classof(const Instruction *I) { |
2877 | return I->getOpcode() == Instruction::PHI; |
2878 | } |
2879 | static bool classof(const Value *V) { |
2880 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2881 | } |
2882 | |
2883 | private: |
2884 | void growOperands(); |
2885 | }; |
2886 | |
2887 | template <> |
2888 | struct OperandTraits<PHINode> : public HungoffOperandTraits<2> { |
2889 | }; |
2890 | |
2891 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)PHINode::op_iterator PHINode::op_begin() { return OperandTraits <PHINode>::op_begin(this); } PHINode::const_op_iterator PHINode::op_begin() const { return OperandTraits<PHINode> ::op_begin(const_cast<PHINode*>(this)); } PHINode::op_iterator PHINode::op_end() { return OperandTraits<PHINode>::op_end (this); } PHINode::const_op_iterator PHINode::op_end() const { return OperandTraits<PHINode>::op_end(const_cast<PHINode *>(this)); } Value *PHINode::getOperand(unsigned i_nocapture ) const { (static_cast <bool> (i_nocapture < OperandTraits <PHINode>::operands(this) && "getOperand() out of range!" ) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 2891, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<PHINode >::op_begin(const_cast<PHINode*>(this))[i_nocapture] .get()); } void PHINode::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<PHINode>::operands(this) && "setOperand() out of range!" ) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 2891, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<PHINode>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned PHINode::getNumOperands() const { return OperandTraits<PHINode>::operands(this); } template <int Idx_nocapture> Use &PHINode::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &PHINode::Op() const { return this->OpFrom <Idx_nocapture>(this); } |
2892 | |
2893 | //===----------------------------------------------------------------------===// |
2894 | // LandingPadInst Class |
2895 | //===----------------------------------------------------------------------===// |
2896 | |
2897 | //===--------------------------------------------------------------------------- |
2898 | /// The landingpad instruction holds all of the information |
2899 | /// necessary to generate correct exception handling. The landingpad instruction |
2900 | /// cannot be moved from the top of a landing pad block, which itself is |
2901 | /// accessible only from the 'unwind' edge of an invoke. This uses the |
2902 | /// SubclassData field in Value to store whether or not the landingpad is a |
2903 | /// cleanup. |
2904 | /// |
2905 | class LandingPadInst : public Instruction { |
2906 | using CleanupField = BoolBitfieldElementT<0>; |
2907 | |
2908 | /// The number of operands actually allocated. NumOperands is |
2909 | /// the number actually in use. |
2910 | unsigned ReservedSpace; |
2911 | |
2912 | LandingPadInst(const LandingPadInst &LP); |
2913 | |
2914 | public: |
2915 | enum ClauseType { Catch, Filter }; |
2916 | |
2917 | private: |
2918 | explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues, |
2919 | const Twine &NameStr, Instruction *InsertBefore); |
2920 | explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues, |
2921 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2922 | |
2923 | // Allocate space for exactly zero operands. |
2924 | void *operator new(size_t S) { return User::operator new(S); } |
2925 | |
2926 | void growOperands(unsigned Size); |
2927 | void init(unsigned NumReservedValues, const Twine &NameStr); |
2928 | |
2929 | protected: |
2930 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2931 | friend class Instruction; |
2932 | |
2933 | LandingPadInst *cloneImpl() const; |
2934 | |
2935 | public: |
2936 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
2937 | |
2938 | /// Constructors - NumReservedClauses is a hint for the number of incoming |
2939 | /// clauses that this landingpad will have (use 0 if you really have no idea). |
2940 | static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses, |
2941 | const Twine &NameStr = "", |
2942 | Instruction *InsertBefore = nullptr); |
2943 | static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses, |
2944 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2945 | |
2946 | /// Provide fast operand accessors |
2947 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2948 | |
2949 | /// Return 'true' if this landingpad instruction is a |
2950 | /// cleanup. I.e., it should be run when unwinding even if its landing pad |
2951 | /// doesn't catch the exception. |
2952 | bool isCleanup() const { return getSubclassData<CleanupField>(); } |
2953 | |
2954 | /// Indicate that this landingpad instruction is a cleanup. |
2955 | void setCleanup(bool V) { setSubclassData<CleanupField>(V); } |
2956 | |
2957 | /// Add a catch or filter clause to the landing pad. |
2958 | void addClause(Constant *ClauseVal); |
2959 | |
2960 | /// Get the value of the clause at index Idx. Use isCatch/isFilter to |
2961 | /// determine what type of clause this is. |
2962 | Constant *getClause(unsigned Idx) const { |
2963 | return cast<Constant>(getOperandList()[Idx]); |
2964 | } |
2965 | |
2966 | /// Return 'true' if the clause and index Idx is a catch clause. |
2967 | bool isCatch(unsigned Idx) const { |
2968 | return !isa<ArrayType>(getOperandList()[Idx]->getType()); |
2969 | } |
2970 | |
2971 | /// Return 'true' if the clause and index Idx is a filter clause. |
2972 | bool isFilter(unsigned Idx) const { |
2973 | return isa<ArrayType>(getOperandList()[Idx]->getType()); |
2974 | } |
2975 | |
2976 | /// Get the number of clauses for this landing pad. |
2977 | unsigned getNumClauses() const { return getNumOperands(); } |
2978 | |
2979 | /// Grow the size of the operand list to accommodate the new |
2980 | /// number of clauses. |
2981 | void reserveClauses(unsigned Size) { growOperands(Size); } |
2982 | |
2983 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2984 | static bool classof(const Instruction *I) { |
2985 | return I->getOpcode() == Instruction::LandingPad; |
2986 | } |
2987 | static bool classof(const Value *V) { |
2988 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2989 | } |
2990 | }; |
2991 | |
2992 | template <> |
2993 | struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> { |
2994 | }; |
2995 | |
2996 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)LandingPadInst::op_iterator LandingPadInst::op_begin() { return OperandTraits<LandingPadInst>::op_begin(this); } LandingPadInst ::const_op_iterator LandingPadInst::op_begin() const { return OperandTraits<LandingPadInst>::op_begin(const_cast< LandingPadInst*>(this)); } LandingPadInst::op_iterator LandingPadInst ::op_end() { return OperandTraits<LandingPadInst>::op_end (this); } LandingPadInst::const_op_iterator LandingPadInst::op_end () const { return OperandTraits<LandingPadInst>::op_end (const_cast<LandingPadInst*>(this)); } Value *LandingPadInst ::getOperand(unsigned i_nocapture) const { (static_cast <bool > (i_nocapture < OperandTraits<LandingPadInst>::operands (this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 2996, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<LandingPadInst >::op_begin(const_cast<LandingPadInst*>(this))[i_nocapture ].get()); } void LandingPadInst::setOperand(unsigned i_nocapture , Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<LandingPadInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 2996, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<LandingPadInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned LandingPadInst::getNumOperands( ) const { return OperandTraits<LandingPadInst>::operands (this); } template <int Idx_nocapture> Use &LandingPadInst ::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &LandingPadInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
2997 | |
2998 | //===----------------------------------------------------------------------===// |
2999 | // ReturnInst Class |
3000 | //===----------------------------------------------------------------------===// |
3001 | |
3002 | //===--------------------------------------------------------------------------- |
3003 | /// Return a value (possibly void), from a function. Execution |
3004 | /// does not continue in this function any longer. |
3005 | /// |
3006 | class ReturnInst : public Instruction { |
3007 | ReturnInst(const ReturnInst &RI); |
3008 | |
3009 | private: |
3010 | // ReturnInst constructors: |
3011 | // ReturnInst() - 'ret void' instruction |
3012 | // ReturnInst( null) - 'ret void' instruction |
3013 | // ReturnInst(Value* X) - 'ret X' instruction |
3014 | // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I |
3015 | // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I |
3016 | // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B |
3017 | // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B |
3018 | // |
3019 | // NOTE: If the Value* passed is of type void then the constructor behaves as |
3020 | // if it was passed NULL. |
3021 | explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr, |
3022 | Instruction *InsertBefore = nullptr); |
3023 | ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd); |
3024 | explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd); |
3025 | |
3026 | protected: |
3027 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3028 | friend class Instruction; |
3029 | |
3030 | ReturnInst *cloneImpl() const; |
3031 | |
3032 | public: |
3033 | static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr, |
3034 | Instruction *InsertBefore = nullptr) { |
3035 | return new(!!retVal) ReturnInst(C, retVal, InsertBefore); |
3036 | } |
3037 | |
3038 | static ReturnInst* Create(LLVMContext &C, Value *retVal, |
3039 | BasicBlock *InsertAtEnd) { |
3040 | return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd); |
3041 | } |
3042 | |
3043 | static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) { |
3044 | return new(0) ReturnInst(C, InsertAtEnd); |
3045 | } |
3046 | |
3047 | /// Provide fast operand accessors |
3048 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
3049 | |
3050 | /// Convenience accessor. Returns null if there is no return value. |
3051 | Value *getReturnValue() const { |
3052 | return getNumOperands() != 0 ? getOperand(0) : nullptr; |
3053 | } |
3054 | |
3055 | unsigned getNumSuccessors() const { return 0; } |
3056 | |
3057 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3058 | static bool classof(const Instruction *I) { |
3059 | return (I->getOpcode() == Instruction::Ret); |
3060 | } |
3061 | static bool classof(const Value *V) { |
3062 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3063 | } |
3064 | |
3065 | private: |
3066 | BasicBlock *getSuccessor(unsigned idx) const { |
3067 | llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!" , "llvm/include/llvm/IR/Instructions.h", 3067); |
3068 | } |
3069 | |
3070 | void setSuccessor(unsigned idx, BasicBlock *B) { |
3071 | llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!" , "llvm/include/llvm/IR/Instructions.h", 3071); |
3072 | } |
3073 | }; |
3074 | |
3075 | template <> |
3076 | struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> { |
3077 | }; |
3078 | |
3079 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)ReturnInst::op_iterator ReturnInst::op_begin() { return OperandTraits <ReturnInst>::op_begin(this); } ReturnInst::const_op_iterator ReturnInst::op_begin() const { return OperandTraits<ReturnInst >::op_begin(const_cast<ReturnInst*>(this)); } ReturnInst ::op_iterator ReturnInst::op_end() { return OperandTraits< ReturnInst>::op_end(this); } ReturnInst::const_op_iterator ReturnInst::op_end() const { return OperandTraits<ReturnInst >::op_end(const_cast<ReturnInst*>(this)); } Value *ReturnInst ::getOperand(unsigned i_nocapture) const { (static_cast <bool > (i_nocapture < OperandTraits<ReturnInst>::operands (this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 3079, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<ReturnInst >::op_begin(const_cast<ReturnInst*>(this))[i_nocapture ].get()); } void ReturnInst::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<ReturnInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 3079, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<ReturnInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned ReturnInst::getNumOperands() const { return OperandTraits<ReturnInst>::operands(this); } template <int Idx_nocapture> Use &ReturnInst::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &ReturnInst::Op() const { return this->OpFrom<Idx_nocapture>(this); } |
3080 | |
3081 | //===----------------------------------------------------------------------===// |
3082 | // BranchInst Class |
3083 | //===----------------------------------------------------------------------===// |
3084 | |
3085 | //===--------------------------------------------------------------------------- |
3086 | /// Conditional or Unconditional Branch instruction. |
3087 | /// |
3088 | class BranchInst : public Instruction { |
3089 | /// Ops list - Branches are strange. The operands are ordered: |
3090 | /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because |
3091 | /// they don't have to check for cond/uncond branchness. These are mostly |
3092 | /// accessed relative from op_end(). |
3093 | BranchInst(const BranchInst &BI); |
3094 | // BranchInst constructors (where {B, T, F} are blocks, and C is a condition): |
3095 | // BranchInst(BB *B) - 'br B' |
3096 | // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F' |
3097 | // BranchInst(BB* B, Inst *I) - 'br B' insert before I |
3098 | // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I |
3099 | // BranchInst(BB* B, BB *I) - 'br B' insert at end |
3100 | // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end |
3101 | explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr); |
3102 | BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, |
3103 | Instruction *InsertBefore = nullptr); |
3104 | BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd); |
3105 | BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, |
3106 | BasicBlock *InsertAtEnd); |
3107 | |
3108 | void AssertOK(); |
3109 | |
3110 | protected: |
3111 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3112 | friend class Instruction; |
3113 | |
3114 | BranchInst *cloneImpl() const; |
3115 | |
3116 | public: |
3117 | /// Iterator type that casts an operand to a basic block. |
3118 | /// |
3119 | /// This only makes sense because the successors are stored as adjacent |
3120 | /// operands for branch instructions. |
3121 | struct succ_op_iterator |
3122 | : iterator_adaptor_base<succ_op_iterator, value_op_iterator, |
3123 | std::random_access_iterator_tag, BasicBlock *, |
3124 | ptrdiff_t, BasicBlock *, BasicBlock *> { |
3125 | explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {} |
3126 | |
3127 | BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3128 | BasicBlock *operator->() const { return operator*(); } |
3129 | }; |
3130 | |
3131 | /// The const version of `succ_op_iterator`. |
3132 | struct const_succ_op_iterator |
3133 | : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator, |
3134 | std::random_access_iterator_tag, |
3135 | const BasicBlock *, ptrdiff_t, const BasicBlock *, |
3136 | const BasicBlock *> { |
3137 | explicit const_succ_op_iterator(const_value_op_iterator I) |
3138 | : iterator_adaptor_base(I) {} |
3139 | |
3140 | const BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3141 | const BasicBlock *operator->() const { return operator*(); } |
3142 | }; |
3143 | |
3144 | static BranchInst *Create(BasicBlock *IfTrue, |
3145 | Instruction *InsertBefore = nullptr) { |
3146 | return new(1) BranchInst(IfTrue, InsertBefore); |
3147 | } |
3148 | |
3149 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse, |
3150 | Value *Cond, Instruction *InsertBefore = nullptr) { |
3151 | return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore); |
3152 | } |
3153 | |
3154 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) { |
3155 | return new(1) BranchInst(IfTrue, InsertAtEnd); |
3156 | } |
3157 | |
3158 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse, |
3159 | Value *Cond, BasicBlock *InsertAtEnd) { |
3160 | return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd); |
3161 | } |
3162 | |
3163 | /// Transparently provide more efficient getOperand methods. |
3164 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
3165 | |
3166 | bool isUnconditional() const { return getNumOperands() == 1; } |
3167 | bool isConditional() const { return getNumOperands() == 3; } |
3168 | |
3169 | Value *getCondition() const { |
3170 | assert(isConditional() && "Cannot get condition of an uncond branch!")(static_cast <bool> (isConditional() && "Cannot get condition of an uncond branch!" ) ? void (0) : __assert_fail ("isConditional() && \"Cannot get condition of an uncond branch!\"" , "llvm/include/llvm/IR/Instructions.h", 3170, __extension__ __PRETTY_FUNCTION__ )); |
3171 | return Op<-3>(); |
3172 | } |
3173 | |
3174 | void setCondition(Value *V) { |
3175 | assert(isConditional() && "Cannot set condition of unconditional branch!")(static_cast <bool> (isConditional() && "Cannot set condition of unconditional branch!" ) ? void (0) : __assert_fail ("isConditional() && \"Cannot set condition of unconditional branch!\"" , "llvm/include/llvm/IR/Instructions.h", 3175, __extension__ __PRETTY_FUNCTION__ )); |
3176 | Op<-3>() = V; |
3177 | } |
3178 | |
3179 | unsigned getNumSuccessors() const { return 1+isConditional(); } |
3180 | |
3181 | BasicBlock *getSuccessor(unsigned i) const { |
3182 | assert(i < getNumSuccessors() && "Successor # out of range for Branch!")(static_cast <bool> (i < getNumSuccessors() && "Successor # out of range for Branch!") ? void (0) : __assert_fail ("i < getNumSuccessors() && \"Successor # out of range for Branch!\"" , "llvm/include/llvm/IR/Instructions.h", 3182, __extension__ __PRETTY_FUNCTION__ )); |
3183 | return cast_or_null<BasicBlock>((&Op<-1>() - i)->get()); |
3184 | } |
3185 | |
3186 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
3187 | assert(idx < getNumSuccessors() && "Successor # out of range for Branch!")(static_cast <bool> (idx < getNumSuccessors() && "Successor # out of range for Branch!") ? void (0) : __assert_fail ("idx < getNumSuccessors() && \"Successor # out of range for Branch!\"" , "llvm/include/llvm/IR/Instructions.h", 3187, __extension__ __PRETTY_FUNCTION__ )); |
3188 | *(&Op<-1>() - idx) = NewSucc; |
3189 | } |
3190 | |
3191 | /// Swap the successors of this branch instruction. |
3192 | /// |
3193 | /// Swaps the successors of the branch instruction. This also swaps any |
3194 | /// branch weight metadata associated with the instruction so that it |
3195 | /// continues to map correctly to each operand. |
3196 | void swapSuccessors(); |
3197 | |
3198 | iterator_range<succ_op_iterator> successors() { |
3199 | return make_range( |
3200 | succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)), |
3201 | succ_op_iterator(value_op_end())); |
3202 | } |
3203 | |
3204 | iterator_range<const_succ_op_iterator> successors() const { |
3205 | return make_range(const_succ_op_iterator( |
3206 | std::next(value_op_begin(), isConditional() ? 1 : 0)), |
3207 | const_succ_op_iterator(value_op_end())); |
3208 | } |
3209 | |
3210 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3211 | static bool classof(const Instruction *I) { |
3212 | return (I->getOpcode() == Instruction::Br); |
3213 | } |
3214 | static bool classof(const Value *V) { |
3215 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3216 | } |
3217 | }; |
3218 | |
3219 | template <> |
3220 | struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> { |
3221 | }; |
3222 | |
3223 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)BranchInst::op_iterator BranchInst::op_begin() { return OperandTraits <BranchInst>::op_begin(this); } BranchInst::const_op_iterator BranchInst::op_begin() const { return OperandTraits<BranchInst >::op_begin(const_cast<BranchInst*>(this)); } BranchInst ::op_iterator BranchInst::op_end() { return OperandTraits< BranchInst>::op_end(this); } BranchInst::const_op_iterator BranchInst::op_end() const { return OperandTraits<BranchInst >::op_end(const_cast<BranchInst*>(this)); } Value *BranchInst ::getOperand(unsigned i_nocapture) const { (static_cast <bool > (i_nocapture < OperandTraits<BranchInst>::operands (this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 3223, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<BranchInst >::op_begin(const_cast<BranchInst*>(this))[i_nocapture ].get()); } void BranchInst::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<BranchInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 3223, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<BranchInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned BranchInst::getNumOperands() const { return OperandTraits<BranchInst>::operands(this); } template <int Idx_nocapture> Use &BranchInst::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &BranchInst::Op() const { return this->OpFrom<Idx_nocapture>(this); } |
3224 | |
3225 | //===----------------------------------------------------------------------===// |
3226 | // SwitchInst Class |
3227 | //===----------------------------------------------------------------------===// |
3228 | |
3229 | //===--------------------------------------------------------------------------- |
3230 | /// Multiway switch |
3231 | /// |
3232 | class SwitchInst : public Instruction { |
3233 | unsigned ReservedSpace; |
3234 | |
3235 | // Operand[0] = Value to switch on |
3236 | // Operand[1] = Default basic block destination |
3237 | // Operand[2n ] = Value to match |
3238 | // Operand[2n+1] = BasicBlock to go to on match |
3239 | SwitchInst(const SwitchInst &SI); |
3240 | |
3241 | /// Create a new switch instruction, specifying a value to switch on and a |
3242 | /// default destination. The number of additional cases can be specified here |
3243 | /// to make memory allocation more efficient. This constructor can also |
3244 | /// auto-insert before another instruction. |
3245 | SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, |
3246 | Instruction *InsertBefore); |
3247 | |
3248 | /// Create a new switch instruction, specifying a value to switch on and a |
3249 | /// default destination. The number of additional cases can be specified here |
3250 | /// to make memory allocation more efficient. This constructor also |
3251 | /// auto-inserts at the end of the specified BasicBlock. |
3252 | SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, |
3253 | BasicBlock *InsertAtEnd); |
3254 | |
3255 | // allocate space for exactly zero operands |
3256 | void *operator new(size_t S) { return User::operator new(S); } |
3257 | |
3258 | void init(Value *Value, BasicBlock *Default, unsigned NumReserved); |
3259 | void growOperands(); |
3260 | |
3261 | protected: |
3262 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3263 | friend class Instruction; |
3264 | |
3265 | SwitchInst *cloneImpl() const; |
3266 | |
3267 | public: |
3268 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
3269 | |
3270 | // -2 |
3271 | static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1); |
3272 | |
3273 | template <typename CaseHandleT> class CaseIteratorImpl; |
3274 | |
3275 | /// A handle to a particular switch case. It exposes a convenient interface |
3276 | /// to both the case value and the successor block. |
3277 | /// |
3278 | /// We define this as a template and instantiate it to form both a const and |
3279 | /// non-const handle. |
3280 | template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT> |
3281 | class CaseHandleImpl { |
3282 | // Directly befriend both const and non-const iterators. |
3283 | friend class SwitchInst::CaseIteratorImpl< |
3284 | CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>; |
3285 | |
3286 | protected: |
3287 | // Expose the switch type we're parameterized with to the iterator. |
3288 | using SwitchInstType = SwitchInstT; |
3289 | |
3290 | SwitchInstT *SI; |
3291 | ptrdiff_t Index; |
3292 | |
3293 | CaseHandleImpl() = default; |
3294 | CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {} |
3295 | |
3296 | public: |
3297 | /// Resolves case value for current case. |
3298 | ConstantIntT *getCaseValue() const { |
3299 | assert((unsigned)Index < SI->getNumCases() &&(static_cast <bool> ((unsigned)Index < SI->getNumCases () && "Index out the number of cases.") ? void (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3300, __extension__ __PRETTY_FUNCTION__ )) |
3300 | "Index out the number of cases.")(static_cast <bool> ((unsigned)Index < SI->getNumCases () && "Index out the number of cases.") ? void (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3300, __extension__ __PRETTY_FUNCTION__ )); |
3301 | return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2)); |
3302 | } |
3303 | |
3304 | /// Resolves successor for current case. |
3305 | BasicBlockT *getCaseSuccessor() const { |
3306 | assert(((unsigned)Index < SI->getNumCases() ||(static_cast <bool> (((unsigned)Index < SI->getNumCases () || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases." ) ? void (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3308, __extension__ __PRETTY_FUNCTION__ )) |
3307 | (unsigned)Index == DefaultPseudoIndex) &&(static_cast <bool> (((unsigned)Index < SI->getNumCases () || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases." ) ? void (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3308, __extension__ __PRETTY_FUNCTION__ )) |
3308 | "Index out the number of cases.")(static_cast <bool> (((unsigned)Index < SI->getNumCases () || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases." ) ? void (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3308, __extension__ __PRETTY_FUNCTION__ )); |
3309 | return SI->getSuccessor(getSuccessorIndex()); |
3310 | } |
3311 | |
3312 | /// Returns number of current case. |
3313 | unsigned getCaseIndex() const { return Index; } |
3314 | |
3315 | /// Returns successor index for current case successor. |
3316 | unsigned getSuccessorIndex() const { |
3317 | assert(((unsigned)Index == DefaultPseudoIndex ||(static_cast <bool> (((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && "Index out the number of cases." ) ? void (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3319, __extension__ __PRETTY_FUNCTION__ )) |
3318 | (unsigned)Index < SI->getNumCases()) &&(static_cast <bool> (((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && "Index out the number of cases." ) ? void (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3319, __extension__ __PRETTY_FUNCTION__ )) |
3319 | "Index out the number of cases.")(static_cast <bool> (((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && "Index out the number of cases." ) ? void (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3319, __extension__ __PRETTY_FUNCTION__ )); |
3320 | return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0; |
3321 | } |
3322 | |
3323 | bool operator==(const CaseHandleImpl &RHS) const { |
3324 | assert(SI == RHS.SI && "Incompatible operators.")(static_cast <bool> (SI == RHS.SI && "Incompatible operators." ) ? void (0) : __assert_fail ("SI == RHS.SI && \"Incompatible operators.\"" , "llvm/include/llvm/IR/Instructions.h", 3324, __extension__ __PRETTY_FUNCTION__ )); |
3325 | return Index == RHS.Index; |
3326 | } |
3327 | }; |
3328 | |
3329 | using ConstCaseHandle = |
3330 | CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>; |
3331 | |
3332 | class CaseHandle |
3333 | : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> { |
3334 | friend class SwitchInst::CaseIteratorImpl<CaseHandle>; |
3335 | |
3336 | public: |
3337 | CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {} |
3338 | |
3339 | /// Sets the new value for current case. |
3340 | void setValue(ConstantInt *V) const { |
3341 | assert((unsigned)Index < SI->getNumCases() &&(static_cast <bool> ((unsigned)Index < SI->getNumCases () && "Index out the number of cases.") ? void (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3342, __extension__ __PRETTY_FUNCTION__ )) |
3342 | "Index out the number of cases.")(static_cast <bool> ((unsigned)Index < SI->getNumCases () && "Index out the number of cases.") ? void (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3342, __extension__ __PRETTY_FUNCTION__ )); |
3343 | SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V)); |
3344 | } |
3345 | |
3346 | /// Sets the new successor for current case. |
3347 | void setSuccessor(BasicBlock *S) const { |
3348 | SI->setSuccessor(getSuccessorIndex(), S); |
3349 | } |
3350 | }; |
3351 | |
3352 | template <typename CaseHandleT> |
3353 | class CaseIteratorImpl |
3354 | : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>, |
3355 | std::random_access_iterator_tag, |
3356 | const CaseHandleT> { |
3357 | using SwitchInstT = typename CaseHandleT::SwitchInstType; |
3358 | |
3359 | CaseHandleT Case; |
3360 | |
3361 | public: |
3362 | /// Default constructed iterator is in an invalid state until assigned to |
3363 | /// a case for a particular switch. |
3364 | CaseIteratorImpl() = default; |
3365 | |
3366 | /// Initializes case iterator for given SwitchInst and for given |
3367 | /// case number. |
3368 | CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {} |
3369 | |
3370 | /// Initializes case iterator for given SwitchInst and for given |
3371 | /// successor index. |
3372 | static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI, |
3373 | unsigned SuccessorIndex) { |
3374 | assert(SuccessorIndex < SI->getNumSuccessors() &&(static_cast <bool> (SuccessorIndex < SI->getNumSuccessors () && "Successor index # out of range!") ? void (0) : __assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 3375, __extension__ __PRETTY_FUNCTION__ )) |
3375 | "Successor index # out of range!")(static_cast <bool> (SuccessorIndex < SI->getNumSuccessors () && "Successor index # out of range!") ? void (0) : __assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 3375, __extension__ __PRETTY_FUNCTION__ )); |
3376 | return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1) |
3377 | : CaseIteratorImpl(SI, DefaultPseudoIndex); |
3378 | } |
3379 | |
3380 | /// Support converting to the const variant. This will be a no-op for const |
3381 | /// variant. |
3382 | operator CaseIteratorImpl<ConstCaseHandle>() const { |
3383 | return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index); |
3384 | } |
3385 | |
3386 | CaseIteratorImpl &operator+=(ptrdiff_t N) { |
3387 | // Check index correctness after addition. |
3388 | // Note: Index == getNumCases() means end(). |
3389 | assert(Case.Index + N >= 0 &&(static_cast <bool> (Case.Index + N >= 0 && ( unsigned)(Case.Index + N) <= Case.SI->getNumCases() && "Case.Index out the number of cases.") ? void (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3391, __extension__ __PRETTY_FUNCTION__ )) |
3390 | (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&(static_cast <bool> (Case.Index + N >= 0 && ( unsigned)(Case.Index + N) <= Case.SI->getNumCases() && "Case.Index out the number of cases.") ? void (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3391, __extension__ __PRETTY_FUNCTION__ )) |
3391 | "Case.Index out the number of cases.")(static_cast <bool> (Case.Index + N >= 0 && ( unsigned)(Case.Index + N) <= Case.SI->getNumCases() && "Case.Index out the number of cases.") ? void (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3391, __extension__ __PRETTY_FUNCTION__ )); |
3392 | Case.Index += N; |
3393 | return *this; |
3394 | } |
3395 | CaseIteratorImpl &operator-=(ptrdiff_t N) { |
3396 | // Check index correctness after subtraction. |
3397 | // Note: Case.Index == getNumCases() means end(). |
3398 | assert(Case.Index - N >= 0 &&(static_cast <bool> (Case.Index - N >= 0 && ( unsigned)(Case.Index - N) <= Case.SI->getNumCases() && "Case.Index out the number of cases.") ? void (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3400, __extension__ __PRETTY_FUNCTION__ )) |
3399 | (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&(static_cast <bool> (Case.Index - N >= 0 && ( unsigned)(Case.Index - N) <= Case.SI->getNumCases() && "Case.Index out the number of cases.") ? void (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3400, __extension__ __PRETTY_FUNCTION__ )) |
3400 | "Case.Index out the number of cases.")(static_cast <bool> (Case.Index - N >= 0 && ( unsigned)(Case.Index - N) <= Case.SI->getNumCases() && "Case.Index out the number of cases.") ? void (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "llvm/include/llvm/IR/Instructions.h", 3400, __extension__ __PRETTY_FUNCTION__ )); |
3401 | Case.Index -= N; |
3402 | return *this; |
3403 | } |
3404 | ptrdiff_t operator-(const CaseIteratorImpl &RHS) const { |
3405 | assert(Case.SI == RHS.Case.SI && "Incompatible operators.")(static_cast <bool> (Case.SI == RHS.Case.SI && "Incompatible operators." ) ? void (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\"" , "llvm/include/llvm/IR/Instructions.h", 3405, __extension__ __PRETTY_FUNCTION__ )); |
3406 | return Case.Index - RHS.Case.Index; |
3407 | } |
3408 | bool operator==(const CaseIteratorImpl &RHS) const { |
3409 | return Case == RHS.Case; |
3410 | } |
3411 | bool operator<(const CaseIteratorImpl &RHS) const { |
3412 | assert(Case.SI == RHS.Case.SI && "Incompatible operators.")(static_cast <bool> (Case.SI == RHS.Case.SI && "Incompatible operators." ) ? void (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\"" , "llvm/include/llvm/IR/Instructions.h", 3412, __extension__ __PRETTY_FUNCTION__ )); |
3413 | return Case.Index < RHS.Case.Index; |
3414 | } |
3415 | const CaseHandleT &operator*() const { return Case; } |
3416 | }; |
3417 | |
3418 | using CaseIt = CaseIteratorImpl<CaseHandle>; |
3419 | using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>; |
3420 | |
3421 | static SwitchInst *Create(Value *Value, BasicBlock *Default, |
3422 | unsigned NumCases, |
3423 | Instruction *InsertBefore = nullptr) { |
3424 | return new SwitchInst(Value, Default, NumCases, InsertBefore); |
3425 | } |
3426 | |
3427 | static SwitchInst *Create(Value *Value, BasicBlock *Default, |
3428 | unsigned NumCases, BasicBlock *InsertAtEnd) { |
3429 | return new SwitchInst(Value, Default, NumCases, InsertAtEnd); |
3430 | } |
3431 | |
3432 | /// Provide fast operand accessors |
3433 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
3434 | |
3435 | // Accessor Methods for Switch stmt |
3436 | Value *getCondition() const { return getOperand(0); } |
3437 | void setCondition(Value *V) { setOperand(0, V); } |
3438 | |
3439 | BasicBlock *getDefaultDest() const { |
3440 | return cast<BasicBlock>(getOperand(1)); |
3441 | } |
3442 | |
3443 | void setDefaultDest(BasicBlock *DefaultCase) { |
3444 | setOperand(1, reinterpret_cast<Value*>(DefaultCase)); |
3445 | } |
3446 | |
3447 | /// Return the number of 'cases' in this switch instruction, excluding the |
3448 | /// default case. |
3449 | unsigned getNumCases() const { |
3450 | return getNumOperands()/2 - 1; |
3451 | } |
3452 | |
3453 | /// Returns a read/write iterator that points to the first case in the |
3454 | /// SwitchInst. |
3455 | CaseIt case_begin() { |
3456 | return CaseIt(this, 0); |
3457 | } |
3458 | |
3459 | /// Returns a read-only iterator that points to the first case in the |
3460 | /// SwitchInst. |
3461 | ConstCaseIt case_begin() const { |
3462 | return ConstCaseIt(this, 0); |
3463 | } |
3464 | |
3465 | /// Returns a read/write iterator that points one past the last in the |
3466 | /// SwitchInst. |
3467 | CaseIt case_end() { |
3468 | return CaseIt(this, getNumCases()); |
3469 | } |
3470 | |
3471 | /// Returns a read-only iterator that points one past the last in the |
3472 | /// SwitchInst. |
3473 | ConstCaseIt case_end() const { |
3474 | return ConstCaseIt(this, getNumCases()); |
3475 | } |
3476 | |
3477 | /// Iteration adapter for range-for loops. |
3478 | iterator_range<CaseIt> cases() { |
3479 | return make_range(case_begin(), case_end()); |
3480 | } |
3481 | |
3482 | /// Constant iteration adapter for range-for loops. |
3483 | iterator_range<ConstCaseIt> cases() const { |
3484 | return make_range(case_begin(), case_end()); |
3485 | } |
3486 | |
3487 | /// Returns an iterator that points to the default case. |
3488 | /// Note: this iterator allows to resolve successor only. Attempt |
3489 | /// to resolve case value causes an assertion. |
3490 | /// Also note, that increment and decrement also causes an assertion and |
3491 | /// makes iterator invalid. |
3492 | CaseIt case_default() { |
3493 | return CaseIt(this, DefaultPseudoIndex); |
3494 | } |
3495 | ConstCaseIt case_default() const { |
3496 | return ConstCaseIt(this, DefaultPseudoIndex); |
3497 | } |
3498 | |
3499 | /// Search all of the case values for the specified constant. If it is |
3500 | /// explicitly handled, return the case iterator of it, otherwise return |
3501 | /// default case iterator to indicate that it is handled by the default |
3502 | /// handler. |
3503 | CaseIt findCaseValue(const ConstantInt *C) { |
3504 | return CaseIt( |
3505 | this, |
3506 | const_cast<const SwitchInst *>(this)->findCaseValue(C)->getCaseIndex()); |
3507 | } |
3508 | ConstCaseIt findCaseValue(const ConstantInt *C) const { |
3509 | ConstCaseIt I = llvm::find_if(cases(), [C](const ConstCaseHandle &Case) { |
3510 | return Case.getCaseValue() == C; |
3511 | }); |
3512 | if (I != case_end()) |
3513 | return I; |
3514 | |
3515 | return case_default(); |
3516 | } |
3517 | |
3518 | /// Finds the unique case value for a given successor. Returns null if the |
3519 | /// successor is not found, not unique, or is the default case. |
3520 | ConstantInt *findCaseDest(BasicBlock *BB) { |
3521 | if (BB == getDefaultDest()) |
3522 | return nullptr; |
3523 | |
3524 | ConstantInt *CI = nullptr; |
3525 | for (auto Case : cases()) { |
3526 | if (Case.getCaseSuccessor() != BB) |
3527 | continue; |
3528 | |
3529 | if (CI) |
3530 | return nullptr; // Multiple cases lead to BB. |
3531 | |
3532 | CI = Case.getCaseValue(); |
3533 | } |
3534 | |
3535 | return CI; |
3536 | } |
3537 | |
3538 | /// Add an entry to the switch instruction. |
3539 | /// Note: |
3540 | /// This action invalidates case_end(). Old case_end() iterator will |
3541 | /// point to the added case. |
3542 | void addCase(ConstantInt *OnVal, BasicBlock *Dest); |
3543 | |
3544 | /// This method removes the specified case and its successor from the switch |
3545 | /// instruction. Note that this operation may reorder the remaining cases at |
3546 | /// index idx and above. |
3547 | /// Note: |
3548 | /// This action invalidates iterators for all cases following the one removed, |
3549 | /// including the case_end() iterator. It returns an iterator for the next |
3550 | /// case. |
3551 | CaseIt removeCase(CaseIt I); |
3552 | |
3553 | unsigned getNumSuccessors() const { return getNumOperands()/2; } |
3554 | BasicBlock *getSuccessor(unsigned idx) const { |
3555 | assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!")(static_cast <bool> (idx < getNumSuccessors() && "Successor idx out of range for switch!") ? void (0) : __assert_fail ("idx < getNumSuccessors() &&\"Successor idx out of range for switch!\"" , "llvm/include/llvm/IR/Instructions.h", 3555, __extension__ __PRETTY_FUNCTION__ )); |
3556 | return cast<BasicBlock>(getOperand(idx*2+1)); |
3557 | } |
3558 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
3559 | assert(idx < getNumSuccessors() && "Successor # out of range for switch!")(static_cast <bool> (idx < getNumSuccessors() && "Successor # out of range for switch!") ? void (0) : __assert_fail ("idx < getNumSuccessors() && \"Successor # out of range for switch!\"" , "llvm/include/llvm/IR/Instructions.h", 3559, __extension__ __PRETTY_FUNCTION__ )); |
3560 | setOperand(idx * 2 + 1, NewSucc); |
3561 | } |
3562 | |
3563 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3564 | static bool classof(const Instruction *I) { |
3565 | return I->getOpcode() == Instruction::Switch; |
3566 | } |
3567 | static bool classof(const Value *V) { |
3568 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3569 | } |
3570 | }; |
3571 | |
3572 | /// A wrapper class to simplify modification of SwitchInst cases along with |
3573 | /// their prof branch_weights metadata. |
3574 | class SwitchInstProfUpdateWrapper { |
3575 | SwitchInst &SI; |
3576 | Optional<SmallVector<uint32_t, 8> > Weights = None; |
3577 | bool Changed = false; |
3578 | |
3579 | protected: |
3580 | static MDNode *getProfBranchWeightsMD(const SwitchInst &SI); |
3581 | |
3582 | MDNode *buildProfBranchWeightsMD(); |
3583 | |
3584 | void init(); |
3585 | |
3586 | public: |
3587 | using CaseWeightOpt = Optional<uint32_t>; |
3588 | SwitchInst *operator->() { return &SI; } |
3589 | SwitchInst &operator*() { return SI; } |
3590 | operator SwitchInst *() { return &SI; } |
3591 | |
3592 | SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); } |
3593 | |
3594 | ~SwitchInstProfUpdateWrapper() { |
3595 | if (Changed) |
3596 | SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD()); |
3597 | } |
3598 | |
3599 | /// Delegate the call to the underlying SwitchInst::removeCase() and remove |
3600 | /// correspondent branch weight. |
3601 | SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I); |
3602 | |
3603 | /// Delegate the call to the underlying SwitchInst::addCase() and set the |
3604 | /// specified branch weight for the added case. |
3605 | void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W); |
3606 | |
3607 | /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark |
3608 | /// this object to not touch the underlying SwitchInst in destructor. |
3609 | SymbolTableList<Instruction>::iterator eraseFromParent(); |
3610 | |
3611 | void setSuccessorWeight(unsigned idx, CaseWeightOpt W); |
3612 | CaseWeightOpt getSuccessorWeight(unsigned idx); |
3613 | |
3614 | static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx); |
3615 | }; |
3616 | |
3617 | template <> |
3618 | struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> { |
3619 | }; |
3620 | |
3621 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)SwitchInst::op_iterator SwitchInst::op_begin() { return OperandTraits <SwitchInst>::op_begin(this); } SwitchInst::const_op_iterator SwitchInst::op_begin() const { return OperandTraits<SwitchInst >::op_begin(const_cast<SwitchInst*>(this)); } SwitchInst ::op_iterator SwitchInst::op_end() { return OperandTraits< SwitchInst>::op_end(this); } SwitchInst::const_op_iterator SwitchInst::op_end() const { return OperandTraits<SwitchInst >::op_end(const_cast<SwitchInst*>(this)); } Value *SwitchInst ::getOperand(unsigned i_nocapture) const { (static_cast <bool > (i_nocapture < OperandTraits<SwitchInst>::operands (this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 3621, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<SwitchInst >::op_begin(const_cast<SwitchInst*>(this))[i_nocapture ].get()); } void SwitchInst::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<SwitchInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 3621, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<SwitchInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned SwitchInst::getNumOperands() const { return OperandTraits<SwitchInst>::operands(this); } template <int Idx_nocapture> Use &SwitchInst::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &SwitchInst::Op() const { return this->OpFrom<Idx_nocapture>(this); } |
3622 | |
3623 | //===----------------------------------------------------------------------===// |
3624 | // IndirectBrInst Class |
3625 | //===----------------------------------------------------------------------===// |
3626 | |
3627 | //===--------------------------------------------------------------------------- |
3628 | /// Indirect Branch Instruction. |
3629 | /// |
3630 | class IndirectBrInst : public Instruction { |
3631 | unsigned ReservedSpace; |
3632 | |
3633 | // Operand[0] = Address to jump to |
3634 | // Operand[n+1] = n-th destination |
3635 | IndirectBrInst(const IndirectBrInst &IBI); |
3636 | |
3637 | /// Create a new indirectbr instruction, specifying an |
3638 | /// Address to jump to. The number of expected destinations can be specified |
3639 | /// here to make memory allocation more efficient. This constructor can also |
3640 | /// autoinsert before another instruction. |
3641 | IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore); |
3642 | |
3643 | /// Create a new indirectbr instruction, specifying an |
3644 | /// Address to jump to. The number of expected destinations can be specified |
3645 | /// here to make memory allocation more efficient. This constructor also |
3646 | /// autoinserts at the end of the specified BasicBlock. |
3647 | IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd); |
3648 | |
3649 | // allocate space for exactly zero operands |
3650 | void *operator new(size_t S) { return User::operator new(S); } |
3651 | |
3652 | void init(Value *Address, unsigned NumDests); |
3653 | void growOperands(); |
3654 | |
3655 | protected: |
3656 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3657 | friend class Instruction; |
3658 | |
3659 | IndirectBrInst *cloneImpl() const; |
3660 | |
3661 | public: |
3662 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
3663 | |
3664 | /// Iterator type that casts an operand to a basic block. |
3665 | /// |
3666 | /// This only makes sense because the successors are stored as adjacent |
3667 | /// operands for indirectbr instructions. |
3668 | struct succ_op_iterator |
3669 | : iterator_adaptor_base<succ_op_iterator, value_op_iterator, |
3670 | std::random_access_iterator_tag, BasicBlock *, |
3671 | ptrdiff_t, BasicBlock *, BasicBlock *> { |
3672 | explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {} |
3673 | |
3674 | BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3675 | BasicBlock *operator->() const { return operator*(); } |
3676 | }; |
3677 | |
3678 | /// The const version of `succ_op_iterator`. |
3679 | struct const_succ_op_iterator |
3680 | : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator, |
3681 | std::random_access_iterator_tag, |
3682 | const BasicBlock *, ptrdiff_t, const BasicBlock *, |
3683 | const BasicBlock *> { |
3684 | explicit const_succ_op_iterator(const_value_op_iterator I) |
3685 | : iterator_adaptor_base(I) {} |
3686 | |
3687 | const BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3688 | const BasicBlock *operator->() const { return operator*(); } |
3689 | }; |
3690 | |
3691 | static IndirectBrInst *Create(Value *Address, unsigned NumDests, |
3692 | Instruction *InsertBefore = nullptr) { |
3693 | return new IndirectBrInst(Address, NumDests, InsertBefore); |
3694 | } |
3695 | |
3696 | static IndirectBrInst *Create(Value *Address, unsigned NumDests, |
3697 | BasicBlock *InsertAtEnd) { |
3698 | return new IndirectBrInst(Address, NumDests, InsertAtEnd); |
3699 | } |
3700 | |
3701 | /// Provide fast operand accessors. |
3702 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
3703 | |
3704 | // Accessor Methods for IndirectBrInst instruction. |
3705 | Value *getAddress() { return getOperand(0); } |
3706 | const Value *getAddress() const { return getOperand(0); } |
3707 | void setAddress(Value *V) { setOperand(0, V); } |
3708 | |
3709 | /// return the number of possible destinations in this |
3710 | /// indirectbr instruction. |
3711 | unsigned getNumDestinations() const { return getNumOperands()-1; } |
3712 | |
3713 | /// Return the specified destination. |
3714 | BasicBlock *getDestination(unsigned i) { return getSuccessor(i); } |
3715 | const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); } |
3716 | |
3717 | /// Add a destination. |
3718 | /// |
3719 | void addDestination(BasicBlock *Dest); |
3720 | |
3721 | /// This method removes the specified successor from the |
3722 | /// indirectbr instruction. |
3723 | void removeDestination(unsigned i); |
3724 | |
3725 | unsigned getNumSuccessors() const { return getNumOperands()-1; } |
3726 | BasicBlock *getSuccessor(unsigned i) const { |
3727 | return cast<BasicBlock>(getOperand(i+1)); |
3728 | } |
3729 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
3730 | setOperand(i + 1, NewSucc); |
3731 | } |
3732 | |
3733 | iterator_range<succ_op_iterator> successors() { |
3734 | return make_range(succ_op_iterator(std::next(value_op_begin())), |
3735 | succ_op_iterator(value_op_end())); |
3736 | } |
3737 | |
3738 | iterator_range<const_succ_op_iterator> successors() const { |
3739 | return make_range(const_succ_op_iterator(std::next(value_op_begin())), |
3740 | const_succ_op_iterator(value_op_end())); |
3741 | } |
3742 | |
3743 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3744 | static bool classof(const Instruction *I) { |
3745 | return I->getOpcode() == Instruction::IndirectBr; |
3746 | } |
3747 | static bool classof(const Value *V) { |
3748 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3749 | } |
3750 | }; |
3751 | |
3752 | template <> |
3753 | struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> { |
3754 | }; |
3755 | |
3756 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)IndirectBrInst::op_iterator IndirectBrInst::op_begin() { return OperandTraits<IndirectBrInst>::op_begin(this); } IndirectBrInst ::const_op_iterator IndirectBrInst::op_begin() const { return OperandTraits<IndirectBrInst>::op_begin(const_cast< IndirectBrInst*>(this)); } IndirectBrInst::op_iterator IndirectBrInst ::op_end() { return OperandTraits<IndirectBrInst>::op_end (this); } IndirectBrInst::const_op_iterator IndirectBrInst::op_end () const { return OperandTraits<IndirectBrInst>::op_end (const_cast<IndirectBrInst*>(this)); } Value *IndirectBrInst ::getOperand(unsigned i_nocapture) const { (static_cast <bool > (i_nocapture < OperandTraits<IndirectBrInst>::operands (this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 3756, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<IndirectBrInst >::op_begin(const_cast<IndirectBrInst*>(this))[i_nocapture ].get()); } void IndirectBrInst::setOperand(unsigned i_nocapture , Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 3756, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<IndirectBrInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned IndirectBrInst::getNumOperands( ) const { return OperandTraits<IndirectBrInst>::operands (this); } template <int Idx_nocapture> Use &IndirectBrInst ::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &IndirectBrInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
3757 | |
3758 | //===----------------------------------------------------------------------===// |
3759 | // InvokeInst Class |
3760 | //===----------------------------------------------------------------------===// |
3761 | |
3762 | /// Invoke instruction. The SubclassData field is used to hold the |
3763 | /// calling convention of the call. |
3764 | /// |
3765 | class InvokeInst : public CallBase { |
3766 | /// The number of operands for this call beyond the called function, |
3767 | /// arguments, and operand bundles. |
3768 | static constexpr int NumExtraOperands = 2; |
3769 | |
3770 | /// The index from the end of the operand array to the normal destination. |
3771 | static constexpr int NormalDestOpEndIdx = -3; |
3772 | |
3773 | /// The index from the end of the operand array to the unwind destination. |
3774 | static constexpr int UnwindDestOpEndIdx = -2; |
3775 | |
3776 | InvokeInst(const InvokeInst &BI); |
3777 | |
3778 | /// Construct an InvokeInst given a range of arguments. |
3779 | /// |
3780 | /// Construct an InvokeInst from a range of arguments |
3781 | inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3782 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3783 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3784 | const Twine &NameStr, Instruction *InsertBefore); |
3785 | |
3786 | inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3787 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3788 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3789 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
3790 | |
3791 | void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3792 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3793 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
3794 | |
3795 | /// Compute the number of operands to allocate. |
3796 | static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) { |
3797 | // We need one operand for the called function, plus our extra operands and |
3798 | // the input operand counts provided. |
3799 | return 1 + NumExtraOperands + NumArgs + NumBundleInputs; |
3800 | } |
3801 | |
3802 | protected: |
3803 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3804 | friend class Instruction; |
3805 | |
3806 | InvokeInst *cloneImpl() const; |
3807 | |
3808 | public: |
3809 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3810 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3811 | const Twine &NameStr, |
3812 | Instruction *InsertBefore = nullptr) { |
3813 | int NumOperands = ComputeNumOperands(Args.size()); |
3814 | return new (NumOperands) |
3815 | InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands, |
3816 | NameStr, InsertBefore); |
3817 | } |
3818 | |
3819 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3820 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3821 | ArrayRef<OperandBundleDef> Bundles = None, |
3822 | const Twine &NameStr = "", |
3823 | Instruction *InsertBefore = nullptr) { |
3824 | int NumOperands = |
3825 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
3826 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
3827 | |
3828 | return new (NumOperands, DescriptorBytes) |
3829 | InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands, |
3830 | NameStr, InsertBefore); |
3831 | } |
3832 | |
3833 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3834 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3835 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3836 | int NumOperands = ComputeNumOperands(Args.size()); |
3837 | return new (NumOperands) |
3838 | InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands, |
3839 | NameStr, InsertAtEnd); |
3840 | } |
3841 | |
3842 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3843 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3844 | ArrayRef<OperandBundleDef> Bundles, |
3845 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3846 | int NumOperands = |
3847 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
3848 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
3849 | |
3850 | return new (NumOperands, DescriptorBytes) |
3851 | InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands, |
3852 | NameStr, InsertAtEnd); |
3853 | } |
3854 | |
3855 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3856 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3857 | const Twine &NameStr, |
3858 | Instruction *InsertBefore = nullptr) { |
3859 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3860 | IfException, Args, None, NameStr, InsertBefore); |
3861 | } |
3862 | |
3863 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3864 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3865 | ArrayRef<OperandBundleDef> Bundles = None, |
3866 | const Twine &NameStr = "", |
3867 | Instruction *InsertBefore = nullptr) { |
3868 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3869 | IfException, Args, Bundles, NameStr, InsertBefore); |
3870 | } |
3871 | |
3872 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3873 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3874 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3875 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3876 | IfException, Args, NameStr, InsertAtEnd); |
3877 | } |
3878 | |
3879 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3880 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3881 | ArrayRef<OperandBundleDef> Bundles, |
3882 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3883 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3884 | IfException, Args, Bundles, NameStr, InsertAtEnd); |
3885 | } |
3886 | |
3887 | /// Create a clone of \p II with a different set of operand bundles and |
3888 | /// insert it before \p InsertPt. |
3889 | /// |
3890 | /// The returned invoke instruction is identical to \p II in every way except |
3891 | /// that the operand bundles for the new instruction are set to the operand |
3892 | /// bundles in \p Bundles. |
3893 | static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles, |
3894 | Instruction *InsertPt = nullptr); |
3895 | |
3896 | // get*Dest - Return the destination basic blocks... |
3897 | BasicBlock *getNormalDest() const { |
3898 | return cast<BasicBlock>(Op<NormalDestOpEndIdx>()); |
3899 | } |
3900 | BasicBlock *getUnwindDest() const { |
3901 | return cast<BasicBlock>(Op<UnwindDestOpEndIdx>()); |
3902 | } |
3903 | void setNormalDest(BasicBlock *B) { |
3904 | Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B); |
3905 | } |
3906 | void setUnwindDest(BasicBlock *B) { |
3907 | Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B); |
3908 | } |
3909 | |
3910 | /// Get the landingpad instruction from the landing pad |
3911 | /// block (the unwind destination). |
3912 | LandingPadInst *getLandingPadInst() const; |
3913 | |
3914 | BasicBlock *getSuccessor(unsigned i) const { |
3915 | assert(i < 2 && "Successor # out of range for invoke!")(static_cast <bool> (i < 2 && "Successor # out of range for invoke!" ) ? void (0) : __assert_fail ("i < 2 && \"Successor # out of range for invoke!\"" , "llvm/include/llvm/IR/Instructions.h", 3915, __extension__ __PRETTY_FUNCTION__ )); |
3916 | return i == 0 ? getNormalDest() : getUnwindDest(); |
3917 | } |
3918 | |
3919 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
3920 | assert(i < 2 && "Successor # out of range for invoke!")(static_cast <bool> (i < 2 && "Successor # out of range for invoke!" ) ? void (0) : __assert_fail ("i < 2 && \"Successor # out of range for invoke!\"" , "llvm/include/llvm/IR/Instructions.h", 3920, __extension__ __PRETTY_FUNCTION__ )); |
3921 | if (i == 0) |
3922 | setNormalDest(NewSucc); |
3923 | else |
3924 | setUnwindDest(NewSucc); |
3925 | } |
3926 | |
3927 | unsigned getNumSuccessors() const { return 2; } |
3928 | |
3929 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3930 | static bool classof(const Instruction *I) { |
3931 | return (I->getOpcode() == Instruction::Invoke); |
3932 | } |
3933 | static bool classof(const Value *V) { |
3934 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3935 | } |
3936 | |
3937 | private: |
3938 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
3939 | // method so that subclasses cannot accidentally use it. |
3940 | template <typename Bitfield> |
3941 | void setSubclassData(typename Bitfield::Type Value) { |
3942 | Instruction::setSubclassData<Bitfield>(Value); |
3943 | } |
3944 | }; |
3945 | |
3946 | InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3947 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3948 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3949 | const Twine &NameStr, Instruction *InsertBefore) |
3950 | : CallBase(Ty->getReturnType(), Instruction::Invoke, |
3951 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
3952 | InsertBefore) { |
3953 | init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr); |
3954 | } |
3955 | |
3956 | InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3957 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3958 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3959 | const Twine &NameStr, BasicBlock *InsertAtEnd) |
3960 | : CallBase(Ty->getReturnType(), Instruction::Invoke, |
3961 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
3962 | InsertAtEnd) { |
3963 | init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr); |
3964 | } |
3965 | |
3966 | //===----------------------------------------------------------------------===// |
3967 | // CallBrInst Class |
3968 | //===----------------------------------------------------------------------===// |
3969 | |
3970 | /// CallBr instruction, tracking function calls that may not return control but |
3971 | /// instead transfer it to a third location. The SubclassData field is used to |
3972 | /// hold the calling convention of the call. |
3973 | /// |
3974 | class CallBrInst : public CallBase { |
3975 | |
3976 | unsigned NumIndirectDests; |
3977 | |
3978 | CallBrInst(const CallBrInst &BI); |
3979 | |
3980 | /// Construct a CallBrInst given a range of arguments. |
3981 | /// |
3982 | /// Construct a CallBrInst from a range of arguments |
3983 | inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
3984 | ArrayRef<BasicBlock *> IndirectDests, |
3985 | ArrayRef<Value *> Args, |
3986 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3987 | const Twine &NameStr, Instruction *InsertBefore); |
3988 | |
3989 | inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
3990 | ArrayRef<BasicBlock *> IndirectDests, |
3991 | ArrayRef<Value *> Args, |
3992 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3993 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
3994 | |
3995 | void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest, |
3996 | ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args, |
3997 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
3998 | |
3999 | /// Should the Indirect Destinations change, scan + update the Arg list. |
4000 | void updateArgBlockAddresses(unsigned i, BasicBlock *B); |
4001 | |
4002 | /// Compute the number of operands to allocate. |
4003 | static int ComputeNumOperands(int NumArgs, int NumIndirectDests, |
4004 | int NumBundleInputs = 0) { |
4005 | // We need one operand for the called function, plus our extra operands and |
4006 | // the input operand counts provided. |
4007 | return 2 + NumIndirectDests + NumArgs + NumBundleInputs; |
4008 | } |
4009 | |
4010 | protected: |
4011 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4012 | friend class Instruction; |
4013 | |
4014 | CallBrInst *cloneImpl() const; |
4015 | |
4016 | public: |
4017 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
4018 | BasicBlock *DefaultDest, |
4019 | ArrayRef<BasicBlock *> IndirectDests, |
4020 | ArrayRef<Value *> Args, const Twine &NameStr, |
4021 | Instruction *InsertBefore = nullptr) { |
4022 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size()); |
4023 | return new (NumOperands) |
4024 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None, |
4025 | NumOperands, NameStr, InsertBefore); |
4026 | } |
4027 | |
4028 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
4029 | BasicBlock *DefaultDest, |
4030 | ArrayRef<BasicBlock *> IndirectDests, |
4031 | ArrayRef<Value *> Args, |
4032 | ArrayRef<OperandBundleDef> Bundles = None, |
4033 | const Twine &NameStr = "", |
4034 | Instruction *InsertBefore = nullptr) { |
4035 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(), |
4036 | CountBundleInputs(Bundles)); |
4037 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
4038 | |
4039 | return new (NumOperands, DescriptorBytes) |
4040 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, |
4041 | NumOperands, NameStr, InsertBefore); |
4042 | } |
4043 | |
4044 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
4045 | BasicBlock *DefaultDest, |
4046 | ArrayRef<BasicBlock *> IndirectDests, |
4047 | ArrayRef<Value *> Args, const Twine &NameStr, |
4048 | BasicBlock *InsertAtEnd) { |
4049 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size()); |
4050 | return new (NumOperands) |
4051 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None, |
4052 | NumOperands, NameStr, InsertAtEnd); |
4053 | } |
4054 | |
4055 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
4056 | BasicBlock *DefaultDest, |
4057 | ArrayRef<BasicBlock *> IndirectDests, |
4058 | ArrayRef<Value *> Args, |
4059 | ArrayRef<OperandBundleDef> Bundles, |
4060 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
4061 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(), |
4062 | CountBundleInputs(Bundles)); |
4063 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
4064 | |
4065 | return new (NumOperands, DescriptorBytes) |
4066 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, |
4067 | NumOperands, NameStr, InsertAtEnd); |
4068 | } |
4069 | |
4070 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
4071 | ArrayRef<BasicBlock *> IndirectDests, |
4072 | ArrayRef<Value *> Args, const Twine &NameStr, |
4073 | Instruction *InsertBefore = nullptr) { |
4074 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
4075 | IndirectDests, Args, NameStr, InsertBefore); |
4076 | } |
4077 | |
4078 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
4079 | ArrayRef<BasicBlock *> IndirectDests, |
4080 | ArrayRef<Value *> Args, |
4081 | ArrayRef<OperandBundleDef> Bundles = None, |
4082 | const Twine &NameStr = "", |
4083 | Instruction *InsertBefore = nullptr) { |
4084 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
4085 | IndirectDests, Args, Bundles, NameStr, InsertBefore); |
4086 | } |
4087 | |
4088 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
4089 | ArrayRef<BasicBlock *> IndirectDests, |
4090 | ArrayRef<Value *> Args, const Twine &NameStr, |
4091 | BasicBlock *InsertAtEnd) { |
4092 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
4093 | IndirectDests, Args, NameStr, InsertAtEnd); |
4094 | } |
4095 | |
4096 | static CallBrInst *Create(FunctionCallee Func, |
4097 | BasicBlock *DefaultDest, |
4098 | ArrayRef<BasicBlock *> IndirectDests, |
4099 | ArrayRef<Value *> Args, |
4100 | ArrayRef<OperandBundleDef> Bundles, |
4101 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
4102 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
4103 | IndirectDests, Args, Bundles, NameStr, InsertAtEnd); |
4104 | } |
4105 | |
4106 | /// Create a clone of \p CBI with a different set of operand bundles and |
4107 | /// insert it before \p InsertPt. |
4108 | /// |
4109 | /// The returned callbr instruction is identical to \p CBI in every way |
4110 | /// except that the operand bundles for the new instruction are set to the |
4111 | /// operand bundles in \p Bundles. |
4112 | static CallBrInst *Create(CallBrInst *CBI, |
4113 | ArrayRef<OperandBundleDef> Bundles, |
4114 | Instruction *InsertPt = nullptr); |
4115 | |
4116 | /// Return the number of callbr indirect dest labels. |
4117 | /// |
4118 | unsigned getNumIndirectDests() const { return NumIndirectDests; } |
4119 | |
4120 | /// getIndirectDestLabel - Return the i-th indirect dest label. |
4121 | /// |
4122 | Value *getIndirectDestLabel(unsigned i) const { |
4123 | assert(i < getNumIndirectDests() && "Out of bounds!")(static_cast <bool> (i < getNumIndirectDests() && "Out of bounds!") ? void (0) : __assert_fail ("i < getNumIndirectDests() && \"Out of bounds!\"" , "llvm/include/llvm/IR/Instructions.h", 4123, __extension__ __PRETTY_FUNCTION__ )); |
4124 | return getOperand(i + arg_size() + getNumTotalBundleOperands() + 1); |
4125 | } |
4126 | |
4127 | Value *getIndirectDestLabelUse(unsigned i) const { |
4128 | assert(i < getNumIndirectDests() && "Out of bounds!")(static_cast <bool> (i < getNumIndirectDests() && "Out of bounds!") ? void (0) : __assert_fail ("i < getNumIndirectDests() && \"Out of bounds!\"" , "llvm/include/llvm/IR/Instructions.h", 4128, __extension__ __PRETTY_FUNCTION__ )); |
4129 | return getOperandUse(i + arg_size() + getNumTotalBundleOperands() + 1); |
4130 | } |
4131 | |
4132 | // Return the destination basic blocks... |
4133 | BasicBlock *getDefaultDest() const { |
4134 | return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1)); |
4135 | } |
4136 | BasicBlock *getIndirectDest(unsigned i) const { |
4137 | return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i)); |
4138 | } |
4139 | SmallVector<BasicBlock *, 16> getIndirectDests() const { |
4140 | SmallVector<BasicBlock *, 16> IndirectDests; |
4141 | for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i) |
4142 | IndirectDests.push_back(getIndirectDest(i)); |
4143 | return IndirectDests; |
4144 | } |
4145 | void setDefaultDest(BasicBlock *B) { |
4146 | *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B); |
4147 | } |
4148 | void setIndirectDest(unsigned i, BasicBlock *B) { |
4149 | updateArgBlockAddresses(i, B); |
4150 | *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B); |
4151 | } |
4152 | |
4153 | BasicBlock *getSuccessor(unsigned i) const { |
4154 | assert(i < getNumSuccessors() + 1 &&(static_cast <bool> (i < getNumSuccessors() + 1 && "Successor # out of range for callbr!") ? void (0) : __assert_fail ("i < getNumSuccessors() + 1 && \"Successor # out of range for callbr!\"" , "llvm/include/llvm/IR/Instructions.h", 4155, __extension__ __PRETTY_FUNCTION__ )) |
4155 | "Successor # out of range for callbr!")(static_cast <bool> (i < getNumSuccessors() + 1 && "Successor # out of range for callbr!") ? void (0) : __assert_fail ("i < getNumSuccessors() + 1 && \"Successor # out of range for callbr!\"" , "llvm/include/llvm/IR/Instructions.h", 4155, __extension__ __PRETTY_FUNCTION__ )); |
4156 | return i == 0 ? getDefaultDest() : getIndirectDest(i - 1); |
4157 | } |
4158 | |
4159 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
4160 | assert(i < getNumIndirectDests() + 1 &&(static_cast <bool> (i < getNumIndirectDests() + 1 && "Successor # out of range for callbr!") ? void (0) : __assert_fail ("i < getNumIndirectDests() + 1 && \"Successor # out of range for callbr!\"" , "llvm/include/llvm/IR/Instructions.h", 4161, __extension__ __PRETTY_FUNCTION__ )) |
4161 | "Successor # out of range for callbr!")(static_cast <bool> (i < getNumIndirectDests() + 1 && "Successor # out of range for callbr!") ? void (0) : __assert_fail ("i < getNumIndirectDests() + 1 && \"Successor # out of range for callbr!\"" , "llvm/include/llvm/IR/Instructions.h", 4161, __extension__ __PRETTY_FUNCTION__ )); |
4162 | return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc); |
4163 | } |
4164 | |
4165 | unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; } |
4166 | |
4167 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4168 | static bool classof(const Instruction *I) { |
4169 | return (I->getOpcode() == Instruction::CallBr); |
4170 | } |
4171 | static bool classof(const Value *V) { |
4172 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4173 | } |
4174 | |
4175 | private: |
4176 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
4177 | // method so that subclasses cannot accidentally use it. |
4178 | template <typename Bitfield> |
4179 | void setSubclassData(typename Bitfield::Type Value) { |
4180 | Instruction::setSubclassData<Bitfield>(Value); |
4181 | } |
4182 | }; |
4183 | |
4184 | CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
4185 | ArrayRef<BasicBlock *> IndirectDests, |
4186 | ArrayRef<Value *> Args, |
4187 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
4188 | const Twine &NameStr, Instruction *InsertBefore) |
4189 | : CallBase(Ty->getReturnType(), Instruction::CallBr, |
4190 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
4191 | InsertBefore) { |
4192 | init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr); |
4193 | } |
4194 | |
4195 | CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
4196 | ArrayRef<BasicBlock *> IndirectDests, |
4197 | ArrayRef<Value *> Args, |
4198 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
4199 | const Twine &NameStr, BasicBlock *InsertAtEnd) |
4200 | : CallBase(Ty->getReturnType(), Instruction::CallBr, |
4201 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
4202 | InsertAtEnd) { |
4203 | init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr); |
4204 | } |
4205 | |
4206 | //===----------------------------------------------------------------------===// |
4207 | // ResumeInst Class |
4208 | //===----------------------------------------------------------------------===// |
4209 | |
4210 | //===--------------------------------------------------------------------------- |
4211 | /// Resume the propagation of an exception. |
4212 | /// |
4213 | class ResumeInst : public Instruction { |
4214 | ResumeInst(const ResumeInst &RI); |
4215 | |
4216 | explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr); |
4217 | ResumeInst(Value *Exn, BasicBlock *InsertAtEnd); |
4218 | |
4219 | protected: |
4220 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4221 | friend class Instruction; |
4222 | |
4223 | ResumeInst *cloneImpl() const; |
4224 | |
4225 | public: |
4226 | static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) { |
4227 | return new(1) ResumeInst(Exn, InsertBefore); |
4228 | } |
4229 | |
4230 | static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) { |
4231 | return new(1) ResumeInst(Exn, InsertAtEnd); |
4232 | } |
4233 | |
4234 | /// Provide fast operand accessors |
4235 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
4236 | |
4237 | /// Convenience accessor. |
4238 | Value *getValue() const { return Op<0>(); } |
4239 | |
4240 | unsigned getNumSuccessors() const { return 0; } |
4241 | |
4242 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4243 | static bool classof(const Instruction *I) { |
4244 | return I->getOpcode() == Instruction::Resume; |
4245 | } |
4246 | static bool classof(const Value *V) { |
4247 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4248 | } |
4249 | |
4250 | private: |
4251 | BasicBlock *getSuccessor(unsigned idx) const { |
4252 | llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!" , "llvm/include/llvm/IR/Instructions.h", 4252); |
4253 | } |
4254 | |
4255 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
4256 | llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!" , "llvm/include/llvm/IR/Instructions.h", 4256); |
4257 | } |
4258 | }; |
4259 | |
4260 | template <> |
4261 | struct OperandTraits<ResumeInst> : |
4262 | public FixedNumOperandTraits<ResumeInst, 1> { |
4263 | }; |
4264 | |
4265 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)ResumeInst::op_iterator ResumeInst::op_begin() { return OperandTraits <ResumeInst>::op_begin(this); } ResumeInst::const_op_iterator ResumeInst::op_begin() const { return OperandTraits<ResumeInst >::op_begin(const_cast<ResumeInst*>(this)); } ResumeInst ::op_iterator ResumeInst::op_end() { return OperandTraits< ResumeInst>::op_end(this); } ResumeInst::const_op_iterator ResumeInst::op_end() const { return OperandTraits<ResumeInst >::op_end(const_cast<ResumeInst*>(this)); } Value *ResumeInst ::getOperand(unsigned i_nocapture) const { (static_cast <bool > (i_nocapture < OperandTraits<ResumeInst>::operands (this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ResumeInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 4265, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<ResumeInst >::op_begin(const_cast<ResumeInst*>(this))[i_nocapture ].get()); } void ResumeInst::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<ResumeInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<ResumeInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 4265, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<ResumeInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned ResumeInst::getNumOperands() const { return OperandTraits<ResumeInst>::operands(this); } template <int Idx_nocapture> Use &ResumeInst::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &ResumeInst::Op() const { return this->OpFrom<Idx_nocapture>(this); } |
4266 | |
4267 | //===----------------------------------------------------------------------===// |
4268 | // CatchSwitchInst Class |
4269 | //===----------------------------------------------------------------------===// |
4270 | class CatchSwitchInst : public Instruction { |
4271 | using UnwindDestField = BoolBitfieldElementT<0>; |
4272 | |
4273 | /// The number of operands actually allocated. NumOperands is |
4274 | /// the number actually in use. |
4275 | unsigned ReservedSpace; |
4276 | |
4277 | // Operand[0] = Outer scope |
4278 | // Operand[1] = Unwind block destination |
4279 | // Operand[n] = BasicBlock to go to on match |
4280 | CatchSwitchInst(const CatchSwitchInst &CSI); |
4281 | |
4282 | /// Create a new switch instruction, specifying a |
4283 | /// default destination. The number of additional handlers can be specified |
4284 | /// here to make memory allocation more efficient. |
4285 | /// This constructor can also autoinsert before another instruction. |
4286 | CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, |
4287 | unsigned NumHandlers, const Twine &NameStr, |
4288 | Instruction *InsertBefore); |
4289 | |
4290 | /// Create a new switch instruction, specifying a |
4291 | /// default destination. The number of additional handlers can be specified |
4292 | /// here to make memory allocation more efficient. |
4293 | /// This constructor also autoinserts at the end of the specified BasicBlock. |
4294 | CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, |
4295 | unsigned NumHandlers, const Twine &NameStr, |
4296 | BasicBlock *InsertAtEnd); |
4297 | |
4298 | // allocate space for exactly zero operands |
4299 | void *operator new(size_t S) { return User::operator new(S); } |
4300 | |
4301 | void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved); |
4302 | void growOperands(unsigned Size); |
4303 | |
4304 | protected: |
4305 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4306 | friend class Instruction; |
4307 | |
4308 | CatchSwitchInst *cloneImpl() const; |
4309 | |
4310 | public: |
4311 | void operator delete(void *Ptr) { return User::operator delete(Ptr); } |
4312 | |
4313 | static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest, |
4314 | unsigned NumHandlers, |
4315 | const Twine &NameStr = "", |
4316 | Instruction *InsertBefore = nullptr) { |
4317 | return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr, |
4318 | InsertBefore); |
4319 | } |
4320 | |
4321 | static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest, |
4322 | unsigned NumHandlers, const Twine &NameStr, |
4323 | BasicBlock *InsertAtEnd) { |
4324 | return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr, |
4325 | InsertAtEnd); |
4326 | } |
4327 | |
4328 | /// Provide fast operand accessors |
4329 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
4330 | |
4331 | // Accessor Methods for CatchSwitch stmt |
4332 | Value *getParentPad() const { return getOperand(0); } |
4333 | void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); } |
4334 | |
4335 | // Accessor Methods for CatchSwitch stmt |
4336 | bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); } |
4337 | bool unwindsToCaller() const { return !hasUnwindDest(); } |
4338 | BasicBlock *getUnwindDest() const { |
4339 | if (hasUnwindDest()) |
4340 | return cast<BasicBlock>(getOperand(1)); |
4341 | return nullptr; |
4342 | } |
4343 | void setUnwindDest(BasicBlock *UnwindDest) { |
4344 | assert(UnwindDest)(static_cast <bool> (UnwindDest) ? void (0) : __assert_fail ("UnwindDest", "llvm/include/llvm/IR/Instructions.h", 4344, __extension__ __PRETTY_FUNCTION__)); |
4345 | assert(hasUnwindDest())(static_cast <bool> (hasUnwindDest()) ? void (0) : __assert_fail ("hasUnwindDest()", "llvm/include/llvm/IR/Instructions.h", 4345 , __extension__ __PRETTY_FUNCTION__)); |
4346 | setOperand(1, UnwindDest); |
4347 | } |
4348 | |
4349 | /// return the number of 'handlers' in this catchswitch |
4350 | /// instruction, except the default handler |
4351 | unsigned getNumHandlers() const { |
4352 | if (hasUnwindDest()) |
4353 | return getNumOperands() - 2; |
4354 | return getNumOperands() - 1; |
4355 | } |
4356 | |
4357 | private: |
4358 | static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); } |
4359 | static const BasicBlock *handler_helper(const Value *V) { |
4360 | return cast<BasicBlock>(V); |
4361 | } |
4362 | |
4363 | public: |
4364 | using DerefFnTy = BasicBlock *(*)(Value *); |
4365 | using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>; |
4366 | using handler_range = iterator_range<handler_iterator>; |
4367 | using ConstDerefFnTy = const BasicBlock *(*)(const Value *); |
4368 | using const_handler_iterator = |
4369 | mapped_iterator<const_op_iterator, ConstDerefFnTy>; |
4370 | using const_handler_range = iterator_range<const_handler_iterator>; |
4371 | |
4372 | /// Returns an iterator that points to the first handler in CatchSwitchInst. |
4373 | handler_iterator handler_begin() { |
4374 | op_iterator It = op_begin() + 1; |
4375 | if (hasUnwindDest()) |
4376 | ++It; |
4377 | return handler_iterator(It, DerefFnTy(handler_helper)); |
4378 | } |
4379 | |
4380 | /// Returns an iterator that points to the first handler in the |
4381 | /// CatchSwitchInst. |
4382 | const_handler_iterator handler_begin() const { |
4383 | const_op_iterator It = op_begin() + 1; |
4384 | if (hasUnwindDest()) |
4385 | ++It; |
4386 | return const_handler_iterator(It, ConstDerefFnTy(handler_helper)); |
4387 | } |
4388 | |
4389 | /// Returns a read-only iterator that points one past the last |
4390 | /// handler in the CatchSwitchInst. |
4391 | handler_iterator handler_end() { |
4392 | return handler_iterator(op_end(), DerefFnTy(handler_helper)); |
4393 | } |
4394 | |
4395 | /// Returns an iterator that points one past the last handler in the |
4396 | /// CatchSwitchInst. |
4397 | const_handler_iterator handler_end() const { |
4398 | return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper)); |
4399 | } |
4400 | |
4401 | /// iteration adapter for range-for loops. |
4402 | handler_range handlers() { |
4403 | return make_range(handler_begin(), handler_end()); |
4404 | } |
4405 | |
4406 | /// iteration adapter for range-for loops. |
4407 | const_handler_range handlers() const { |
4408 | return make_range(handler_begin(), handler_end()); |
4409 | } |
4410 | |
4411 | /// Add an entry to the switch instruction... |
4412 | /// Note: |
4413 | /// This action invalidates handler_end(). Old handler_end() iterator will |
4414 | /// point to the added handler. |
4415 | void addHandler(BasicBlock *Dest); |
4416 | |
4417 | void removeHandler(handler_iterator HI); |
4418 | |
4419 | unsigned getNumSuccessors() const { return getNumOperands() - 1; } |
4420 | BasicBlock *getSuccessor(unsigned Idx) const { |
4421 | assert(Idx < getNumSuccessors() &&(static_cast <bool> (Idx < getNumSuccessors() && "Successor # out of range for catchswitch!") ? void (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\"" , "llvm/include/llvm/IR/Instructions.h", 4422, __extension__ __PRETTY_FUNCTION__ )) |
4422 | "Successor # out of range for catchswitch!")(static_cast <bool> (Idx < getNumSuccessors() && "Successor # out of range for catchswitch!") ? void (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\"" , "llvm/include/llvm/IR/Instructions.h", 4422, __extension__ __PRETTY_FUNCTION__ )); |
4423 | return cast<BasicBlock>(getOperand(Idx + 1)); |
4424 | } |
4425 | void setSuccessor(unsigned Idx, BasicBlock *NewSucc) { |
4426 | assert(Idx < getNumSuccessors() &&(static_cast <bool> (Idx < getNumSuccessors() && "Successor # out of range for catchswitch!") ? void (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\"" , "llvm/include/llvm/IR/Instructions.h", 4427, __extension__ __PRETTY_FUNCTION__ )) |
4427 | "Successor # out of range for catchswitch!")(static_cast <bool> (Idx < getNumSuccessors() && "Successor # out of range for catchswitch!") ? void (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\"" , "llvm/include/llvm/IR/Instructions.h", 4427, __extension__ __PRETTY_FUNCTION__ )); |
4428 | setOperand(Idx + 1, NewSucc); |
4429 | } |
4430 | |
4431 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4432 | static bool classof(const Instruction *I) { |
4433 | return I->getOpcode() == Instruction::CatchSwitch; |
4434 | } |
4435 | static bool classof(const Value *V) { |
4436 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4437 | } |
4438 | }; |
4439 | |
4440 | template <> |
4441 | struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {}; |
4442 | |
4443 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)CatchSwitchInst::op_iterator CatchSwitchInst::op_begin() { return OperandTraits<CatchSwitchInst>::op_begin(this); } CatchSwitchInst ::const_op_iterator CatchSwitchInst::op_begin() const { return OperandTraits<CatchSwitchInst>::op_begin(const_cast< CatchSwitchInst*>(this)); } CatchSwitchInst::op_iterator CatchSwitchInst ::op_end() { return OperandTraits<CatchSwitchInst>::op_end (this); } CatchSwitchInst::const_op_iterator CatchSwitchInst:: op_end() const { return OperandTraits<CatchSwitchInst>:: op_end(const_cast<CatchSwitchInst*>(this)); } Value *CatchSwitchInst ::getOperand(unsigned i_nocapture) const { (static_cast <bool > (i_nocapture < OperandTraits<CatchSwitchInst>:: operands(this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 4443, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<CatchSwitchInst >::op_begin(const_cast<CatchSwitchInst*>(this))[i_nocapture ].get()); } void CatchSwitchInst::setOperand(unsigned i_nocapture , Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 4443, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<CatchSwitchInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned CatchSwitchInst::getNumOperands () const { return OperandTraits<CatchSwitchInst>::operands (this); } template <int Idx_nocapture> Use &CatchSwitchInst ::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &CatchSwitchInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
4444 | |
4445 | //===----------------------------------------------------------------------===// |
4446 | // CleanupPadInst Class |
4447 | //===----------------------------------------------------------------------===// |
4448 | class CleanupPadInst : public FuncletPadInst { |
4449 | private: |
4450 | explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args, |
4451 | unsigned Values, const Twine &NameStr, |
4452 | Instruction *InsertBefore) |
4453 | : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values, |
4454 | NameStr, InsertBefore) {} |
4455 | explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args, |
4456 | unsigned Values, const Twine &NameStr, |
4457 | BasicBlock *InsertAtEnd) |
4458 | : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values, |
4459 | NameStr, InsertAtEnd) {} |
4460 | |
4461 | public: |
4462 | static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None, |
4463 | const Twine &NameStr = "", |
4464 | Instruction *InsertBefore = nullptr) { |
4465 | unsigned Values = 1 + Args.size(); |
4466 | return new (Values) |
4467 | CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore); |
4468 | } |
4469 | |
4470 | static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args, |
4471 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
4472 | unsigned Values = 1 + Args.size(); |
4473 | return new (Values) |
4474 | CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd); |
4475 | } |
4476 | |
4477 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4478 | static bool classof(const Instruction *I) { |
4479 | return I->getOpcode() == Instruction::CleanupPad; |
4480 | } |
4481 | static bool classof(const Value *V) { |
4482 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4483 | } |
4484 | }; |
4485 | |
4486 | //===----------------------------------------------------------------------===// |
4487 | // CatchPadInst Class |
4488 | //===----------------------------------------------------------------------===// |
4489 | class CatchPadInst : public FuncletPadInst { |
4490 | private: |
4491 | explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args, |
4492 | unsigned Values, const Twine &NameStr, |
4493 | Instruction *InsertBefore) |
4494 | : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values, |
4495 | NameStr, InsertBefore) {} |
4496 | explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args, |
4497 | unsigned Values, const Twine &NameStr, |
4498 | BasicBlock *InsertAtEnd) |
4499 | : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values, |
4500 | NameStr, InsertAtEnd) {} |
4501 | |
4502 | public: |
4503 | static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args, |
4504 | const Twine &NameStr = "", |
4505 | Instruction *InsertBefore = nullptr) { |
4506 | unsigned Values = 1 + Args.size(); |
4507 | return new (Values) |
4508 | CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore); |
4509 | } |
4510 | |
4511 | static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args, |
4512 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
4513 | unsigned Values = 1 + Args.size(); |
4514 | return new (Values) |
4515 | CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd); |
4516 | } |
4517 | |
4518 | /// Convenience accessors |
4519 | CatchSwitchInst *getCatchSwitch() const { |
4520 | return cast<CatchSwitchInst>(Op<-1>()); |
4521 | } |
4522 | void setCatchSwitch(Value *CatchSwitch) { |
4523 | assert(CatchSwitch)(static_cast <bool> (CatchSwitch) ? void (0) : __assert_fail ("CatchSwitch", "llvm/include/llvm/IR/Instructions.h", 4523, __extension__ __PRETTY_FUNCTION__)); |
4524 | Op<-1>() = CatchSwitch; |
4525 | } |
4526 | |
4527 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4528 | static bool classof(const Instruction *I) { |
4529 | return I->getOpcode() == Instruction::CatchPad; |
4530 | } |
4531 | static bool classof(const Value *V) { |
4532 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4533 | } |
4534 | }; |
4535 | |
4536 | //===----------------------------------------------------------------------===// |
4537 | // CatchReturnInst Class |
4538 | //===----------------------------------------------------------------------===// |
4539 | |
4540 | class CatchReturnInst : public Instruction { |
4541 | CatchReturnInst(const CatchReturnInst &RI); |
4542 | CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore); |
4543 | CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd); |
4544 | |
4545 | void init(Value *CatchPad, BasicBlock *BB); |
4546 | |
4547 | protected: |
4548 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4549 | friend class Instruction; |
4550 | |
4551 | CatchReturnInst *cloneImpl() const; |
4552 | |
4553 | public: |
4554 | static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB, |
4555 | Instruction *InsertBefore = nullptr) { |
4556 | assert(CatchPad)(static_cast <bool> (CatchPad) ? void (0) : __assert_fail ("CatchPad", "llvm/include/llvm/IR/Instructions.h", 4556, __extension__ __PRETTY_FUNCTION__)); |
4557 | assert(BB)(static_cast <bool> (BB) ? void (0) : __assert_fail ("BB" , "llvm/include/llvm/IR/Instructions.h", 4557, __extension__ __PRETTY_FUNCTION__ )); |
4558 | return new (2) CatchReturnInst(CatchPad, BB, InsertBefore); |
4559 | } |
4560 | |
4561 | static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB, |
4562 | BasicBlock *InsertAtEnd) { |
4563 | assert(CatchPad)(static_cast <bool> (CatchPad) ? void (0) : __assert_fail ("CatchPad", "llvm/include/llvm/IR/Instructions.h", 4563, __extension__ __PRETTY_FUNCTION__)); |
4564 | assert(BB)(static_cast <bool> (BB) ? void (0) : __assert_fail ("BB" , "llvm/include/llvm/IR/Instructions.h", 4564, __extension__ __PRETTY_FUNCTION__ )); |
4565 | return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd); |
4566 | } |
4567 | |
4568 | /// Provide fast operand accessors |
4569 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
4570 | |
4571 | /// Convenience accessors. |
4572 | CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); } |
4573 | void setCatchPad(CatchPadInst *CatchPad) { |
4574 | assert(CatchPad)(static_cast <bool> (CatchPad) ? void (0) : __assert_fail ("CatchPad", "llvm/include/llvm/IR/Instructions.h", 4574, __extension__ __PRETTY_FUNCTION__)); |
4575 | Op<0>() = CatchPad; |
4576 | } |
4577 | |
4578 | BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); } |
4579 | void setSuccessor(BasicBlock *NewSucc) { |
4580 | assert(NewSucc)(static_cast <bool> (NewSucc) ? void (0) : __assert_fail ("NewSucc", "llvm/include/llvm/IR/Instructions.h", 4580, __extension__ __PRETTY_FUNCTION__)); |
4581 | Op<1>() = NewSucc; |
4582 | } |
4583 | unsigned getNumSuccessors() const { return 1; } |
4584 | |
4585 | /// Get the parentPad of this catchret's catchpad's catchswitch. |
4586 | /// The successor block is implicitly a member of this funclet. |
4587 | Value *getCatchSwitchParentPad() const { |
4588 | return getCatchPad()->getCatchSwitch()->getParentPad(); |
4589 | } |
4590 | |
4591 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4592 | static bool classof(const Instruction *I) { |
4593 | return (I->getOpcode() == Instruction::CatchRet); |
4594 | } |
4595 | static bool classof(const Value *V) { |
4596 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4597 | } |
4598 | |
4599 | private: |
4600 | BasicBlock *getSuccessor(unsigned Idx) const { |
4601 | assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!")(static_cast <bool> (Idx < getNumSuccessors() && "Successor # out of range for catchret!") ? void (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchret!\"" , "llvm/include/llvm/IR/Instructions.h", 4601, __extension__ __PRETTY_FUNCTION__ )); |
4602 | return getSuccessor(); |
4603 | } |
4604 | |
4605 | void setSuccessor(unsigned Idx, BasicBlock *B) { |
4606 | assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!")(static_cast <bool> (Idx < getNumSuccessors() && "Successor # out of range for catchret!") ? void (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchret!\"" , "llvm/include/llvm/IR/Instructions.h", 4606, __extension__ __PRETTY_FUNCTION__ )); |
4607 | setSuccessor(B); |
4608 | } |
4609 | }; |
4610 | |
4611 | template <> |
4612 | struct OperandTraits<CatchReturnInst> |
4613 | : public FixedNumOperandTraits<CatchReturnInst, 2> {}; |
4614 | |
4615 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)CatchReturnInst::op_iterator CatchReturnInst::op_begin() { return OperandTraits<CatchReturnInst>::op_begin(this); } CatchReturnInst ::const_op_iterator CatchReturnInst::op_begin() const { return OperandTraits<CatchReturnInst>::op_begin(const_cast< CatchReturnInst*>(this)); } CatchReturnInst::op_iterator CatchReturnInst ::op_end() { return OperandTraits<CatchReturnInst>::op_end (this); } CatchReturnInst::const_op_iterator CatchReturnInst:: op_end() const { return OperandTraits<CatchReturnInst>:: op_end(const_cast<CatchReturnInst*>(this)); } Value *CatchReturnInst ::getOperand(unsigned i_nocapture) const { (static_cast <bool > (i_nocapture < OperandTraits<CatchReturnInst>:: operands(this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 4615, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<CatchReturnInst >::op_begin(const_cast<CatchReturnInst*>(this))[i_nocapture ].get()); } void CatchReturnInst::setOperand(unsigned i_nocapture , Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 4615, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<CatchReturnInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned CatchReturnInst::getNumOperands () const { return OperandTraits<CatchReturnInst>::operands (this); } template <int Idx_nocapture> Use &CatchReturnInst ::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &CatchReturnInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
4616 | |
4617 | //===----------------------------------------------------------------------===// |
4618 | // CleanupReturnInst Class |
4619 | //===----------------------------------------------------------------------===// |
4620 | |
4621 | class CleanupReturnInst : public Instruction { |
4622 | using UnwindDestField = BoolBitfieldElementT<0>; |
4623 | |
4624 | private: |
4625 | CleanupReturnInst(const CleanupReturnInst &RI); |
4626 | CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values, |
4627 | Instruction *InsertBefore = nullptr); |
4628 | CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values, |
4629 | BasicBlock *InsertAtEnd); |
4630 | |
4631 | void init(Value *CleanupPad, BasicBlock *UnwindBB); |
4632 | |
4633 | protected: |
4634 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4635 | friend class Instruction; |
4636 | |
4637 | CleanupReturnInst *cloneImpl() const; |
4638 | |
4639 | public: |
4640 | static CleanupReturnInst *Create(Value *CleanupPad, |
4641 | BasicBlock *UnwindBB = nullptr, |
4642 | Instruction *InsertBefore = nullptr) { |
4643 | assert(CleanupPad)(static_cast <bool> (CleanupPad) ? void (0) : __assert_fail ("CleanupPad", "llvm/include/llvm/IR/Instructions.h", 4643, __extension__ __PRETTY_FUNCTION__)); |
4644 | unsigned Values = 1; |
4645 | if (UnwindBB) |
4646 | ++Values; |
4647 | return new (Values) |
4648 | CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore); |
4649 | } |
4650 | |
4651 | static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB, |
4652 | BasicBlock *InsertAtEnd) { |
4653 | assert(CleanupPad)(static_cast <bool> (CleanupPad) ? void (0) : __assert_fail ("CleanupPad", "llvm/include/llvm/IR/Instructions.h", 4653, __extension__ __PRETTY_FUNCTION__)); |
4654 | unsigned Values = 1; |
4655 | if (UnwindBB) |
4656 | ++Values; |
4657 | return new (Values) |
4658 | CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd); |
4659 | } |
4660 | |
4661 | /// Provide fast operand accessors |
4662 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
4663 | |
4664 | bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); } |
4665 | bool unwindsToCaller() const { return !hasUnwindDest(); } |
4666 | |
4667 | /// Convenience accessor. |
4668 | CleanupPadInst *getCleanupPad() const { |
4669 | return cast<CleanupPadInst>(Op<0>()); |
4670 | } |
4671 | void setCleanupPad(CleanupPadInst *CleanupPad) { |
4672 | assert(CleanupPad)(static_cast <bool> (CleanupPad) ? void (0) : __assert_fail ("CleanupPad", "llvm/include/llvm/IR/Instructions.h", 4672, __extension__ __PRETTY_FUNCTION__)); |
4673 | Op<0>() = CleanupPad; |
4674 | } |
4675 | |
4676 | unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; } |
4677 | |
4678 | BasicBlock *getUnwindDest() const { |
4679 | return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr; |
4680 | } |
4681 | void setUnwindDest(BasicBlock *NewDest) { |
4682 | assert(NewDest)(static_cast <bool> (NewDest) ? void (0) : __assert_fail ("NewDest", "llvm/include/llvm/IR/Instructions.h", 4682, __extension__ __PRETTY_FUNCTION__)); |
4683 | assert(hasUnwindDest())(static_cast <bool> (hasUnwindDest()) ? void (0) : __assert_fail ("hasUnwindDest()", "llvm/include/llvm/IR/Instructions.h", 4683 , __extension__ __PRETTY_FUNCTION__)); |
4684 | Op<1>() = NewDest; |
4685 | } |
4686 | |
4687 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4688 | static bool classof(const Instruction *I) { |
4689 | return (I->getOpcode() == Instruction::CleanupRet); |
4690 | } |
4691 | static bool classof(const Value *V) { |
4692 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4693 | } |
4694 | |
4695 | private: |
4696 | BasicBlock *getSuccessor(unsigned Idx) const { |
4697 | assert(Idx == 0)(static_cast <bool> (Idx == 0) ? void (0) : __assert_fail ("Idx == 0", "llvm/include/llvm/IR/Instructions.h", 4697, __extension__ __PRETTY_FUNCTION__)); |
4698 | return getUnwindDest(); |
4699 | } |
4700 | |
4701 | void setSuccessor(unsigned Idx, BasicBlock *B) { |
4702 | assert(Idx == 0)(static_cast <bool> (Idx == 0) ? void (0) : __assert_fail ("Idx == 0", "llvm/include/llvm/IR/Instructions.h", 4702, __extension__ __PRETTY_FUNCTION__)); |
4703 | setUnwindDest(B); |
4704 | } |
4705 | |
4706 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
4707 | // method so that subclasses cannot accidentally use it. |
4708 | template <typename Bitfield> |
4709 | void setSubclassData(typename Bitfield::Type Value) { |
4710 | Instruction::setSubclassData<Bitfield>(Value); |
4711 | } |
4712 | }; |
4713 | |
4714 | template <> |
4715 | struct OperandTraits<CleanupReturnInst> |
4716 | : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {}; |
4717 | |
4718 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)CleanupReturnInst::op_iterator CleanupReturnInst::op_begin() { return OperandTraits<CleanupReturnInst>::op_begin(this ); } CleanupReturnInst::const_op_iterator CleanupReturnInst:: op_begin() const { return OperandTraits<CleanupReturnInst> ::op_begin(const_cast<CleanupReturnInst*>(this)); } CleanupReturnInst ::op_iterator CleanupReturnInst::op_end() { return OperandTraits <CleanupReturnInst>::op_end(this); } CleanupReturnInst:: const_op_iterator CleanupReturnInst::op_end() const { return OperandTraits <CleanupReturnInst>::op_end(const_cast<CleanupReturnInst *>(this)); } Value *CleanupReturnInst::getOperand(unsigned i_nocapture) const { (static_cast <bool> (i_nocapture < OperandTraits<CleanupReturnInst>::operands(this) && "getOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CleanupReturnInst>::operands(this) && \"getOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 4718, __extension__ __PRETTY_FUNCTION__ )); return cast_or_null<Value>( OperandTraits<CleanupReturnInst >::op_begin(const_cast<CleanupReturnInst*>(this))[i_nocapture ].get()); } void CleanupReturnInst::setOperand(unsigned i_nocapture , Value *Val_nocapture) { (static_cast <bool> (i_nocapture < OperandTraits<CleanupReturnInst>::operands(this) && "setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<CleanupReturnInst>::operands(this) && \"setOperand() out of range!\"" , "llvm/include/llvm/IR/Instructions.h", 4718, __extension__ __PRETTY_FUNCTION__ )); OperandTraits<CleanupReturnInst>::op_begin(this)[i_nocapture ] = Val_nocapture; } unsigned CleanupReturnInst::getNumOperands () const { return OperandTraits<CleanupReturnInst>::operands (this); } template <int Idx_nocapture> Use &CleanupReturnInst ::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &CleanupReturnInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
4719 | |
4720 | //===----------------------------------------------------------------------===// |
4721 | // UnreachableInst Class |
4722 | //===----------------------------------------------------------------------===// |
4723 | |
4724 | //===--------------------------------------------------------------------------- |
4725 | /// This function has undefined behavior. In particular, the |
4726 | /// presence of this instruction indicates some higher level knowledge that the |
4727 | /// end of the block cannot be reached. |
4728 | /// |
4729 | class UnreachableInst : public Instruction { |
4730 | protected: |
4731 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4732 | friend class Instruction; |
4733 | |
4734 | UnreachableInst *cloneImpl() const; |
4735 | |
4736 | public: |
4737 | explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr); |
4738 | explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd); |
4739 | |
4740 | // allocate space for exactly zero operands |
4741 | void *operator new(size_t S) { return User::operator new(S, 0); } |
4742 | void operator delete(void *Ptr) { User::operator delete(Ptr); } |
4743 | |
4744 | unsigned getNumSuccessors() const { return 0; } |
4745 | |
4746 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4747 | static bool classof(const Instruction *I) { |
4748 | return I->getOpcode() == Instruction::Unreachable; |
4749 | } |
4750 | static bool classof(const Value *V) { |
4751 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4752 | } |
4753 | |
4754 | private: |
4755 | BasicBlock *getSuccessor(unsigned idx) const { |
4756 | llvm_unreachable("UnreachableInst has no successors!")::llvm::llvm_unreachable_internal("UnreachableInst has no successors!" , "llvm/include/llvm/IR/Instructions.h", 4756); |
4757 | } |
4758 | |
4759 | void setSuccessor(unsigned idx, BasicBlock *B) { |
4760 | llvm_unreachable("UnreachableInst has no successors!")::llvm::llvm_unreachable_internal("UnreachableInst has no successors!" , "llvm/include/llvm/IR/Instructions.h", 4760); |
4761 | } |
4762 | }; |
4763 | |
4764 | //===----------------------------------------------------------------------===// |
4765 | // TruncInst Class |
4766 | //===----------------------------------------------------------------------===// |
4767 | |
4768 | /// This class represents a truncation of integer types. |
4769 | class TruncInst : public CastInst { |
4770 | protected: |
4771 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4772 | friend class Instruction; |
4773 | |
4774 | /// Clone an identical TruncInst |
4775 | TruncInst *cloneImpl() const; |
4776 | |
4777 | public: |
4778 | /// Constructor with insert-before-instruction semantics |
4779 | TruncInst( |
4780 | Value *S, ///< The value to be truncated |
4781 | Type *Ty, ///< The (smaller) type to truncate to |
4782 | const Twine &NameStr = "", ///< A name for the new instruction |
4783 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4784 | ); |
4785 | |
4786 | /// Constructor with insert-at-end-of-block semantics |
4787 | TruncInst( |
4788 | Value *S, ///< The value to be truncated |
4789 | Type *Ty, ///< The (smaller) type to truncate to |
4790 | const Twine &NameStr, ///< A name for the new instruction |
4791 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4792 | ); |
4793 | |
4794 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4795 | static bool classof(const Instruction *I) { |
4796 | return I->getOpcode() == Trunc; |
4797 | } |
4798 | static bool classof(const Value *V) { |
4799 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4800 | } |
4801 | }; |
4802 | |
4803 | //===----------------------------------------------------------------------===// |
4804 | // ZExtInst Class |
4805 | //===----------------------------------------------------------------------===// |
4806 | |
4807 | /// This class represents zero extension of integer types. |
4808 | class ZExtInst : public CastInst { |
4809 | protected: |
4810 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4811 | friend class Instruction; |
4812 | |
4813 | /// Clone an identical ZExtInst |
4814 | ZExtInst *cloneImpl() const; |
4815 | |
4816 | public: |
4817 | /// Constructor with insert-before-instruction semantics |
4818 | ZExtInst( |
4819 | Value *S, ///< The value to be zero extended |
4820 | Type *Ty, ///< The type to zero extend to |
4821 | const Twine &NameStr = "", ///< A name for the new instruction |
4822 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4823 | ); |
4824 | |
4825 | /// Constructor with insert-at-end semantics. |
4826 | ZExtInst( |
4827 | Value *S, ///< The value to be zero extended |
4828 | Type *Ty, ///< The type to zero extend to |
4829 | const Twine &NameStr, ///< A name for the new instruction |
4830 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4831 | ); |
4832 | |
4833 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4834 | static bool classof(const Instruction *I) { |
4835 | return I->getOpcode() == ZExt; |
4836 | } |
4837 | static bool classof(const Value *V) { |
4838 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4839 | } |
4840 | }; |
4841 | |
4842 | //===----------------------------------------------------------------------===// |
4843 | // SExtInst Class |
4844 | //===----------------------------------------------------------------------===// |
4845 | |
4846 | /// This class represents a sign extension of integer types. |
4847 | class SExtInst : public CastInst { |
4848 | protected: |
4849 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4850 | friend class Instruction; |
4851 | |
4852 | /// Clone an identical SExtInst |
4853 | SExtInst *cloneImpl() const; |
4854 | |
4855 | public: |
4856 | /// Constructor with insert-before-instruction semantics |
4857 | SExtInst( |
4858 | Value *S, ///< The value to be sign extended |
4859 | Type *Ty, ///< The type to sign extend to |
4860 | const Twine &NameStr = "", ///< A name for the new instruction |
4861 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4862 | ); |
4863 | |
4864 | /// Constructor with insert-at-end-of-block semantics |
4865 | SExtInst( |
4866 | Value *S, ///< The value to be sign extended |
4867 | Type *Ty, ///< The type to sign extend to |
4868 | const Twine &NameStr, ///< A name for the new instruction |
4869 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4870 | ); |
4871 | |
4872 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4873 | static bool classof(const Instruction *I) { |
4874 | return I->getOpcode() == SExt; |
4875 | } |
4876 | static bool classof(const Value *V) { |
4877 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4878 | } |
4879 | }; |
4880 | |
4881 | //===----------------------------------------------------------------------===// |
4882 | // FPTruncInst Class |
4883 | //===----------------------------------------------------------------------===// |
4884 | |
4885 | /// This class represents a truncation of floating point types. |
4886 | class FPTruncInst : public CastInst { |
4887 | protected: |
4888 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4889 | friend class Instruction; |
4890 | |
4891 | /// Clone an identical FPTruncInst |
4892 | FPTruncInst *cloneImpl() const; |
4893 | |
4894 | public: |
4895 | /// Constructor with insert-before-instruction semantics |
4896 | FPTruncInst( |
4897 | Value *S, ///< The value to be truncated |
4898 | Type *Ty, ///< The type to truncate to |
4899 | const Twine &NameStr = "", ///< A name for the new instruction |
4900 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4901 | ); |
4902 | |
4903 | /// Constructor with insert-before-instruction semantics |
4904 | FPTruncInst( |
4905 | Value *S, ///< The value to be truncated |
4906 | Type *Ty, ///< The type to truncate to |
4907 | const Twine &NameStr, ///< A name for the new instruction |
4908 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4909 | ); |
4910 | |
4911 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4912 | static bool classof(const Instruction *I) { |
4913 | return I->getOpcode() == FPTrunc; |
4914 | } |
4915 | static bool classof(const Value *V) { |
4916 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4917 | } |
4918 | }; |
4919 | |
4920 | //===----------------------------------------------------------------------===// |
4921 | // FPExtInst Class |
4922 | //===----------------------------------------------------------------------===// |
4923 | |
4924 | /// This class represents an extension of floating point types. |
4925 | class FPExtInst : public CastInst { |
4926 | protected: |
4927 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4928 | friend class Instruction; |
4929 | |
4930 | /// Clone an identical FPExtInst |
4931 | FPExtInst *cloneImpl() const; |
4932 | |
4933 | public: |
4934 | /// Constructor with insert-before-instruction semantics |
4935 | FPExtInst( |
4936 | Value *S, ///< The value to be extended |
4937 | Type *Ty, ///< The type to extend to |
4938 | const Twine &NameStr = "", ///< A name for the new instruction |
4939 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4940 | ); |
4941 | |
4942 | /// Constructor with insert-at-end-of-block semantics |
4943 | FPExtInst( |
4944 | Value *S, ///< The value to be extended |
4945 | Type *Ty, ///< The type to extend to |
4946 | const Twine &NameStr, ///< A name for the new instruction |
4947 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4948 | ); |
4949 | |
4950 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4951 | static bool classof(const Instruction *I) { |
4952 | return I->getOpcode() == FPExt; |
4953 | } |
4954 | static bool classof(const Value *V) { |
4955 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4956 | } |
4957 | }; |
4958 | |
4959 | //===----------------------------------------------------------------------===// |
4960 | // UIToFPInst Class |
4961 | //===----------------------------------------------------------------------===// |
4962 | |
4963 | /// This class represents a cast unsigned integer to floating point. |
4964 | class UIToFPInst : public CastInst { |
4965 | protected: |
4966 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4967 | friend class Instruction; |
4968 | |
4969 | /// Clone an identical UIToFPInst |
4970 | UIToFPInst *cloneImpl() const; |
4971 | |
4972 | public: |
4973 | /// Constructor with insert-before-instruction semantics |
4974 | UIToFPInst( |
4975 | Value *S, ///< The value to be converted |
4976 | Type *Ty, ///< The type to convert to |
4977 | const Twine &NameStr = "", ///< A name for the new instruction |
4978 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4979 | ); |
4980 | |
4981 | /// Constructor with insert-at-end-of-block semantics |
4982 | UIToFPInst( |
4983 | Value *S, ///< The value to be converted |
4984 | Type *Ty, ///< The type to convert to |
4985 | const Twine &NameStr, ///< A name for the new instruction |
4986 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4987 | ); |
4988 | |
4989 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4990 | static bool classof(const Instruction *I) { |
4991 | return I->getOpcode() == UIToFP; |
4992 | } |
4993 | static bool classof(const Value *V) { |
4994 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4995 | } |
4996 | }; |
4997 | |
4998 | //===----------------------------------------------------------------------===// |
4999 | // SIToFPInst Class |
5000 | //===----------------------------------------------------------------------===// |
5001 | |
5002 | /// This class represents a cast from signed integer to floating point. |
5003 | class SIToFPInst : public CastInst { |
5004 | protected: |
5005 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5006 | friend class Instruction; |
5007 | |
5008 | /// Clone an identical SIToFPInst |
5009 | SIToFPInst *cloneImpl() const; |
5010 | |
5011 | public: |
5012 | /// Constructor with insert-before-instruction semantics |
5013 | SIToFPInst( |
5014 | Value *S, ///< The value to be converted |
5015 | Type *Ty, ///< The type to convert to |
5016 | const Twine &NameStr = "", ///< A name for the new instruction |
5017 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5018 | ); |
5019 | |
5020 | /// Constructor with insert-at-end-of-block semantics |
5021 | SIToFPInst( |
5022 | Value *S, ///< The value to be converted |
5023 | Type *Ty, ///< The type to convert to |
5024 | const Twine &NameStr, ///< A name for the new instruction |
5025 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5026 | ); |
5027 | |
5028 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
5029 | static bool classof(const Instruction *I) { |
5030 | return I->getOpcode() == SIToFP; |
5031 | } |
5032 | static bool classof(const Value *V) { |
5033 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5034 | } |
5035 | }; |
5036 | |
5037 | //===----------------------------------------------------------------------===// |
5038 | // FPToUIInst Class |
5039 | //===----------------------------------------------------------------------===// |
5040 | |
5041 | /// This class represents a cast from floating point to unsigned integer |
5042 | class FPToUIInst : public CastInst { |
5043 | protected: |
5044 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5045 | friend class Instruction; |
5046 | |
5047 | /// Clone an identical FPToUIInst |
5048 | FPToUIInst *cloneImpl() const; |
5049 | |
5050 | public: |
5051 | /// Constructor with insert-before-instruction semantics |
5052 | FPToUIInst( |
5053 | Value *S, ///< The value to be converted |
5054 | Type *Ty, ///< The type to convert to |
5055 | const Twine &NameStr = "", ///< A name for the new instruction |
5056 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5057 | ); |
5058 | |
5059 | /// Constructor with insert-at-end-of-block semantics |
5060 | FPToUIInst( |
5061 | Value *S, ///< The value to be converted |
5062 | Type *Ty, ///< The type to convert to |
5063 | const Twine &NameStr, ///< A name for the new instruction |
5064 | BasicBlock *InsertAtEnd ///< Where to insert the new instruction |
5065 | ); |
5066 | |
5067 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
5068 | static bool classof(const Instruction *I) { |
5069 | return I->getOpcode() == FPToUI; |
5070 | } |
5071 | static bool classof(const Value *V) { |
5072 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5073 | } |
5074 | }; |
5075 | |
5076 | //===----------------------------------------------------------------------===// |
5077 | // FPToSIInst Class |
5078 | //===----------------------------------------------------------------------===// |
5079 | |
5080 | /// This class represents a cast from floating point to signed integer. |
5081 | class FPToSIInst : public CastInst { |
5082 | protected: |
5083 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5084 | friend class Instruction; |
5085 | |
5086 | /// Clone an identical FPToSIInst |
5087 | FPToSIInst *cloneImpl() const; |
5088 | |
5089 | public: |
5090 | /// Constructor with insert-before-instruction semantics |
5091 | FPToSIInst( |
5092 | Value *S, ///< The value to be converted |
5093 | Type *Ty, ///< The type to convert to |
5094 | const Twine &NameStr = "", ///< A name for the new instruction |
5095 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5096 | ); |
5097 | |
5098 | /// Constructor with insert-at-end-of-block semantics |
5099 | FPToSIInst( |
5100 | Value *S, ///< The value to be converted |
5101 | Type *Ty, ///< The type to convert to |
5102 | const Twine &NameStr, ///< A name for the new instruction |
5103 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5104 | ); |
5105 | |
5106 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
5107 | static bool classof(const Instruction *I) { |
5108 | return I->getOpcode() == FPToSI; |
5109 | } |
5110 | static bool classof(const Value *V) { |
5111 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5112 | } |
5113 | }; |
5114 | |
5115 | //===----------------------------------------------------------------------===// |
5116 | // IntToPtrInst Class |
5117 | //===----------------------------------------------------------------------===// |
5118 | |
5119 | /// This class represents a cast from an integer to a pointer. |
5120 | class IntToPtrInst : public CastInst { |
5121 | public: |
5122 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5123 | friend class Instruction; |
5124 | |
5125 | /// Constructor with insert-before-instruction semantics |
5126 | IntToPtrInst( |
5127 | Value *S, ///< The value to be converted |
5128 | Type *Ty, ///< The type to convert to |
5129 | const Twine &NameStr = "", ///< A name for the new instruction |
5130 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5131 | ); |
5132 | |
5133 | /// Constructor with insert-at-end-of-block semantics |
5134 | IntToPtrInst( |
5135 | Value *S, ///< The value to be converted |
5136 | Type *Ty, ///< The type to convert to |
5137 | const Twine &NameStr, ///< A name for the new instruction |
5138 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5139 | ); |
5140 | |
5141 | /// Clone an identical IntToPtrInst. |
5142 | IntToPtrInst *cloneImpl() const; |
5143 | |
5144 | /// Returns the address space of this instruction's pointer type. |
5145 | unsigned getAddressSpace() const { |
5146 | return getType()->getPointerAddressSpace(); |
5147 | } |
5148 | |
5149 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5150 | static bool classof(const Instruction *I) { |
5151 | return I->getOpcode() == IntToPtr; |
5152 | } |
5153 | static bool classof(const Value *V) { |
5154 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5155 | } |
5156 | }; |
5157 | |
5158 | //===----------------------------------------------------------------------===// |
5159 | // PtrToIntInst Class |
5160 | //===----------------------------------------------------------------------===// |
5161 | |
5162 | /// This class represents a cast from a pointer to an integer. |
5163 | class PtrToIntInst : public CastInst { |
5164 | protected: |
5165 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5166 | friend class Instruction; |
5167 | |
5168 | /// Clone an identical PtrToIntInst. |
5169 | PtrToIntInst *cloneImpl() const; |
5170 | |
5171 | public: |
5172 | /// Constructor with insert-before-instruction semantics |
5173 | PtrToIntInst( |
5174 | Value *S, ///< The value to be converted |
5175 | Type *Ty, ///< The type to convert to |
5176 | const Twine &NameStr = "", ///< A name for the new instruction |
5177 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5178 | ); |
5179 | |
5180 | /// Constructor with insert-at-end-of-block semantics |
5181 | PtrToIntInst( |
5182 | Value *S, ///< The value to be converted |
5183 | Type *Ty, ///< The type to convert to |
5184 | const Twine &NameStr, ///< A name for the new instruction |
5185 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5186 | ); |
5187 | |
5188 | /// Gets the pointer operand. |
5189 | Value *getPointerOperand() { return getOperand(0); } |
5190 | /// Gets the pointer operand. |
5191 | const Value *getPointerOperand() const { return getOperand(0); } |
5192 | /// Gets the operand index of the pointer operand. |
5193 | static unsigned getPointerOperandIndex() { return 0U; } |
5194 | |
5195 | /// Returns the address space of the pointer operand. |
5196 | unsigned getPointerAddressSpace() const { |
5197 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
5198 | } |
5199 | |
5200 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5201 | static bool classof(const Instruction *I) { |
5202 | return I->getOpcode() == PtrToInt; |
5203 | } |
5204 | static bool classof(const Value *V) { |
5205 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5206 | } |
5207 | }; |
5208 | |
5209 | //===----------------------------------------------------------------------===// |
5210 | // BitCastInst Class |
5211 | //===----------------------------------------------------------------------===// |
5212 | |
5213 | /// This class represents a no-op cast from one type to another. |
5214 | class BitCastInst : public CastInst { |
5215 | protected: |
5216 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5217 | friend class Instruction; |
5218 | |
5219 | /// Clone an identical BitCastInst. |
5220 | BitCastInst *cloneImpl() const; |
5221 | |
5222 | public: |
5223 | /// Constructor with insert-before-instruction semantics |
5224 | BitCastInst( |
5225 | Value *S, ///< The value to be casted |
5226 | Type *Ty, ///< The type to casted to |
5227 | const Twine &NameStr = "", ///< A name for the new instruction |
5228 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5229 | ); |
5230 | |
5231 | /// Constructor with insert-at-end-of-block semantics |
5232 | BitCastInst( |
5233 | Value *S, ///< The value to be casted |
5234 | Type *Ty, ///< The type to casted to |
5235 | const Twine &NameStr, ///< A name for the new instruction |
5236 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5237 | ); |
5238 | |
5239 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5240 | static bool classof(const Instruction *I) { |
5241 | return I->getOpcode() == BitCast; |
5242 | } |
5243 | static bool classof(const Value *V) { |
5244 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5245 | } |
5246 | }; |
5247 | |
5248 | //===----------------------------------------------------------------------===// |
5249 | // AddrSpaceCastInst Class |
5250 | //===----------------------------------------------------------------------===// |
5251 | |
5252 | /// This class represents a conversion between pointers from one address space |
5253 | /// to another. |
5254 | class AddrSpaceCastInst : public CastInst { |
5255 | protected: |
5256 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5257 | friend class Instruction; |
5258 | |
5259 | /// Clone an identical AddrSpaceCastInst. |
5260 | AddrSpaceCastInst *cloneImpl() const; |
5261 | |
5262 | public: |
5263 | /// Constructor with insert-before-instruction semantics |
5264 | AddrSpaceCastInst( |
5265 | Value *S, ///< The value to be casted |
5266 | Type *Ty, ///< The type to casted to |
5267 | const Twine &NameStr = "", ///< A name for the new instruction |
5268 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5269 | ); |
5270 | |
5271 | /// Constructor with insert-at-end-of-block semantics |
5272 | AddrSpaceCastInst( |
5273 | Value *S, ///< The value to be casted |
5274 | Type *Ty, ///< The type to casted to |
5275 | const Twine &NameStr, ///< A name for the new instruction |
5276 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5277 | ); |
5278 | |
5279 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5280 | static bool classof(const Instruction *I) { |
5281 | return I->getOpcode() == AddrSpaceCast; |
5282 | } |
5283 | static bool classof(const Value *V) { |
5284 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5285 | } |
5286 | |
5287 | /// Gets the pointer operand. |
5288 | Value *getPointerOperand() { |
5289 | return getOperand(0); |
5290 | } |
5291 | |
5292 | /// Gets the pointer operand. |
5293 | const Value *getPointerOperand() const { |
5294 | return getOperand(0); |
5295 | } |
5296 | |
5297 | /// Gets the operand index of the pointer operand. |
5298 | static unsigned getPointerOperandIndex() { |
5299 | return 0U; |
5300 | } |
5301 | |
5302 | /// Returns the address space of the pointer operand. |
5303 | unsigned getSrcAddressSpace() const { |
5304 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
5305 | } |
5306 | |
5307 | /// Returns the address space of the result. |
5308 | unsigned getDestAddressSpace() const { |
5309 | return getType()->getPointerAddressSpace(); |
5310 | } |
5311 | }; |
5312 | |
5313 | //===----------------------------------------------------------------------===// |
5314 | // Helper functions |
5315 | //===----------------------------------------------------------------------===// |
5316 | |
5317 | /// A helper function that returns the pointer operand of a load or store |
5318 | /// instruction. Returns nullptr if not load or store. |
5319 | inline const Value *getLoadStorePointerOperand(const Value *V) { |
5320 | if (auto *Load = dyn_cast<LoadInst>(V)) |
5321 | return Load->getPointerOperand(); |
5322 | if (auto *Store = dyn_cast<StoreInst>(V)) |
5323 | return Store->getPointerOperand(); |
5324 | return nullptr; |
5325 | } |
5326 | inline Value *getLoadStorePointerOperand(Value *V) { |
5327 | return const_cast<Value *>( |
5328 | getLoadStorePointerOperand(static_cast<const Value *>(V))); |
5329 | } |
5330 | |
5331 | /// A helper function that returns the pointer operand of a load, store |
5332 | /// or GEP instruction. Returns nullptr if not load, store, or GEP. |
5333 | inline const Value *getPointerOperand(const Value *V) { |
5334 | if (auto *Ptr = getLoadStorePointerOperand(V)) |
5335 | return Ptr; |
5336 | if (auto *Gep = dyn_cast<GetElementPtrInst>(V)) |
5337 | return Gep->getPointerOperand(); |
5338 | return nullptr; |
5339 | } |
5340 | inline Value *getPointerOperand(Value *V) { |
5341 | return const_cast<Value *>(getPointerOperand(static_cast<const Value *>(V))); |
5342 | } |
5343 | |
5344 | /// A helper function that returns the alignment of load or store instruction. |
5345 | inline Align getLoadStoreAlignment(Value *I) { |
5346 | assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(static_cast <bool> ((isa<LoadInst>(I) || isa< StoreInst>(I)) && "Expected Load or Store instruction" ) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "llvm/include/llvm/IR/Instructions.h", 5347, __extension__ __PRETTY_FUNCTION__ )) |
5347 | "Expected Load or Store instruction")(static_cast <bool> ((isa<LoadInst>(I) || isa< StoreInst>(I)) && "Expected Load or Store instruction" ) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "llvm/include/llvm/IR/Instructions.h", 5347, __extension__ __PRETTY_FUNCTION__ )); |
5348 | if (auto *LI = dyn_cast<LoadInst>(I)) |
5349 | return LI->getAlign(); |
5350 | return cast<StoreInst>(I)->getAlign(); |
5351 | } |
5352 | |
5353 | /// A helper function that returns the address space of the pointer operand of |
5354 | /// load or store instruction. |
5355 | inline unsigned getLoadStoreAddressSpace(Value *I) { |
5356 | assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(static_cast <bool> ((isa<LoadInst>(I) || isa< StoreInst>(I)) && "Expected Load or Store instruction" ) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "llvm/include/llvm/IR/Instructions.h", 5357, __extension__ __PRETTY_FUNCTION__ )) |
5357 | "Expected Load or Store instruction")(static_cast <bool> ((isa<LoadInst>(I) || isa< StoreInst>(I)) && "Expected Load or Store instruction" ) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "llvm/include/llvm/IR/Instructions.h", 5357, __extension__ __PRETTY_FUNCTION__ )); |
5358 | if (auto *LI = dyn_cast<LoadInst>(I)) |
5359 | return LI->getPointerAddressSpace(); |
5360 | return cast<StoreInst>(I)->getPointerAddressSpace(); |
5361 | } |
5362 | |
5363 | /// A helper function that returns the type of a load or store instruction. |
5364 | inline Type *getLoadStoreType(Value *I) { |
5365 | assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(static_cast <bool> ((isa<LoadInst>(I) || isa< StoreInst>(I)) && "Expected Load or Store instruction" ) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "llvm/include/llvm/IR/Instructions.h", 5366, __extension__ __PRETTY_FUNCTION__ )) |
5366 | "Expected Load or Store instruction")(static_cast <bool> ((isa<LoadInst>(I) || isa< StoreInst>(I)) && "Expected Load or Store instruction" ) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "llvm/include/llvm/IR/Instructions.h", 5366, __extension__ __PRETTY_FUNCTION__ )); |
5367 | if (auto *LI = dyn_cast<LoadInst>(I)) |
5368 | return LI->getType(); |
5369 | return cast<StoreInst>(I)->getValueOperand()->getType(); |
5370 | } |
5371 | |
5372 | /// A helper function that returns an atomic operation's sync scope; returns |
5373 | /// None if it is not an atomic operation. |
5374 | inline Optional<SyncScope::ID> getAtomicSyncScopeID(const Instruction *I) { |
5375 | if (!I->isAtomic()) |
5376 | return None; |
5377 | if (auto *AI = dyn_cast<LoadInst>(I)) |
5378 | return AI->getSyncScopeID(); |
5379 | if (auto *AI = dyn_cast<StoreInst>(I)) |
5380 | return AI->getSyncScopeID(); |
5381 | if (auto *AI = dyn_cast<FenceInst>(I)) |
5382 | return AI->getSyncScopeID(); |
5383 | if (auto *AI = dyn_cast<AtomicCmpXchgInst>(I)) |
5384 | return AI->getSyncScopeID(); |
5385 | if (auto *AI = dyn_cast<AtomicRMWInst>(I)) |
5386 | return AI->getSyncScopeID(); |
5387 | llvm_unreachable("unhandled atomic operation")::llvm::llvm_unreachable_internal("unhandled atomic operation" , "llvm/include/llvm/IR/Instructions.h", 5387); |
5388 | } |
5389 | |
5390 | //===----------------------------------------------------------------------===// |
5391 | // FreezeInst Class |
5392 | //===----------------------------------------------------------------------===// |
5393 | |
5394 | /// This class represents a freeze function that returns random concrete |
5395 | /// value if an operand is either a poison value or an undef value |
5396 | class FreezeInst : public UnaryInstruction { |
5397 | protected: |
5398 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5399 | friend class Instruction; |
5400 | |
5401 | /// Clone an identical FreezeInst |
5402 | FreezeInst *cloneImpl() const; |
5403 | |
5404 | public: |
5405 | explicit FreezeInst(Value *S, |
5406 | const Twine &NameStr = "", |
5407 | Instruction *InsertBefore = nullptr); |
5408 | FreezeInst(Value *S, const Twine &NameStr, BasicBlock *InsertAtEnd); |
5409 | |
5410 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5411 | static inline bool classof(const Instruction *I) { |
5412 | return I->getOpcode() == Freeze; |
5413 | } |
5414 | static inline bool classof(const Value *V) { |
5415 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5416 | } |
5417 | }; |
5418 | |
5419 | } // end namespace llvm |
5420 | |
5421 | #endif // LLVM_IR_INSTRUCTIONS_H |