Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/CodeGen/CodeGenPrepare.cpp
Warning:line 1128, column 37
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name CodeGenPrepare.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -resource-dir /usr/lib/llvm-15/lib/clang/15.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/CodeGen -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/CodeGen -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-15/lib/clang/15.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/CodeGen/CodeGenPrepare.cpp
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
102using namespace llvm;
103using namespace llvm::PatternMatch;
104
105#define DEBUG_TYPE"codegenprepare" "codegenprepare"
106
107STATISTIC(NumBlocksElim, "Number of blocks eliminated")static llvm::Statistic NumBlocksElim = {"codegenprepare", "NumBlocksElim"
, "Number of blocks eliminated"}
;
108STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated")static llvm::Statistic NumPHIsElim = {"codegenprepare", "NumPHIsElim"
, "Number of trivial PHIs eliminated"}
;
109STATISTIC(NumGEPsElim, "Number of GEPs converted to casts")static llvm::Statistic NumGEPsElim = {"codegenprepare", "NumGEPsElim"
, "Number of GEPs converted to casts"}
;
110STATISTIC(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"
}
;
112STATISTIC(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"
}
;
114STATISTIC(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"
}
;
116STATISTIC(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"}
;
119STATISTIC(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"}
;
122STATISTIC(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"}
;
123STATISTIC(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"}
;
124STATISTIC(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"}
;
126STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized")static llvm::Statistic NumAndUses = {"codegenprepare", "NumAndUses"
, "Number of uses of and mask instructions optimized"}
;
127STATISTIC(NumRetsDup, "Number of return instructions duplicated")static llvm::Statistic NumRetsDup = {"codegenprepare", "NumRetsDup"
, "Number of return instructions duplicated"}
;
128STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved")static llvm::Statistic NumDbgValueMoved = {"codegenprepare", "NumDbgValueMoved"
, "Number of debug value instructions moved"}
;
129STATISTIC(NumSelectsExpanded, "Number of selects turned into branches")static llvm::Statistic NumSelectsExpanded = {"codegenprepare"
, "NumSelectsExpanded", "Number of selects turned into branches"
}
;
130STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed")static llvm::Statistic NumStoreExtractExposed = {"codegenprepare"
, "NumStoreExtractExposed", "Number of store(extractelement) exposed"
}
;
131
132static cl::opt<bool> DisableBranchOpts(
133 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
134 cl::desc("Disable branch optimizations in CodeGenPrepare"));
135
136static cl::opt<bool>
137 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
138 cl::desc("Disable GC optimizations in CodeGenPrepare"));
139
140static cl::opt<bool> DisableSelectToBranch(
141 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
142 cl::desc("Disable select to branch conversion."));
143
144static cl::opt<bool> AddrSinkUsingGEPs(
145 "addr-sink-using-gep", cl::Hidden, cl::init(true),
146 cl::desc("Address sinking in CGP using GEPs."));
147
148static cl::opt<bool> EnableAndCmpSinking(
149 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
150 cl::desc("Enable sinkinig and/cmp into branches."));
151
152static cl::opt<bool> DisableStoreExtract(
153 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
154 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
155
156static 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
160static 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
165static 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
170static cl::opt<bool> DisablePreheaderProtect(
171 "disable-preheader-prot", cl::Hidden, cl::init(false),
172 cl::desc("Disable protection against removing loop preheaders"));
173
174static 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
178static 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
189static 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
194static 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
198static cl::opt<bool>
199EnableTypePromotionMerge("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
203static 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
208static cl::opt<bool>
209AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
210 cl::desc("Allow creation of Phis in Address sinking."));
211
212static cl::opt<bool>
213AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
214 cl::desc("Allow creation of selects in Address sinking."));
215
216static 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
220static 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
224static 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
228static 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
232static 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
237static 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
241static 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
246static cl::opt<bool> OptimizePhiTypes(
247 "cgp-optimize-phi-types", cl::Hidden, cl::init(false),
248 cl::desc("Enable converting phi types in CodeGenPrepare"));
249
250namespace {
251
252enum 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
261using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
262using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
263using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
264using SExts = SmallVector<Instruction *, 16>;
265using ValueToSExts = DenseMap<Value *, SExts>;
266
267class 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
439char CodeGenPrepare::ID = 0;
440
441INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,static void *initializeCodeGenPreparePassOnce(PassRegistry &
Registry) {
442 "Optimize for code generation", false, false)static void *initializeCodeGenPreparePassOnce(PassRegistry &
Registry) {
443INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)initializeLoopInfoWrapperPassPass(Registry);
444INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)initializeProfileSummaryInfoWrapperPassPass(Registry);
445INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
446INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)initializeTargetPassConfigPass(Registry);
447INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry);
448INITIALIZE_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
451FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
452
453bool 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
624bool 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.
646void 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.
668void 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.
679bool 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.
721BasicBlock *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.
756bool 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
789bool 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.
878bool 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.
943void 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
1003static 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
1038static 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.
1054static bool
1055simplifyRelocatesOffABase(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();
7
Loop condition is false. Execution continues on line 1073
1065 &*R != RelocatedBase; ++R)
6
Assuming the condition is false
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) {
8
Assuming '__begin1' is not equal to '__end1'
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__
))
9
Assuming the condition is true
10
'?' condition is true
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()) {
11
Assuming the condition is false
12
Taking false branch
1077 // A duplicate relocate call. TODO: coalesce duplicates.
1078 continue;
1079 }
1080
1081 if (RelocatedBase->getParent() != ToReplace->getParent()) {
13
Assuming the condition is false
14
Taking false branch
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();
15
'Base' initialized here
1090 auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
16
Assuming the object is a 'GetElementPtrInst'
1091 if (!Derived
16.1
'Derived' is non-null
|| Derived->getPointerOperand() != Base)
17
Assuming pointer value is null
18
Taking false branch
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__
))
19
Taking false branch
20
Assuming the condition is true
21
'?' condition is true
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()) {
22
Called C++ object pointer is null
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'
1167bool 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)
1
Assuming the condition is false
2
Taking false branch
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())
3
Assuming the condition is false
4
Taking false branch
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);
5
Calling 'simplifyRelocatesOffABase'
1191 return MadeChange;
1192}
1193
1194/// Sink the specified cast instruction into its user blocks.
1195static 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.
1263static 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.)
1305bool 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.
1323static Optional<std::pair<Instruction *, Constant *> >
1324getIVIncrement(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
1339static 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
1353bool 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.
1435static 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.
1466bool 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
1498bool 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.
1567static 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.
1646static 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
1714bool 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.
1735static 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
1812static 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.
1827static bool
1828SinkShiftAndTruncate(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.
1917static 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.
2018static 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
2081bool 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
2309bool 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 && PN->getParent() != BB)
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
2418namespace {
2419
2420/// This is an extended version of TargetLowering::AddrMode
2421/// which holds actual Value*'s for register values.
2422struct 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
2549static 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)
2556void 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
2589LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void ExtAddrMode::dump() const {
2590 print(dbgs());
2591 dbgs() << '\n';
2592}
2593#endif
2594
2595namespace {
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.
2603class 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
2962public:
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
3008private:
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
3019void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3020 Value *NewVal) {
3021 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
3022 Inst, Idx, NewVal));
3023}
3024
3025void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3026 Value *NewVal) {
3027 Actions.push_back(
3028 std::make_unique<TypePromotionTransaction::InstructionRemover>(
3029 Inst, RemovedInsts, NewVal));
3030}
3031
3032void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3033 Value *New) {
3034 Actions.push_back(
3035 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3036}
3037
3038void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3039 Actions.push_back(
3040 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3041}
3042
3043Value *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
3051Value *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
3059Value *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
3067void TypePromotionTransaction::moveBefore(Instruction *Inst,
3068 Instruction *Before) {
3069 Actions.push_back(
3070 std::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
3071 Inst, Before));
3072}
3073
3074TypePromotionTransaction::ConstRestorationPt
3075TypePromotionTransaction::getRestorationPoint() const {
3076 return !Actions.empty() ? Actions.back().get() : nullptr;
3077}
3078
3079bool 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
3087void 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
3095namespace {
3096
3097/// A helper class for matching addressing modes.
3098///
3099/// This encapsulates the logic for matching the target-legal addressing modes.
3100class 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
3157public:
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
3184private:
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
3197class PhiNodeSet;
3198
3199/// An iterator for PhiNodeSet.
3200class PhiNodeSetIterator {
3201 PhiNodeSet * const Set;
3202 size_t CurrentIndex = 0;
3203
3204public:
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.
3224class 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
3245public:
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
3296private:
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
3314PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
3315 : Set(Set), CurrentIndex(Start) {}
3316
3317PHINode * 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
3323PhiNodeSetIterator& 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
3331bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
3332 return CurrentIndex == RHS.CurrentIndex;
3333}
3334
3335bool 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.
3342class 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
3351public:
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.
3433class AddressingModeCombiner {
3434 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
3435 typedef std::pair<PHINode *, PHINode *> PHIPair;
3436
3437private:
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
3456public:
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
3552private:
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.
3844bool 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.
3969static 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.
4000static 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
4014namespace {
4015
4016/// Hepler class to perform type promotion.
4017class 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
4125public:
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
4150bool 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
4252TypePromotionHelper::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
4285Value *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
4333Value *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.
4442bool 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.
4470bool 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///
4743bool 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.
4826static 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.
4850static 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.
4855static 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.
4933bool 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.
4976bool AddressingModeMatcher::
4977isProfitableToFoldIntoAddressingMode(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.
5062static 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.).
5087bool 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.
5472bool 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.
5609bool 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.
5635static 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.
5688bool 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.
573